1
0
Fork 0
forked from svrjs/svrjs

Lint out the codebase

This commit is contained in:
Dorian Niemiec 2024-08-26 19:23:52 +02:00
parent 488bee1a95
commit 2f783ce1a2
13 changed files with 326 additions and 273 deletions

View file

@ -268,11 +268,11 @@ function clientErrorHandler(err, socket) {
.replace( .replace(
/{errorMessage}/g, /{errorMessage}/g,
errorCode.toString() + errorCode.toString() +
" " + " " +
http.STATUS_CODES[errorCode] http.STATUS_CODES[errorCode]
.replace(/&/g, "&") .replace(/&/g, "&")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") .replace(/>/g, "&gt;"),
) )
.replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode]) .replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode])
.replace( .replace(
@ -284,7 +284,7 @@ function clientErrorHandler(err, socket) {
.replace(/\r\n/g, "<br/>") .replace(/\r\n/g, "<br/>")
.replace(/\n/g, "<br/>") .replace(/\n/g, "<br/>")
.replace(/\r/g, "<br/>") .replace(/\r/g, "<br/>")
.replace(/ {2}/g, "&nbsp;&nbsp;") .replace(/ {2}/g, "&nbsp;&nbsp;"),
) )
.replace( .replace(
/{server}/g, /{server}/g,
@ -296,7 +296,7 @@ function clientErrorHandler(err, socket) {
) )
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") .replace(/>/g, "&gt;"),
) )
.replace( .replace(
/{contact}/g, /{contact}/g,
@ -305,7 +305,7 @@ function clientErrorHandler(err, socket) {
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") .replace(/>/g, "&gt;")
.replace(/\./g, "[dot]") .replace(/\./g, "[dot]")
.replace(/@/g, "[at]") .replace(/@/g, "[at]"),
)}`, )}`,
); );
res.end(); res.end();
@ -377,11 +377,11 @@ function clientErrorHandler(err, socket) {
} }
res.writeHead(errorCode, http.STATUS_CODES[errorCode], cheaders); res.writeHead(errorCode, http.STATUS_CODES[errorCode], cheaders);
res.write( res.write(
( `<!DOCTYPE html><html><head><title>{errorMessage}</title><meta name="viewport" content="width=device-width, initial-scale=1.0" /><style>${defaultPageCSS}</style></head><body><h1>{errorMessage}</h1><p>{errorDesc}</p>${
`<!DOCTYPE html><html><head><title>{errorMessage}</title><meta name="viewport" content="width=device-width, initial-scale=1.0" /><style>${defaultPageCSS}</style></head><body><h1>{errorMessage}</h1><p>{errorDesc}</p>${additionalError == 404 additionalError == 404
? "" ? ""
: "<p>Additionally, a {additionalError} error occurred while loading an error page.</p>"}<p><i>{server}</i></p></body></html>` : "<p>Additionally, a {additionalError} error occurred while loading an error page.</p>"
) }<p><i>{server}</i></p></body></html>`
.replace( .replace(
/{errorMessage}/g, /{errorMessage}/g,
errorCode.toString() + errorCode.toString() +
@ -438,16 +438,19 @@ function clientErrorHandler(err, socket) {
process.reqcounter++; process.reqcounter++;
process.malformedcounter++; process.malformedcounter++;
logFacilities.locmessage( logFacilities.locmessage(
`Somebody connected to ${config.secure && fromMain `Somebody connected to ${
? (typeof config.sport == "number" ? "port " : "socket ") + config.sport config.secure && fromMain
: (typeof config.port == "number" ? "port " : "socket ") + ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport
config.port}...`, : (typeof config.port == "number" ? "port " : "socket ") + config.port
}...`,
); );
logFacilities.reqmessage( logFacilities.reqmessage(
`Client ${!reqip || reqip == "" `Client ${
? "[unknown client]" !reqip || reqip == ""
: reqip + ? "[unknown client]"
(reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")} sent invalid request.`, : reqip +
(reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")
} sent invalid request.`,
); );
try { try {
head = fs.existsSync("./.head") head = fs.existsSync("./.head")

View file

@ -33,16 +33,19 @@ function noproxyHandler(req, socket, head) {
var reqport = socket.remotePort; var reqport = socket.remotePort;
process.reqcounter++; process.reqcounter++;
logFacilities.locmessage( logFacilities.locmessage(
`Somebody connected to ${config.secure `Somebody connected to ${
? (typeof config.sport == "number" ? "port " : "socket ") + config.sport config.secure
: (typeof config.port == "number" ? "port " : "socket ") + ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport
config.port}...`, : (typeof config.port == "number" ? "port " : "socket ") + config.port
}...`,
); );
logFacilities.reqmessage( logFacilities.reqmessage(
`Client ${!reqip || reqip == "" `Client ${
? "[unknown client]" !reqip || reqip == ""
: reqip + ? "[unknown client]"
(reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")} wants to proxy ${req.url} through this server`, : reqip +
(reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")
} wants to proxy ${req.url} through this server`,
); );
if (req.headers["user-agent"] != undefined) if (req.headers["user-agent"] != undefined)
logFacilities.reqmessage("Client uses " + req.headers["user-agent"]); logFacilities.reqmessage("Client uses " + req.headers["user-agent"]);

View file

@ -39,16 +39,19 @@ function proxyHandler(req, socket, head) {
var reqport = socket.remotePort; var reqport = socket.remotePort;
process.reqcounter++; process.reqcounter++;
logFacilities.locmessage( logFacilities.locmessage(
`Somebody connected to ${config.secure `Somebody connected to ${
? (typeof config.sport == "number" ? "port " : "socket ") + config.sport config.secure
: (typeof config.port == "number" ? "port " : "socket ") + ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport
config.port}...`, : (typeof config.port == "number" ? "port " : "socket ") + config.port
}...`,
); );
logFacilities.reqmessage( logFacilities.reqmessage(
`Client ${!reqip || reqip == "" `Client ${
? "[unknown client]" !reqip || reqip == ""
: reqip + ? "[unknown client]"
(reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")} wants to proxy ${req.url} through this server`, : reqip +
(reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")
} wants to proxy ${req.url} through this server`,
); );
if (req.headers["user-agent"] != undefined) if (req.headers["user-agent"] != undefined)
logFacilities.reqmessage("Client uses " + req.headers["user-agent"]); logFacilities.reqmessage("Client uses " + req.headers["user-agent"]);

View file

@ -134,9 +134,7 @@ function requestHandler(req, res) {
req.socket.remoteAddress == "::1" || req.socket.remoteAddress == "::1" ||
req.socket.remoteAddress == "::ffff:127.0.0.1" || req.socket.remoteAddress == "::ffff:127.0.0.1" ||
req.socket.remoteAddress == "127.0.0.1" || req.socket.remoteAddress == "127.0.0.1" ||
req.socket.remoteAddress == "localhost" || req.socket.remoteAddress == "localhost")
req.socket.remoteAddress == host ||
req.socket.remoteAddress == "::ffff:" + host)
) { ) {
let headers = config.getCustomHeaders(); let headers = config.getCustomHeaders();
res.writeHead(204, http.STATUS_CODES[204], headers); res.writeHead(204, http.STATUS_CODES[204], headers);
@ -204,10 +202,11 @@ function requestHandler(req, res) {
req.isProxy = false; req.isProxy = false;
if (req.url[0] != "/" && req.url != "*") req.isProxy = true; if (req.url[0] != "/" && req.url != "*") req.isProxy = true;
logFacilities.locmessage( logFacilities.locmessage(
`Somebody connected to ${config.secure && fromMain `Somebody connected to ${
? (typeof config.sport == "number" ? "port " : "socket ") + config.sport config.secure && fromMain
: (typeof config.port == "number" ? "port " : "socket ") + ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport
config.port}...`, : (typeof config.port == "number" ? "port " : "socket ") + config.port
}...`,
); );
if (req.socket == null) { if (req.socket == null) {
@ -267,10 +266,13 @@ function requestHandler(req, res) {
} }
logFacilities.reqmessage( logFacilities.reqmessage(
`Client ${!reqip || reqip == "" `Client ${
? "[unknown client]" !reqip || reqip == ""
: reqip + ? "[unknown client]"
(reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")} wants ${req.method == "GET" : reqip +
(reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")
} wants ${
req.method == "GET"
? "content in " ? "content in "
: req.method == "POST" : req.method == "POST"
? "to post content in " ? "to post content in "
@ -280,7 +282,8 @@ function requestHandler(req, res) {
? "to delete content in " ? "to delete content in "
: req.method == "PATCH" : req.method == "PATCH"
? "to patch content in " ? "to patch content in "
: "to access content using " + req.method + " method in "}${req.headers.host == undefined || req.isProxy ? "" : req.headers.host}${req.url}`, : "to access content using " + req.method + " method in "
}${req.headers.host == undefined || req.isProxy ? "" : req.headers.host}${req.url}`,
); );
if (req.headers["user-agent"] != undefined) if (req.headers["user-agent"] != undefined)
logFacilities.reqmessage("Client uses " + req.headers["user-agent"]); logFacilities.reqmessage("Client uses " + req.headers["user-agent"]);
@ -528,11 +531,11 @@ function requestHandler(req, res) {
res.writeHead(errorCode, http.STATUS_CODES[errorCode], cheaders); res.writeHead(errorCode, http.STATUS_CODES[errorCode], cheaders);
res.write( res.write(
( `<!DOCTYPE html><html><head><title>{errorMessage}</title><meta name="viewport" content="width=device-width, initial-scale=1.0" /><style>${defaultPageCSS}</style></head><body><h1>{errorMessage}</h1><p>{errorDesc}</p>${
`<!DOCTYPE html><html><head><title>{errorMessage}</title><meta name="viewport" content="width=device-width, initial-scale=1.0" /><style>${defaultPageCSS}</style></head><body><h1>{errorMessage}</h1><p>{errorDesc}</p>${additionalError == 404 additionalError == 404
? "" ? ""
: "<p>Additionally, a {additionalError} error occurred while loading an error page.</p>"}<p><i>{server}</i></p></body></html>` : "<p>Additionally, a {additionalError} error occurred while loading an error page.</p>"
) }<p><i>{server}</i></p></body></html>`
.replace( .replace(
/{errorMessage}/g, /{errorMessage}/g,
errorCode.toString() + errorCode.toString() +

View file

@ -657,8 +657,7 @@ if (!disableMods) {
if (mod.modInfo) modInfos.push(mod.modInfo); if (mod.modInfo) modInfos.push(mod.modInfo);
else { else {
modInfos.push({ modInfos.push({
name: name: `Unknown mod (${modFileRaw}; module.exports.modInfo not set)`,
`Unknown mod (${modFileRaw}; module.exports.modInfo not set)`,
version: "ERROR", version: "ERROR",
}); });
} }
@ -772,12 +771,15 @@ if (!disableMods) {
if (fs.existsSync(SSJSPath) && fs.statSync(SSJSPath).isFile()) { if (fs.existsSync(SSJSPath) && fs.statSync(SSJSPath).isFile()) {
try { try {
// Prepend necessary modules and variables to the custom server side script // Prepend necessary modules and variables to the custom server side script
const modhead = const modhead = `var readline = require('readline');\r\nvar os = require('os');\r\nvar http = require('http');\r\nvar url = require('url');\r\nvar fs = require('fs');\r\nvar path = require('path');\r\n${
`var readline = require('readline');\r\nvar os = require('os');\r\nvar http = require('http');\r\nvar url = require('url');\r\nvar fs = require('fs');\r\nvar path = require('path');\r\n${hexstrbase64 === undefined hexstrbase64 === undefined
? "" ? ""
: "var hexstrbase64 = require('../hexstrbase64/index.js');\r\n"}${crypto.__disabled__ === undefined : "var hexstrbase64 = require('../hexstrbase64/index.js');\r\n"
? "var crypto = require('crypto');\r\nvar https = require('https');\r\n" }${
: ""}var stream = require(\'stream\');\r\nvar customvar1;\r\nvar customvar2;\r\nvar customvar3;\r\nvar customvar4;\r\n\r\nfunction Mod() {}\r\nMod.prototype.callback = function callback(req, res, serverconsole, responseEnd, href, ext, uobject, search, defaultpage, users, page404, head, foot, fd, elseCallback, configJSON, callServerError, getCustomHeaders, origHref, redirect, parsePostData, authUser) {\r\nreturn function () {\r\nvar disableEndElseCallbackExecute = false;\r\nfunction filterHeaders(e){var r={};return Object.keys(e).forEach((function(t){null!==e[t]&&void 0!==e[t]&&("object"==typeof e[t]?r[t]=JSON.parse(JSON.stringify(e[t])):r[t]=e[t])})),r}\r\nfunction checkHostname(e){if(void 0===e||"*"==e)return!0;if(req.headers.host&&0==e.indexOf("*.")&&"*."!=e){var r=e.substring(2);if(req.headers.host==r||req.headers.host.indexOf("."+r)==req.headers.host.length-r.length-1)return!0}else if(req.headers.host&&req.headers.host==e)return!0;return!1}\r\nfunction checkHref(e){return href==e||"win32"==os.platform()&&href.toLowerCase()==e.toLowerCase()}\r\n`; crypto.__disabled__ === undefined
? "var crypto = require('crypto');\r\nvar https = require('https');\r\n"
: ""
}var stream = require(\'stream\');\r\nvar customvar1;\r\nvar customvar2;\r\nvar customvar3;\r\nvar customvar4;\r\n\r\nfunction Mod() {}\r\nMod.prototype.callback = function callback(req, res, serverconsole, responseEnd, href, ext, uobject, search, defaultpage, users, page404, head, foot, fd, elseCallback, configJSON, callServerError, getCustomHeaders, origHref, redirect, parsePostData, authUser) {\r\nreturn function () {\r\nvar disableEndElseCallbackExecute = false;\r\nfunction filterHeaders(e){var r={};return Object.keys(e).forEach((function(t){null!==e[t]&&void 0!==e[t]&&("object"==typeof e[t]?r[t]=JSON.parse(JSON.stringify(e[t])):r[t]=e[t])})),r}\r\nfunction checkHostname(e){if(void 0===e||"*"==e)return!0;if(req.headers.host&&0==e.indexOf("*.")&&"*."!=e){var r=e.substring(2);if(req.headers.host==r||req.headers.host.indexOf("."+r)==req.headers.host.length-r.length-1)return!0}else if(req.headers.host&&req.headers.host==e)return!0;return!1}\r\nfunction checkHref(e){return href==e||"win32"==os.platform()&&href.toLowerCase()==e.toLowerCase()}\r\n`;
const modfoot = const modfoot =
"\r\nif(!disableEndElseCallbackExecute) {\r\ntry{\r\nelseCallback();\r\n} catch(err) {\r\n}\r\n}\r\n}\r\n}\r\nmodule.exports = Mod;"; "\r\nif(!disableEndElseCallbackExecute) {\r\ntry{\r\nelseCallback();\r\n} catch(err) {\r\n}\r\n}\r\n}\r\n}\r\nmodule.exports = Mod;";
// Write the modified server side script to the temp folder // Write the modified server side script to the temp folder
@ -872,9 +874,11 @@ function listeningMessage() {
if (process.serverConfig.secure && (sListenToLocalhost || sListenToAny)) { if (process.serverConfig.secure && (sListenToLocalhost || sListenToAny)) {
if (typeof process.serverConfig.sport === "number") { if (typeof process.serverConfig.sport === "number") {
serverconsole.locmessage( serverconsole.locmessage(
`* https://localhost${process.serverConfig.sport == 443 `* https://localhost${
? "" process.serverConfig.sport == 443
: ":" + process.serverConfig.sport}`, ? ""
: ":" + process.serverConfig.sport
}`,
); );
} else { } else {
serverconsole.locmessage("* " + process.serverConfig.sport); // Unix socket or Windows named pipe serverconsole.locmessage("* " + process.serverConfig.sport); // Unix socket or Windows named pipe
@ -889,9 +893,9 @@ function listeningMessage() {
) { ) {
if (typeof process.serverConfig.port === "number") { if (typeof process.serverConfig.port === "number") {
serverconsole.locmessage( serverconsole.locmessage(
`* http://localhost${process.serverConfig.port == 80 `* http://localhost${
? "" process.serverConfig.port == 80 ? "" : ":" + process.serverConfig.port
: ":" + process.serverConfig.port}`, }`,
); );
} else { } else {
serverconsole.locmessage("* " + process.serverConfig.port); // Unix socket or Windows named pipe serverconsole.locmessage("* " + process.serverConfig.port); // Unix socket or Windows named pipe
@ -904,9 +908,11 @@ function listeningMessage() {
(!sListenToAny || (host != "" && host != "[offline]")) (!sListenToAny || (host != "" && host != "[offline]"))
) )
serverconsole.locmessage( serverconsole.locmessage(
`* https://${sAccHost.indexOf(":") > -1 ? "[" + sAccHost + "]" : sAccHost}${process.serverConfig.sport == 443 `* https://${sAccHost.indexOf(":") > -1 ? "[" + sAccHost + "]" : sAccHost}${
? "" process.serverConfig.sport == 443
: ":" + process.serverConfig.sport}`, ? ""
: ":" + process.serverConfig.sport
}`,
); );
if ( if (
!( !(
@ -918,17 +924,19 @@ function listeningMessage() {
typeof process.serverConfig.port === "number" typeof process.serverConfig.port === "number"
) )
serverconsole.locmessage( serverconsole.locmessage(
`* http://${accHost.indexOf(":") > -1 ? "[" + accHost + "]" : accHost}${process.serverConfig.port == 80 `* http://${accHost.indexOf(":") > -1 ? "[" + accHost + "]" : accHost}${
? "" process.serverConfig.port == 80 ? "" : ":" + process.serverConfig.port
: ":" + process.serverConfig.port}`, }`,
); );
ipStatusCallback(() => { ipStatusCallback(() => {
if (pubip != "") { if (pubip != "") {
if (process.serverConfig.secure && !sListenToLocalhost) if (process.serverConfig.secure && !sListenToLocalhost)
serverconsole.locmessage( serverconsole.locmessage(
`* https://${pubip.indexOf(":") > -1 ? "[" + pubip + "]" : pubip}${process.serverConfig.spubport == 443 `* https://${pubip.indexOf(":") > -1 ? "[" + pubip + "]" : pubip}${
? "" process.serverConfig.spubport == 443
: ":" + process.serverConfig.spubport}`, ? ""
: ":" + process.serverConfig.spubport
}`,
); );
if ( if (
!( !(
@ -938,17 +946,21 @@ function listeningMessage() {
!listenToLocalhost !listenToLocalhost
) )
serverconsole.locmessage( serverconsole.locmessage(
`* http://${pubip.indexOf(":") > -1 ? "[" + pubip + "]" : pubip}${process.serverConfig.pubport == 80 `* http://${pubip.indexOf(":") > -1 ? "[" + pubip + "]" : pubip}${
? "" process.serverConfig.pubport == 80
: ":" + process.serverConfig.pubport}`, ? ""
: ":" + process.serverConfig.pubport
}`,
); );
} }
if (domain != "") { if (domain != "") {
if (process.serverConfig.secure && !sListenToLocalhost) if (process.serverConfig.secure && !sListenToLocalhost)
serverconsole.locmessage( serverconsole.locmessage(
`* https://${domain}${process.serverConfig.spubport == 443 `* https://${domain}${
? "" process.serverConfig.spubport == 443
: ":" + process.serverConfig.spubport}`, ? ""
: ":" + process.serverConfig.spubport
}`,
); );
if ( if (
!( !(
@ -958,9 +970,11 @@ function listeningMessage() {
!listenToLocalhost !listenToLocalhost
) )
serverconsole.locmessage( serverconsole.locmessage(
`* http://${domain}${process.serverConfig.pubport == 80 `* http://${domain}${
? "" process.serverConfig.pubport == 80
: ":" + process.serverConfig.pubport}`, ? ""
: ":" + process.serverConfig.pubport
}`,
); );
} }
serverconsole.locmessage('For CLI help, you can type "help"'); serverconsole.locmessage('For CLI help, you can type "help"');
@ -1248,9 +1262,7 @@ let commands = {
mods: (args, log) => { mods: (args, log) => {
log("Mods:"); log("Mods:");
for (let i = 0; i < modInfos.length; i++) { for (let i = 0; i < modInfos.length; i++) {
log( log(`${(i + 1).toString()}. ${modInfos[i].name} ${modInfos[i].version}`);
`${(i + 1).toString()}. ${modInfos[i].name} ${modInfos[i].version}`,
);
} }
if (modInfos.length == 0) { if (modInfos.length == 0) {
log("No mods installed."); log("No mods installed.");
@ -1823,23 +1835,27 @@ function start(init) {
) )
) )
serverconsole.locmessage( serverconsole.locmessage(
`Starting HTTP server at ${typeof process.serverConfig.port == "number" `Starting HTTP server at ${
? listenAddress typeof process.serverConfig.port == "number"
? (listenAddress.indexOf(":") > -1 ? listenAddress
? "[" + listenAddress + "]" ? (listenAddress.indexOf(":") > -1
: listenAddress) + ":" ? "[" + listenAddress + "]"
: "port " : listenAddress) + ":"
: ""}${process.serverConfig.port.toString()}...`, : "port "
: ""
}${process.serverConfig.port.toString()}...`,
); );
if (process.serverConfig.secure) if (process.serverConfig.secure)
serverconsole.locmessage( serverconsole.locmessage(
`Starting HTTPS server at ${typeof process.serverConfig.sport == "number" `Starting HTTPS server at ${
? sListenAddress typeof process.serverConfig.sport == "number"
? (sListenAddress.indexOf(":") > -1 ? sListenAddress
? "[" + sListenAddress + "]" ? (sListenAddress.indexOf(":") > -1
: sListenAddress) + ":" ? "[" + sListenAddress + "]"
: "port " : sListenAddress) + ":"
: ""}${process.serverConfig.sport.toString()}...`, : "port "
: ""
}${process.serverConfig.sport.toString()}...`,
); );
} }
@ -1997,9 +2013,7 @@ function start(init) {
} }
} catch (err) { } catch (err) {
if (line != "") { if (line != "") {
process.send( process.send(`Can't execute command \"${line.split(" ")[0]}".`);
`Can't execute command \"${line.split(" ")[0]}".`,
);
process.send("\x12END"); process.send("\x12END");
} }
} }
@ -2065,9 +2079,7 @@ function start(init) {
cluster.workers[clusterID].removeAllListeners("message"); cluster.workers[clusterID].removeAllListeners("message");
addListenersToWorker(cluster.workers[clusterID]); addListenersToWorker(cluster.workers[clusterID]);
} }
serverconsole.climessage( serverconsole.climessage(`Can't run command "${command}".`);
`Can't run command "${command}".`,
);
} }
}); });
if (command == "stop") { if (command == "stop") {

View file

@ -12,14 +12,17 @@ module.exports = (req, res, logFacilities, config, next) => {
`<!DOCTYPE html><html><head><title>Proxy not implemented</title><meta name="viewport" content="width=device-width, initial-scale=1.0" /><style>${defaultPageCSS}</style></head><body><h1>Proxy not implemented</h1><p>${name `<!DOCTYPE html><html><head><title>Proxy not implemented</title><meta name="viewport" content="width=device-width, initial-scale=1.0" /><style>${defaultPageCSS}</style></head><body><h1>Proxy not implemented</h1><p>${name
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;")} doesn't support proxy without proxy mod. If you're administator of this server, then install this mod in order to use ${name .replace(
.replace(/&/g, "&amp;") />/g,
.replace(/</g, "&lt;") "&gt;",
.replace(/>/g, "&gt;")} as a proxy.</p><p><i>${config )} doesn't support proxy without proxy mod. If you're administator of this server, then install this mod in order to use ${name
.generateServerString() .replace(/&/g, "&amp;")
.replace(/&/g, "&amp;") .replace(/</g, "&lt;")
.replace(/</g, "&lt;") .replace(/>/g, "&gt;")} as a proxy.</p><p><i>${config
.replace(/>/g, "&gt;")}</i></p></body></html>`, .generateServerString()
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")}</i></p></body></html>`,
); );
res.end(); res.end();
logFacilities.errmessage( logFacilities.errmessage(

View file

@ -269,10 +269,11 @@ module.exports = (req, res, logFacilities, config, next) => {
const authorizedCallback = (bruteProtection) => { const authorizedCallback = (bruteProtection) => {
try { try {
const ha = config.getCustomHeaders(); const ha = config.getCustomHeaders();
ha["WWW-Authenticate"] = ha["WWW-Authenticate"] = `Basic realm="${
`Basic realm="${authcode.realm authcode.realm
? authcode.realm.replace(/(\\|")/g, "\\$1") ? authcode.realm.replace(/(\\|")/g, "\\$1")
: name + " HTTP Basic Authorization"}", charset="UTF-8"`; : name + " HTTP Basic Authorization"
}", charset="UTF-8"`;
const credentials = req.headers["authorization"]; const credentials = req.headers["authorization"];
if (!credentials) { if (!credentials) {
res.error(401, ha); res.error(401, ha);

View file

@ -86,18 +86,18 @@ module.exports = (req, res, logFacilities, config, next) => {
return; return;
} }
if (rewrittenURL != req.url) { if (rewrittenURL != req.url) {
logFacilities.resmessage( logFacilities.resmessage(`URL rewritten: ${req.url} => ${rewrittenURL}`);
`URL rewritten: ${req.url} => ${rewrittenURL}`,
);
req.url = rewrittenURL; req.url = rewrittenURL;
try { try {
req.parsedURL = new URL( req.parsedURL = new URL(
req.url, req.url,
`http${req.socket.encrypted ? "s" : ""}://${req.headers.host `http${req.socket.encrypted ? "s" : ""}://${
? req.headers.host req.headers.host
: config.domain ? req.headers.host
? config.domain : config.domain
: "unknown.invalid"}`, ? config.domain
: "unknown.invalid"
}`,
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);
@ -131,11 +131,13 @@ module.exports = (req, res, logFacilities, config, next) => {
try { try {
req.parsedURL = new URL( req.parsedURL = new URL(
req.url, req.url,
`http${req.socket.encrypted ? "s" : ""}://${req.headers.host `http${req.socket.encrypted ? "s" : ""}://${
? req.headers.host req.headers.host
: config.domain ? req.headers.host
? config.domain : config.domain
: "unknown.invalid"}`, ? config.domain
: "unknown.invalid"
}`,
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);

View file

@ -580,58 +580,66 @@ module.exports = (req, res, logFacilities, config, next) => {
); );
// Generate HTML head and footer based on configuration and custom content // Generate HTML head and footer based on configuration and custom content
let htmlHead = let htmlHead = `${
`${(!config.enableDirectoryListingWithDefaultHead || res.head == "" (!config.enableDirectoryListingWithDefaultHead || res.head == ""
? !headerHasHTMLTag ? !headerHasHTMLTag
? "<!DOCTYPE html><html><head><title>Directory: " + ? "<!DOCTYPE html><html><head><title>Directory: " +
decodeURIComponent(origHref)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;") +
'</title><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><style>' +
defaultPageCSS +
"</style></head><body>"
: customDirListingHeader.replace(
/<head>/i,
"<head><title>Directory: " +
decodeURIComponent(origHref) decodeURIComponent(origHref)
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") + .replace(/>/g, "&gt;") +
"</title>" '</title><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><style>' +
) defaultPageCSS +
"</style></head><body>"
: customDirListingHeader.replace(
/<head>/i,
"<head><title>Directory: " +
decodeURIComponent(origHref)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;") +
"</title>",
)
: res.head.replace( : res.head.replace(
/<head>/i, /<head>/i,
"<head><title>Directory: " + "<head><title>Directory: " +
decodeURIComponent(origHref) decodeURIComponent(origHref)
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") + .replace(/>/g, "&gt;") +
"</title>" "</title>",
)) + )) + (!headerHasHTMLTag ? customDirListingHeader : "")
(!headerHasHTMLTag ? customDirListingHeader : "")}<h1>Directory: ${decodeURIComponent(origHref) }<h1>Directory: ${decodeURIComponent(origHref)
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;")}</h1><table id="directoryListing"> <tr> <th></th> <th>Filename</th> <th>Size</th> <th>Date</th> </tr>${checkPathLevel(decodeURIComponent(origHref)) < 1 .replace(
? "" />/g,
: '<tr><td style="width: 24px;"><img src="/.dirimages/return.png" width="24px" height="24px" alt="[RET]" /></td><td style="word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;"><a href="' + "&gt;",
)}</h1><table id="directoryListing"> <tr> <th></th> <th>Filename</th> <th>Size</th> <th>Date</th> </tr>${
checkPathLevel(decodeURIComponent(origHref)) < 1
? ""
: '<tr><td style="width: 24px;"><img src="/.dirimages/return.png" width="24px" height="24px" alt="[RET]" /></td><td style="word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;"><a href="' +
origHref.replace(/\/+/g, "/").replace(/\/[^\/]*\/?$/, "/") + origHref.replace(/\/+/g, "/").replace(/\/[^\/]*\/?$/, "/") +
'">Return</a></td><td></td><td></td></tr>'}`; '">Return</a></td><td></td><td></td></tr>'
}`;
let htmlFoot = let htmlFoot = `</table><p><i>${config
`</table><p><i>${config .generateServerString()
.generateServerString() .replace(/&/g, "&amp;")
.replace(/&/g, "&amp;") .replace(/</g, "&lt;")
.replace(/</g, "&lt;") .replace(/>/g, "&gt;")}${
.replace(/>/g, "&gt;")}${req.headers.host == undefined req.headers.host == undefined
? "" ? ""
: " on " + : " on " +
String(req.headers.host) String(req.headers.host)
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;")}</i></p>${customDirListingFooter}${!config.enableDirectoryListingWithDefaultHead || res.foot == "" .replace(/>/g, "&gt;")
? "</body></html>" }</i></p>${customDirListingFooter}${
: res.foot}`; !config.enableDirectoryListingWithDefaultHead || res.foot == ""
? "</body></html>"
: res.foot
}`;
if ( if (
fs.existsSync( fs.existsSync(
@ -736,26 +744,34 @@ module.exports = (req, res, logFacilities, config, next) => {
const emime = eext ? mime.contentType(eext) : false; const emime = eext ? mime.contentType(eext) : false;
if (filelist[i].errored) { if (filelist[i].errored) {
directoryListingRows.push( directoryListingRows.push(
`<tr><td style="width: 24px;"><img src="/.dirimages/bad.png" alt="[BAD]" width="24px" height="24px" /></td><td style="word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;"><a href="${(href + "/" + encodeURI(ename)).replace( `<tr><td style="width: 24px;"><img src="/.dirimages/bad.png" alt="[BAD]" width="24px" height="24px" /></td><td style="word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;"><a href="${(
/\/+/g, href +
"/" "/" +
)}">${ename encodeURI(ename)
).replace(/\/+/g, "/")}">${ename
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;")}</a></td><td>-</td><td>${estats ? estats.mtime.toDateString() : "-"}</td></tr>\r\n`, .replace(
/>/g,
"&gt;",
)}</a></td><td>-</td><td>${estats ? estats.mtime.toDateString() : "-"}</td></tr>\r\n`,
); );
} else { } else {
let entry = let entry = `<tr><td style="width: 24px;"><img src="[img]" alt="[alt]" width="24px" height="24px" /></td><td style="word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;"><a href="${(
`<tr><td style="width: 24px;"><img src="[img]" alt="[alt]" width="24px" height="24px" /></td><td style="word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;"><a href="${( origHref +
origHref + "/" +
"/" + encodeURIComponent(ename)
encodeURIComponent(ename) ).replace(
).replace(/\/+/g, "/")}${estats.isDirectory() ? "/" : ""}">${ename /\/+/g,
.replace(/&/g, "&amp;") "/",
.replace(/</g, "&lt;") )}${estats.isDirectory() ? "/" : ""}">${ename
.replace(/>/g, "&gt;")}</a></td><td>${estats.isDirectory() .replace(/&/g, "&amp;")
? "-" .replace(/</g, "&lt;")
: sizify(estats.size.toString())}</td><td>${estats.mtime.toDateString()}</td></tr>\r\n`; .replace(/>/g, "&gt;")}</a></td><td>${
estats.isDirectory()
? "-"
: sizify(estats.size.toString())
}</td><td>${estats.mtime.toDateString()}</td></tr>\r\n`;
// Determine the file type and set the appropriate image and alt text // Determine the file type and set the appropriate image and alt text
if (estats.isDirectory()) { if (estats.isDirectory()) {
@ -763,15 +779,17 @@ module.exports = (req, res, logFacilities, config, next) => {
.replace("[img]", "/.dirimages/directory.png") .replace("[img]", "/.dirimages/directory.png")
.replace("[alt]", "[DIR]"); .replace("[alt]", "[DIR]");
} else if (!estats.isFile()) { } else if (!estats.isFile()) {
entry = entry = `<tr><td style="width: 24px;"><img src="[img]" alt="[alt]" width="24px" height="24px" /></td><td style="word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;"><a href="${(
`<tr><td style="width: 24px;"><img src="[img]" alt="[alt]" width="24px" height="24px" /></td><td style="word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;"><a href="${( origHref +
origHref + "/" +
"/" + encodeURIComponent(ename)
encodeURIComponent(ename) ).replace(/\/+/g, "/")}">${ename
).replace(/\/+/g, "/")}">${ename .replace(/&/g, "&amp;")
.replace(/&/g, "&amp;") .replace(/</g, "&lt;")
.replace(/</g, "&lt;") .replace(
.replace(/>/g, "&gt;")}</a></td><td>-</td><td>${estats.mtime.toDateString()}</td></tr>\r\n`; />/g,
"&gt;",
)}</a></td><td>-</td><td>${estats.mtime.toDateString()}</td></tr>\r\n`;
// Determine the special file types (block device, character device, etc.) // Determine the special file types (block device, character device, etc.)
if (estats.isBlockDevice()) { if (estats.isBlockDevice()) {

View file

@ -31,82 +31,83 @@ module.exports = (req, res, logFacilities, config, next) => {
"Server version: " + config.generateServerString() + "<br/><hr/>"; "Server version: " + config.generateServerString() + "<br/><hr/>";
//Those entries are just dates and numbers converted/formatted to strings, so no escaping is needed. //Those entries are just dates and numbers converted/formatted to strings, so no escaping is needed.
statusBody += statusBody += `Current time: ${new Date().toString()}<br/>Thread start time: ${new Date(new Date() - process.uptime() * 1000).toString()}<br/>Thread uptime: ${formatRelativeTime(Math.floor(process.uptime()))}<br/>`;
`Current time: ${new Date().toString()}<br/>Thread start time: ${new Date(new Date() - process.uptime() * 1000).toString()}<br/>Thread uptime: ${formatRelativeTime(Math.floor(process.uptime()))}<br/>`;
statusBody += `OS uptime: ${formatRelativeTime(os.uptime())}<br/>`; statusBody += `OS uptime: ${formatRelativeTime(os.uptime())}<br/>`;
statusBody += `Total request count: ${process.reqcounter}<br/>`; statusBody += `Total request count: ${process.reqcounter}<br/>`;
statusBody += statusBody += `Average request rate: ${Math.round((process.reqcounter / process.uptime()) * 100) / 100} requests/s<br/>`;
`Average request rate: ${Math.round((process.reqcounter / process.uptime()) * 100) / 100} requests/s<br/>`;
statusBody += `Client errors (4xx): ${process.err4xxcounter}<br/>`; statusBody += `Client errors (4xx): ${process.err4xxcounter}<br/>`;
statusBody += `Server errors (5xx): ${process.err5xxcounter}<br/>`; statusBody += `Server errors (5xx): ${process.err5xxcounter}<br/>`;
statusBody += statusBody += `Average error rate: ${
`Average error rate: ${Math.round( Math.round(
((process.err4xxcounter + process.err5xxcounter) / process.reqcounter) * ((process.err4xxcounter + process.err5xxcounter) / process.reqcounter) *
10000 10000,
) / ) / 100
100}%<br/>`; }%<br/>`;
statusBody += `Malformed HTTP requests: ${process.malformedcounter}`; statusBody += `Malformed HTTP requests: ${process.malformedcounter}`;
if (process.memoryUsage) if (process.memoryUsage)
statusBody += statusBody += `<br/>Memory usage of thread: ${sizify(process.memoryUsage().rss, true)}B`;
`<br/>Memory usage of thread: ${sizify(process.memoryUsage().rss, true)}B`;
if (process.cpuUsage) if (process.cpuUsage)
statusBody += statusBody += `<br/>Total CPU usage by thread: u${process.cpuUsage().user / 1000}ms s${process.cpuUsage().system / 1000}ms - ${
`<br/>Total CPU usage by thread: u${process.cpuUsage().user / 1000}ms s${process.cpuUsage().system / 1000}ms - ${Math.round( Math.round(
((process.cpuUsage().user + process.cpuUsage().system) / ((process.cpuUsage().user + process.cpuUsage().system) /
1000000 / 1000000 /
process.uptime()) * process.uptime()) *
1000 1000,
) / ) / 1000
1000}%`; }%`;
statusBody += `<br/>Thread PID: ${process.pid}<br/>`; statusBody += `<br/>Thread PID: ${process.pid}<br/>`;
res.writeHead(200, http.STATUS_CODES[200], { res.writeHead(200, http.STATUS_CODES[200], {
"Content-Type": "text/html; charset=utf-8", "Content-Type": "text/html; charset=utf-8",
}); });
res.end( res.end(
`${res.head == "" `${
? "<!DOCTYPE html><html><head><title>" + res.head == ""
name ? "<!DOCTYPE html><html><head><title>" +
.replace(/&/g, "&amp;") name
.replace(/</g, "&lt;") .replace(/&/g, "&amp;")
.replace(/>/g, "&gt;") + .replace(/</g, "&lt;")
" status" + .replace(/>/g, "&gt;") +
(req.headers.host == undefined " status" +
(req.headers.host == undefined
? ""
: " for " +
String(req.headers.host)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")) +
'</title><meta name="viewport" content="width=device-width, initial-scale=1.0" /><style>' +
defaultPageCSS +
"</style></head><body>"
: res.head.replace(
/<head>/i,
"<head><title>" +
name
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;") +
" status" +
(req.headers.host == undefined
? ""
: " for " +
String(req.headers.host)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")) +
"</title>",
)
}<h1>${name
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")} status${
req.headers.host == undefined
? "" ? ""
: " for " + : " for " +
String(req.headers.host)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")) +
'</title><meta name="viewport" content="width=device-width, initial-scale=1.0" /><style>' +
defaultPageCSS +
"</style></head><body>"
: res.head.replace(
/<head>/i,
"<head><title>" +
name
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;") +
" status" +
(req.headers.host == undefined
? ""
: " for " +
String(req.headers.host) String(req.headers.host)
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;")) + .replace(/>/g, "&gt;")
"</title>" }</h1>${statusBody}${res.foot == "" ? "</body></html>" : res.foot}`,
)}<h1>${name
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")} status${req.headers.host == undefined
? ""
: " for " +
String(req.headers.host)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")}</h1>${statusBody}${res.foot == "" ? "</body></html>" : res.foot}`,
); );
return; return;
} }

View file

@ -13,19 +13,19 @@ module.exports = (req, res, logFacilities, config, next) => {
if (req.parsedURL.pathname != sanitizedHref && !req.isProxy) { if (req.parsedURL.pathname != sanitizedHref && !req.isProxy) {
let sanitizedURL = let sanitizedURL =
sanitizedHref + req.parsedURL.search + req.parsedURL.hash; sanitizedHref + req.parsedURL.search + req.parsedURL.hash;
logFacilities.resmessage( logFacilities.resmessage(`URL sanitized: ${req.url} => ${sanitizedURL}`);
`URL sanitized: ${req.url} => ${sanitizedURL}`,
);
if (config.rewriteDirtyURLs) { if (config.rewriteDirtyURLs) {
req.url = sanitizedURL; req.url = sanitizedURL;
try { try {
req.parsedURL = new URL( req.parsedURL = new URL(
req.url, req.url,
`http${req.socket.encrypted ? "s" : ""}://${req.headers.host `http${req.socket.encrypted ? "s" : ""}://${
? req.headers.host req.headers.host
: config.domain ? req.headers.host
? config.domain : config.domain
: "unknown.invalid"}`, ? config.domain
: "unknown.invalid"
}`,
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);
@ -36,9 +36,7 @@ module.exports = (req, res, logFacilities, config, next) => {
return; return;
} }
} else if (req.url != preparedReqUrl && !req.isProxy) { } else if (req.url != preparedReqUrl && !req.isProxy) {
logFacilities.resmessage( logFacilities.resmessage(`URL sanitized: ${req.url} => ${preparedReqUrl}`);
`URL sanitized: ${req.url} => ${preparedReqUrl}`,
);
if (config.rewriteDirtyURLs) { if (config.rewriteDirtyURLs) {
req.url = preparedReqUrl; req.url = preparedReqUrl;
} else { } else {

View file

@ -80,11 +80,13 @@ module.exports = (req, res, logFacilities, config, next) => {
try { try {
req.parsedURL = new URL( req.parsedURL = new URL(
req.url, req.url,
`http${req.socket.encrypted ? "s" : ""}://${req.headers.host `http${req.socket.encrypted ? "s" : ""}://${
? req.headers.host req.headers.host
: config.domain ? req.headers.host
? config.domain : config.domain
: "unknown.invalid"}`, ? config.domain
: "unknown.invalid"
}`,
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);
@ -118,11 +120,13 @@ module.exports = (req, res, logFacilities, config, next) => {
try { try {
req.parsedURL = new URL( req.parsedURL = new URL(
req.url, req.url,
`http${req.socket.encrypted ? "s" : ""}://${req.headers.host `http${req.socket.encrypted ? "s" : ""}://${
? req.headers.host req.headers.host
: config.domain ? req.headers.host
? config.domain : config.domain
: "unknown.invalid"}`, ? config.domain
: "unknown.invalid"
}`,
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);

View file

@ -4,9 +4,11 @@ const getOS = require("./getOS.js");
function generateServerString(exposeServerVersion) { function generateServerString(exposeServerVersion) {
return exposeServerVersion return exposeServerVersion
? `${name.replace(/ /g, "-")}/${version} (${getOS()}; ${process.isBun ? `${name.replace(/ /g, "-")}/${version} (${getOS()}; ${
? "Bun/v" + process.versions.bun + "; like Node.JS/" + process.version process.isBun
: "Node.JS/" + process.version})` ? "Bun/v" + process.versions.bun + "; like Node.JS/" + process.version
: "Node.JS/" + process.version
})`
: name.replace(/ /g, "-"); : name.replace(/ /g, "-");
} }