1
0
Fork 0
forked from svrjs/svrjs

Replace some strings with template strings

This commit is contained in:
Dorian Niemiec 2024-08-26 19:21:52 +02:00
parent d92fc14991
commit 488bee1a95
16 changed files with 316 additions and 519 deletions

View file

@ -64,7 +64,7 @@ function clientErrorHandler(err, socket) {
headername.match(/[^\x09\x20-\x7e\x80-\xff]|.:/) || headername.match(/[^\x09\x20-\x7e\x80-\xff]|.:/) ||
headerValueS.match(/[^\x09\x20-\x7e\x80-\xff]/) headerValueS.match(/[^\x09\x20-\x7e\x80-\xff]/)
) )
throw new Error("Invalid header!!! (" + headername + ")"); throw new Error(`Invalid header!!! (${headername})`);
head += headername + ": " + headerValueS; head += headername + ": " + headerValueS;
}); });
} else { } else {
@ -72,7 +72,7 @@ function clientErrorHandler(err, socket) {
headername.match(/[^\x09\x20-\x7e\x80-\xff]|.:/) || headername.match(/[^\x09\x20-\x7e\x80-\xff]|.:/) ||
headers[headername].match(/[^\x09\x20-\x7e\x80-\xff]/) headers[headername].match(/[^\x09\x20-\x7e\x80-\xff]/)
) )
throw new Error("Invalid header!!! (" + headername + ")"); throw new Error(`Invalid header!!! (${headername})`);
head += headername + ": " + headers[headername]; head += headername + ": " + headers[headername];
} }
head += "\r\n"; head += "\r\n";
@ -264,51 +264,49 @@ function clientErrorHandler(err, socket) {
// Disable custom error page for HTTP SSL error // Disable custom error page for HTTP SSL error
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>' + `<!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><p><i>{server}</i></p></body></html>"
defaultPageCSS + .replace(
"</style></head><body><h1>{errorMessage}</h1><p>{errorDesc}</p><p><i>{server}</i></p></body></html>" /{errorMessage}/g,
.replace( errorCode.toString() +
/{errorMessage}/g, " " +
errorCode.toString() + http.STATUS_CODES[errorCode]
" " + .replace(/&/g, "&amp;")
http.STATUS_CODES[errorCode] .replace(/</g, "&lt;")
.replace(/&/g, "&amp;") .replace(/>/g, "&gt;")
.replace(/</g, "&lt;") )
.replace(/>/g, "&gt;"), .replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode])
.replace(
/{stack}/g,
stack
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/\r\n/g, "<br/>")
.replace(/\n/g, "<br/>")
.replace(/\r/g, "<br/>")
.replace(/ {2}/g, "&nbsp;&nbsp;")
)
.replace(
/{server}/g,
(
config.generateServerString() +
(!config.exposeModsInErrorPages || extName == undefined
? ""
: " " + extName)
) )
.replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode]) .replace(/&/g, "&amp;")
.replace( .replace(/</g, "&lt;")
/{stack}/g, .replace(/>/g, "&gt;")
stack )
.replace(/&/g, "&amp;") .replace(
.replace(/</g, "&lt;") /{contact}/g,
.replace(/>/g, "&gt;") config.serverAdministratorEmail
.replace(/\r\n/g, "<br/>") .replace(/&/g, "&amp;")
.replace(/\n/g, "<br/>") .replace(/</g, "&lt;")
.replace(/\r/g, "<br/>") .replace(/>/g, "&gt;")
.replace(/ {2}/g, "&nbsp;&nbsp;"), .replace(/\./g, "[dot]")
) .replace(/@/g, "[at]")
.replace( )}`,
/{server}/g,
(
config.generateServerString() +
(!config.exposeModsInErrorPages || extName == undefined
? ""
: " " + extName)
)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;"),
)
.replace(
/{contact}/g,
config.serverAdministratorEmail
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/\./g, "[dot]")
.replace(/@/g, "[at]"),
),
); );
res.end(); res.end();
} else { } else {
@ -380,13 +378,9 @@ 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>' + `<!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
defaultPageCSS +
"</style></head><body><h1>{errorMessage}</h1><p>{errorDesc}</p>" +
(additionalError == 404
? "" ? ""
: "<p>Additionally, a {additionalError} error occurred while loading an error page.</p>") + : "<p>Additionally, a {additionalError} error occurred while loading an error page.</p>"}<p><i>{server}</i></p></body></html>`
"<p><i>{server}</i></p></body></html>"
) )
.replace( .replace(
/{errorMessage}/g, /{errorMessage}/g,
@ -444,20 +438,16 @@ function clientErrorHandler(err, socket) {
process.reqcounter++; process.reqcounter++;
process.malformedcounter++; process.malformedcounter++;
logFacilities.locmessage( logFacilities.locmessage(
"Somebody connected to " + `Somebody connected to ${config.secure && fromMain
(config.secure && fromMain ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport
? (typeof config.sport == "number" ? "port " : "socket ") + config.sport : (typeof config.port == "number" ? "port " : "socket ") +
: (typeof config.port == "number" ? "port " : "socket ") + config.port}...`,
config.port) +
"...",
); );
logFacilities.reqmessage( logFacilities.reqmessage(
"Client " + `Client ${!reqip || reqip == ""
(!reqip || reqip == "" ? "[unknown client]"
? "[unknown client]" : reqip +
: reqip + (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")} sent invalid request.`,
(reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")) +
" sent invalid request.",
); );
try { try {
head = fs.existsSync("./.head") head = fs.existsSync("./.head")
@ -486,7 +476,7 @@ function clientErrorHandler(err, socket) {
return; return;
} else { } else {
logFacilities.errmessage( logFacilities.errmessage(
"An SSL error occured: " + (err.code ? err.code : err.message), `An SSL error occured: ${err.code ? err.code : err.message}`,
); );
callServerError(400); callServerError(400);
return; return;
@ -494,7 +484,7 @@ function clientErrorHandler(err, socket) {
} }
if (err.code && err.code.indexOf("ERR_HTTP2_") == 0) { if (err.code && err.code.indexOf("ERR_HTTP2_") == 0) {
logFacilities.errmessage("An HTTP/2 error occured: " + err.code); logFacilities.errmessage(`An HTTP/2 error occured: ${err.code}`);
callServerError(400); callServerError(400);
return; return;
} }

View file

@ -33,22 +33,16 @@ function noproxyHandler(req, socket, head) {
var reqport = socket.remotePort; var reqport = socket.remotePort;
process.reqcounter++; process.reqcounter++;
logFacilities.locmessage( logFacilities.locmessage(
"Somebody connected to " + `Somebody connected to ${config.secure
(config.secure ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport
? (typeof config.sport == "number" ? "port " : "socket ") + config.sport : (typeof config.port == "number" ? "port " : "socket ") +
: (typeof config.port == "number" ? "port " : "socket ") + config.port}...`,
config.port) +
"...",
); );
logFacilities.reqmessage( logFacilities.reqmessage(
"Client " + `Client ${!reqip || reqip == ""
(!reqip || reqip == "" ? "[unknown client]"
? "[unknown client]" : reqip +
: reqip + (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")} wants to proxy ${req.url} through this server`,
(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,22 +39,16 @@ function proxyHandler(req, socket, head) {
var reqport = socket.remotePort; var reqport = socket.remotePort;
process.reqcounter++; process.reqcounter++;
logFacilities.locmessage( logFacilities.locmessage(
"Somebody connected to " + `Somebody connected to ${config.secure
(config.secure ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport
? (typeof config.sport == "number" ? "port " : "socket ") + config.sport : (typeof config.port == "number" ? "port " : "socket ") +
: (typeof config.port == "number" ? "port " : "socket ") + config.port}...`,
config.port) +
"...",
); );
logFacilities.reqmessage( logFacilities.reqmessage(
"Client " + `Client ${!reqip || reqip == ""
(!reqip || reqip == "" ? "[unknown client]"
? "[unknown client]" : reqip +
: reqip + (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")} wants to proxy ${req.url} through this server`,
(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"]);
@ -81,7 +75,7 @@ function proxyHandler(req, socket, head) {
} }
} else { } else {
logFacilities.errmessage( logFacilities.errmessage(
name + " doesn't support proxy without proxy mod.", `${name} doesn't support proxy without proxy mod.`,
); );
if (!socket.destroyed) socket.end("HTTP/1.1 501 Not Implemented\n\n"); if (!socket.destroyed) socket.end("HTTP/1.1 501 Not Implemented\n\n");
} }

View file

@ -204,12 +204,10 @@ 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 " + `Somebody connected to ${config.secure && fromMain
(config.secure && fromMain ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport
? (typeof config.sport == "number" ? "port " : "socket ") + config.sport : (typeof config.port == "number" ? "port " : "socket ") +
: (typeof config.port == "number" ? "port " : "socket ") + config.port}...`,
config.port) +
"...",
); );
if (req.socket == null) { if (req.socket == null) {
@ -269,13 +267,10 @@ function requestHandler(req, res) {
} }
logFacilities.reqmessage( logFacilities.reqmessage(
"Client " + `Client ${!reqip || reqip == ""
(!reqip || reqip == "" ? "[unknown client]"
? "[unknown client]" : reqip +
: reqip + (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")} wants ${req.method == "GET"
(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 "
@ -285,9 +280,7 @@ 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 ") + : "to access content using " + req.method + " method in "}${req.headers.host == undefined || req.isProxy ? "" : req.headers.host}${req.url}`,
(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"]);
@ -536,13 +529,9 @@ 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>' + `<!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
defaultPageCSS +
"</style></head><body><h1>{errorMessage}</h1><p>{errorDesc}</p>" +
(additionalError == 404
? "" ? ""
: "<p>Additionally, a {additionalError} error occurred while loading an error page.</p>") + : "<p>Additionally, a {additionalError} error occurred while loading an error page.</p>"}<p><i>{server}</i></p></body></html>`
"<p><i>{server}</i></p></body></html>"
) )
.replace( .replace(
/{errorMessage}/g, /{errorMessage}/g,

View file

@ -15,7 +15,7 @@ function serverErrorHandler(err, isRedirect, server, start) {
: serverErrorDescs["UNKNOWN"], : serverErrorDescs["UNKNOWN"],
); );
serverconsole.locmessage( serverconsole.locmessage(
(isRedirect ? attmtsRedir : attmts) + " attempts left.", `${isRedirect ? attmtsRedir : attmts} attempts left.`,
); );
} else { } else {
try { try {
@ -59,7 +59,7 @@ process.messageEventListeners.push((worker, serverconsole) => {
? serverErrorDescs[errCode] ? serverErrorDescs[errCode]
: serverErrorDescs["UNKNOWN"], : serverErrorDescs["UNKNOWN"],
); );
serverconsole.locmessage(tries + " attempts left."); serverconsole.locmessage(`${tries} attempts left.`);
} }
if (message.length >= 9 && message.indexOf("\x12ERRCRASH") == 0) { if (message.length >= 9 && message.indexOf("\x12ERRCRASH") == 0) {
const errno = os.constants.errno[message.substring(9)]; const errno = os.constants.errno[message.substring(9)];

View file

@ -658,9 +658,7 @@ if (!disableMods) {
else { else {
modInfos.push({ modInfos.push({
name: name:
"Unknown mod (" + `Unknown mod (${modFileRaw}; module.exports.modInfo not set)`,
modFileRaw +
"; module.exports.modInfo not set)",
version: "ERROR", version: "ERROR",
}); });
} }
@ -736,7 +734,7 @@ if (!disableMods) {
} catch (err) { } catch (err) {
// If failed to read info file, add a placeholder entry to modInfos with an error message // If failed to read info file, add a placeholder entry to modInfos with an error message
modInfos.push({ modInfos.push({
name: "Unknown mod (" + modFileRaw + ";" + err.message + ")", name: `Unknown mod (${modFileRaw}; ${err.message})`,
version: "ERROR", version: "ERROR",
}); });
} }
@ -775,14 +773,11 @@ if (!disableMods) {
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") + : "var hexstrbase64 = require('../hexstrbase64/index.js');\r\n"}${crypto.__disabled__ === undefined
(crypto.__disabled__ === undefined ? "var crypto = require('crypto');\r\nvar https = require('https');\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`;
: "") +
'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
@ -877,10 +872,9 @@ 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" + `* https://localhost${process.serverConfig.sport == 443
(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
@ -895,10 +889,9 @@ function listeningMessage() {
) { ) {
if (typeof process.serverConfig.port === "number") { if (typeof process.serverConfig.port === "number") {
serverconsole.locmessage( serverconsole.locmessage(
"* http://localhost" + `* http://localhost${process.serverConfig.port == 80
(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
@ -911,11 +904,9 @@ function listeningMessage() {
(!sListenToAny || (host != "" && host != "[offline]")) (!sListenToAny || (host != "" && host != "[offline]"))
) )
serverconsole.locmessage( serverconsole.locmessage(
"* https://" + `* https://${sAccHost.indexOf(":") > -1 ? "[" + sAccHost + "]" : sAccHost}${process.serverConfig.sport == 443
(sAccHost.indexOf(":") > -1 ? "[" + sAccHost + "]" : sAccHost) + ? ""
(process.serverConfig.sport == 443 : ":" + process.serverConfig.sport}`,
? ""
: ":" + process.serverConfig.sport),
); );
if ( if (
!( !(
@ -927,21 +918,17 @@ function listeningMessage() {
typeof process.serverConfig.port === "number" typeof process.serverConfig.port === "number"
) )
serverconsole.locmessage( serverconsole.locmessage(
"* http://" + `* http://${accHost.indexOf(":") > -1 ? "[" + accHost + "]" : accHost}${process.serverConfig.port == 80
(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://" + `* https://${pubip.indexOf(":") > -1 ? "[" + pubip + "]" : pubip}${process.serverConfig.spubport == 443
(pubip.indexOf(":") > -1 ? "[" + pubip + "]" : pubip) + ? ""
(process.serverConfig.spubport == 443 : ":" + process.serverConfig.spubport}`,
? ""
: ":" + process.serverConfig.spubport),
); );
if ( if (
!( !(
@ -951,21 +938,17 @@ function listeningMessage() {
!listenToLocalhost !listenToLocalhost
) )
serverconsole.locmessage( serverconsole.locmessage(
"* http://" + `* http://${pubip.indexOf(":") > -1 ? "[" + pubip + "]" : pubip}${process.serverConfig.pubport == 80
(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://" + `* https://${domain}${process.serverConfig.spubport == 443
domain + ? ""
(process.serverConfig.spubport == 443 : ":" + process.serverConfig.spubport}`,
? ""
: ":" + process.serverConfig.spubport),
); );
if ( if (
!( !(
@ -975,11 +958,9 @@ function listeningMessage() {
!listenToLocalhost !listenToLocalhost
) )
serverconsole.locmessage( serverconsole.locmessage(
"* http://" + `* http://${domain}${process.serverConfig.pubport == 80
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"');
@ -994,8 +975,7 @@ function listeningMessage() {
sendStatistics(modInfos, (err) => { sendStatistics(modInfos, (err) => {
if (err) if (err)
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
"There was a problem, when sending data to statistics server! Reason: " + `There was a problem, when sending data to statistics server! Reason: ${err.message}`,
err.message,
); );
}); });
} }
@ -1223,7 +1203,7 @@ let commands = {
log("Server closed."); log("Server closed.");
if (cluster.isPrimary !== undefined) process.send("\x12CLOSE"); if (cluster.isPrimary !== undefined) process.send("\x12CLOSE");
} catch (err) { } catch (err) {
log("Cannot close server! Reason: " + err.message); log(`Cannot close server! Reason: ${err.message}`);
} }
}, },
open: (args, log) => { open: (args, log) => {
@ -1259,21 +1239,17 @@ let commands = {
} }
log("Server opened."); log("Server opened.");
} catch (err) { } catch (err) {
log("Cannot open server! Reason: " + err.message); log(`Cannot open server! Reason: ${err.message}`);
} }
}, },
help: (args, log) => { help: (args, log) => {
log("Server commands:\n" + Object.keys(commands).join(" ")); log(`Server commands:\n${Object.keys(commands).join(" ")}`);
}, },
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() + `${(i + 1).toString()}. ${modInfos[i].name} ${modInfos[i].version}`,
". " +
modInfos[i].name +
" " +
modInfos[i].version,
); );
} }
if (modInfos.length == 0) { if (modInfos.length == 0) {
@ -1340,8 +1316,8 @@ let commands = {
}, },
restart: (args, log) => { restart: (args, log) => {
if (cluster.isPrimary === undefined) if (cluster.isPrimary === undefined)
log("This command is not supported on single-threaded " + name + "."); log(`This command is not supported on single-threaded ${name}.`);
else log("This command need to be run in " + name + " master."); else log(`This command need to be run in ${name} master.`);
}, },
}; };
@ -1385,8 +1361,7 @@ function SVRJSFork() {
) { ) {
threadLimitWarned = true; threadLimitWarned = true;
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
name + `${name} limited the number of workers to one, because of startup problems in Bun 1.0 and newer with shimmed (not native) clustering module. Reliability may suffer.`,
" limited the number of workers to one, because of startup problems in Bun 1.0 and newer with shimmed (not native) clustering module. Reliability may suffer.",
); );
} }
if ( if (
@ -1402,8 +1377,7 @@ function SVRJSFork() {
} else { } else {
if (SVRJSInitialized) if (SVRJSInitialized)
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
name + `${name} limited the number of workers to one, because of startup problems in Bun 1.0 and newer with shimmed (not native) clustering module. Reliability may suffer.`,
" limited the number of workers to one, because of startup problems in Bun 1.0 and newer with shimmed (not native) clustering module. Reliability may suffer.",
); );
} }
} catch (err) { } catch (err) {
@ -1419,8 +1393,7 @@ function SVRJSFork() {
) { ) {
threadLimitWarned = true; threadLimitWarned = true;
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
name + `${name} limited the number of workers to one, because of startup problems in Bun 1.0 and newer with shimmed (not native) clustering module. Reliability may suffer.`,
" limited the number of workers to one, because of startup problems in Bun 1.0 and newer with shimmed (not native) clustering module. Reliability may suffer.",
); );
} }
if ( if (
@ -1436,8 +1409,7 @@ function SVRJSFork() {
} else { } else {
if (SVRJSInitialized) if (SVRJSInitialized)
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
name + `${name} limited the number of workers to one, because of startup problems in Bun 1.0 and newer with shimmed (not native) clustering module. Reliability may suffer.`,
" limited the number of workers to one, because of startup problems in Bun 1.0 and newer with shimmed (not native) clustering module. Reliability may suffer.",
); );
} }
} else { } else {
@ -1533,8 +1505,7 @@ function msgListener(message) {
serverconsole.locmessage("Configuration saved."); serverconsole.locmessage("Configuration saved.");
} else if (message.indexOf("\x12SAVEERR") == 0) { } else if (message.indexOf("\x12SAVEERR") == 0) {
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
"There was a problem while saving configuration file. Reason: " + `There was a problem while saving configuration file. Reason: ${message.substring(8)}`,
message.substring(8),
); );
} else if (message[0] == "\x12") { } else if (message[0] == "\x12") {
// Discard unrecognized control messages // Discard unrecognized control messages
@ -1656,9 +1627,7 @@ function start(init) {
for (let i = 0; i < logo.length; i++) console.log(logo[i]); // Print logo for (let i = 0; i < logo.length; i++) console.log(logo[i]); // Print logo
console.log(); console.log();
console.log( console.log(
"Welcome to \x1b[1m" + `Welcome to \x1b[1m${name} - a web server running on Node.JS\x1b[0m`,
name +
" - a web server running on Node.JS\x1b[0m",
); );
// Print warnings // Print warnings
@ -1672,13 +1641,7 @@ function start(init) {
); );
if (process.isBun) { if (process.isBun) {
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
"Bun support is experimental. Some features of " + `Bun support is experimental. Some features of ${name}, ${name} mods and ${name} server-side JavaScript may not work as expected.`,
name +
", " +
name +
" mods and " +
name +
" server-side JavaScript may not work as expected.",
); );
if ( if (
process.isBun && process.isBun &&
@ -1698,9 +1661,7 @@ function start(init) {
} }
if (cluster.isPrimary === undefined) if (cluster.isPrimary === undefined)
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
"You're running " + `You're running ${name} on single thread. Reliability may suffer, as the server is stopped after crash.`,
name +
" on single thread. Reliability may suffer, as the server is stopped after crash.",
); );
if (crypto.__disabled__ !== undefined) if (crypto.__disabled__ !== undefined)
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
@ -1730,13 +1691,7 @@ function start(init) {
); );
if (process.getuid && process.getuid() == 0) if (process.getuid && process.getuid() == 0)
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
"You're running " + `You're running ${name} as root. It's recommended to run ${name} as an non-root user. Running ${name} as root may increase the risks of OS command execution vulnerabilities.`,
name +
" as root. It's recommended to run " +
name +
" as an non-root user. Running " +
name +
" as root may increase the risks of OS command execution vulnerabilities.",
); );
if ( if (
!process.isBun && !process.isBun &&
@ -1765,15 +1720,11 @@ function start(init) {
); );
if (process.serverConfig.disableMods) if (process.serverConfig.disableMods)
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
"" + `${name} is running without mods and server-side JavaScript enabled. Web applications may not work as expected`,
name +
" is running without mods and server-side JavaScript enabled. Web applications may not work as expected",
); );
if (process.serverConfig.optOutOfStatisticsServer) if (process.serverConfig.optOutOfStatisticsServer)
serverconsole.locmessage( serverconsole.locmessage(
"" + `${name} is configured to opt out of sending data to the statistics server.`,
name +
" is configured to opt out of sending data to the statistics server.",
); );
console.log(); console.log();
@ -1781,9 +1732,7 @@ function start(init) {
if (process.isPrimary || process.isPrimary === undefined) { if (process.isPrimary || process.isPrimary === undefined) {
modLoadingErrors.forEach(function (modLoadingError) { modLoadingErrors.forEach(function (modLoadingError) {
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
'There was a problem while loading a "' + `There was a problem while loading a "${String(modLoadingError.modName).replace(/[\r\n]/g, "")}" mod.`,
String(modLoadingError.modName).replace(/[\r\n]/g, "") +
'" mod.',
); );
serverconsole.locwarnmessage("Stack:"); serverconsole.locwarnmessage("Stack:");
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
@ -1808,28 +1757,21 @@ function start(init) {
const CPUs = os.cpus(); const CPUs = os.cpus();
if (CPUs.length > 0) if (CPUs.length > 0)
serverconsole.locmessage( serverconsole.locmessage(
"CPU: " + (CPUs.length > 1 ? CPUs.length + "x " : "") + CPUs[0].model, `CPU: ${CPUs.length > 1 ? CPUs.length + "x " : ""}${CPUs[0].model}`,
); );
// Throw errors // Throw errors
if (vnum < 64) if (vnum < 64)
throw new Error( throw new Error(
"" + `${name} requires Node.JS 10.0.0 and newer, but your Node.JS version isn't supported by ${name}.`,
name +
" requires Node.JS 10.0.0 and newer, but your Node.JS version isn't supported by " +
name +
".",
); );
if (configJSONRErr) if (configJSONRErr)
throw new Error( throw new Error(
"Can't read " + `Can't read ${name} configuration file: ${configJSONRErr.message}`,
name +
" configuration file: " +
configJSONRErr.message,
); );
if (configJSONPErr) if (configJSONPErr)
throw new Error( throw new Error(
"" + name + " configuration parse error: " + configJSONPErr.message, `${name} configuration parse error: ${configJSONPErr.message}`,
); );
if ( if (
process.serverConfig.enableHTTP2 && process.serverConfig.enableHTTP2 &&
@ -1837,15 +1779,11 @@ function start(init) {
typeof process.serverConfig.port != "number" typeof process.serverConfig.port != "number"
) )
throw new Error( throw new Error(
"HTTP/2 without HTTPS, along with Unix sockets/Windows named pipes aren't supported by " + `HTTP/2 without HTTPS, along with Unix sockets/Windows named pipes aren't supported by ${name}.`,
name +
".",
); );
if (process.serverConfig.enableHTTP2 && http2.__disabled__ !== undefined) if (process.serverConfig.enableHTTP2 && http2.__disabled__ !== undefined)
throw new Error( throw new Error(
"HTTP/2 isn't supported by your Node.JS version! You may not be able to use HTTP/2 with " + `HTTP/2 isn't supported by your Node.JS version! You may not be able to use HTTP/2 with ${name}`,
name +
"",
); );
if (listenAddress) { if (listenAddress) {
if (listenAddress.match(/^[0-9]+$/)) if (listenAddress.match(/^[0-9]+$/))
@ -1857,20 +1795,19 @@ function start(init) {
/^(?:2(?:2[4-9]|3[0-9])\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$|ff[0-9a-f][0-9a-f]:[0-9a-f:])/i, /^(?:2(?:2[4-9]|3[0-9])\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$|ff[0-9a-f][0-9a-f]:[0-9a-f:])/i,
) )
) )
throw new Error("" + name + " can't listen on multicast address."); throw new Error(`${name} can't listen on multicast address.`);
if (brdIPs.indexOf(listenAddress) > -1) if (brdIPs.indexOf(listenAddress) > -1)
throw new Error("" + name + " can't listen on broadcast address."); throw new Error(`${name} can't listen on broadcast address.`);
if (netIPs.indexOf(listenAddress) > -1) if (netIPs.indexOf(listenAddress) > -1)
throw new Error("" + name + " can't listen on subnet address."); throw new Error(`${name} can't listen on subnet address.`);
} }
if (certificateError) if (certificateError)
throw new Error( throw new Error(
"There was a problem with SSL certificate/private key: " + `There was a problem with SSL certificate/private key: ${certificateError.message}`,
certificateError.message,
); );
if (wwwrootError) if (wwwrootError)
throw new Error( throw new Error(
"There was a problem with your web root: " + wwwrootError.message, `There was a problem with your web root: ${wwwrootError.message}`,
); );
if (sniReDos) if (sniReDos)
throw new Error( throw new Error(
@ -1886,29 +1823,23 @@ function start(init) {
) )
) )
serverconsole.locmessage( serverconsole.locmessage(
"Starting HTTP server at " + `Starting HTTP server at ${typeof process.serverConfig.port == "number"
(typeof process.serverConfig.port == "number" ? listenAddress
? listenAddress ? (listenAddress.indexOf(":") > -1
? (listenAddress.indexOf(":") > -1 ? "[" + listenAddress + "]"
? "[" + listenAddress + "]" : listenAddress) + ":"
: listenAddress) + ":" : "port "
: "port " : ""}${process.serverConfig.port.toString()}...`,
: "") +
process.serverConfig.port.toString() +
"...",
); );
if (process.serverConfig.secure) if (process.serverConfig.secure)
serverconsole.locmessage( serverconsole.locmessage(
"Starting HTTPS server at " + `Starting HTTPS server at ${typeof process.serverConfig.sport == "number"
(typeof process.serverConfig.sport == "number" ? sListenAddress
? sListenAddress ? (sListenAddress.indexOf(":") > -1
? (sListenAddress.indexOf(":") > -1 ? "[" + sListenAddress + "]"
? "[" + sListenAddress + "]" : sListenAddress) + ":"
: sListenAddress) + ":" : "port "
: "port " : ""}${process.serverConfig.sport.toString()}...`,
: "") +
process.serverConfig.sport.toString() +
"...",
); );
} }
@ -2013,8 +1944,7 @@ function start(init) {
addListenersToWorker(cluster.workers[goodWorkers[wN]]); addListenersToWorker(cluster.workers[goodWorkers[wN]]);
} }
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
"There was a problem while saving configuration file. Reason: " + `There was a problem while saving configuration file. Reason: ${err.message}`,
err.message,
); );
} }
}); });
@ -2062,13 +1992,13 @@ function start(init) {
commands[command](argss, (msg) => process.send(msg)); commands[command](argss, (msg) => process.send(msg));
process.send("\x12END"); process.send("\x12END");
} else { } else {
process.send('Unrecognized command "' + line.split(" ")[0] + '".'); process.send(`Unrecognized command "${line.split(" ")[0]}".`);
process.send("\x12END"); process.send("\x12END");
} }
} 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");
} }
@ -2106,7 +2036,7 @@ function start(init) {
} }
if (stopError) if (stopError)
serverconsole.climessage( serverconsole.climessage(
"Some " + name + " workers might not be stopped.", `Some ${name} workers might not be stopped.`,
); );
SVRJSInitialized = false; SVRJSInitialized = false;
closedMaster = true; closedMaster = true;
@ -2115,7 +2045,7 @@ function start(init) {
forkWorkers(workersToFork, function () { forkWorkers(workersToFork, function () {
SVRJSInitialized = true; SVRJSInitialized = true;
exiting = false; exiting = false;
serverconsole.climessage("" + name + " workers restarted."); serverconsole.climessage(`${name} workers restarted.`);
}); });
return; return;
@ -2136,7 +2066,7 @@ function start(init) {
addListenersToWorker(cluster.workers[clusterID]); addListenersToWorker(cluster.workers[clusterID]);
} }
serverconsole.climessage( serverconsole.climessage(
"Can't run command \"" + command + '".', `Can't run command "${command}".`,
); );
} }
}); });
@ -2380,8 +2310,7 @@ function start(init) {
addListenersToWorker(cluster.workers[goodWorkers[wN]]); addListenersToWorker(cluster.workers[goodWorkers[wN]]);
} }
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
"There was a problem while terminating unused worker process. Reason: " + `There was a problem while terminating unused worker process. Reason: ${err.message}`,
err.message,
); );
} }
} }
@ -2399,7 +2328,7 @@ function start(init) {
if (cluster.isPrimary || cluster.isPrimary === undefined) { if (cluster.isPrimary || cluster.isPrimary === undefined) {
// Crash handler // Crash handler
function crashHandlerMaster(err) { function crashHandlerMaster(err) {
serverconsole.locerrmessage(name + " main process just crashed!!!"); serverconsole.locerrmessage(`${name} main process just crashed!!!`);
serverconsole.locerrmessage("Stack:"); serverconsole.locerrmessage("Stack:");
serverconsole.locerrmessage( serverconsole.locerrmessage(
err.stack ? generateErrorStack(err) : String(err), err.stack ? generateErrorStack(err) : String(err),
@ -2417,8 +2346,7 @@ if (cluster.isPrimary || cluster.isPrimary === undefined) {
} }
} catch (err) { } catch (err) {
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
"There was a problem while saving configuration file. Reason: " + `There was a problem while saving configuration file. Reason: ${err.message}`,
err.message,
); );
} }
try { try {
@ -2474,7 +2402,7 @@ if (cluster.isPrimary || cluster.isPrimary === undefined) {
} else { } else {
// Crash handler // Crash handler
function crashHandler(err) { function crashHandler(err) {
serverconsole.locerrmessage(name + " worker just crashed!!!"); serverconsole.locerrmessage(`${name} worker just crashed!!!`);
serverconsole.locerrmessage("Stack:"); serverconsole.locerrmessage("Stack:");
serverconsole.locerrmessage( serverconsole.locerrmessage(
err.stack ? generateErrorStack(err) : String(err), err.stack ? generateErrorStack(err) : String(err),
@ -2499,7 +2427,7 @@ if (cluster.isPrimary || cluster.isPrimary === undefined) {
try { try {
start(true); start(true);
} catch (err) { } catch (err) {
serverconsole.locerrmessage("There was a problem starting " + name + "!!!"); serverconsole.locerrmessage(`There was a problem starting ${name}!!!`);
serverconsole.locerrmessage("Stack:"); serverconsole.locerrmessage("Stack:");
serverconsole.locerrmessage(generateErrorStack(err)); serverconsole.locerrmessage(generateErrorStack(err));
setTimeout(function () { setTimeout(function () {

View file

@ -90,7 +90,7 @@ module.exports = (req, res, logFacilities, config, next) => {
!config.exposeServerVersion !config.exposeServerVersion
) { ) {
res.error(403); res.error(403);
logFacilities.errmessage("Access to " + name + " script is denied."); logFacilities.errmessage(`Access to ${name} script is denied.`);
return; return;
} else if ( } else if (
(isForbiddenPath(decodedHrefWithoutDuplicateSlashes, "svrjs") || (isForbiddenPath(decodedHrefWithoutDuplicateSlashes, "svrjs") ||

View file

@ -9,29 +9,21 @@ module.exports = (req, res, logFacilities, config, next) => {
eheaders["Content-Type"] = "text/html; charset=utf-8"; eheaders["Content-Type"] = "text/html; charset=utf-8";
res.writeHead(501, http.STATUS_CODES[501], eheaders); res.writeHead(501, http.STATUS_CODES[501], eheaders);
res.write( res.write(
'<!DOCTYPE html><html><head><title>Proxy not implemented</title><meta name="viewport" content="width=device-width, initial-scale=1.0" /><style>' + `<!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
defaultPageCSS + .replace(/&/g, "&amp;")
"</style></head><body><h1>Proxy not implemented</h1><p>" + .replace(/</g, "&lt;")
name .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(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&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 " + .generateServerString()
name .replace(/&/g, "&amp;")
.replace(/&/g, "&amp;") .replace(/</g, "&lt;")
.replace(/</g, "&lt;") .replace(/>/g, "&gt;")}</i></p></body></html>`,
.replace(/>/g, "&gt;") +
" as a proxy.</p><p><i>" +
config
.generateServerString()
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;") +
"</i></p></body></html>",
); );
res.end(); res.end();
logFacilities.errmessage( logFacilities.errmessage(
name + " doesn't support proxy without proxy mod.", `${name} doesn't support proxy without proxy mod.`,
); );
return; return;
} }

View file

@ -155,7 +155,7 @@ module.exports = (req, res, logFacilities, config, next) => {
} else if (nonscode.scode == 410) { } else if (nonscode.scode == 410) {
logFacilities.errmessage("Content is gone."); logFacilities.errmessage("Content is gone.");
} else if (nonscode.scode == 418) { } else if (nonscode.scode == 418) {
logFacilities.errmessage(name + " is always a teapot ;)"); logFacilities.errmessage(`${name} is always a teapot ;)`);
} else { } else {
logFacilities.errmessage("Client fails receiving content."); logFacilities.errmessage("Client fails receiving content.");
} }
@ -186,8 +186,7 @@ module.exports = (req, res, logFacilities, config, next) => {
res.error( res.error(
500, 500,
new Error( new Error(
name + `${name} doesn't support scrypt-hashed passwords on Node.JS versions without scrypt hash support.`,
" doesn't support scrypt-hashed passwords on Node.JS versions without scrypt hash support.",
), ),
); );
return; return;
@ -226,8 +225,7 @@ module.exports = (req, res, logFacilities, config, next) => {
res.error( res.error(
500, 500,
new Error( new Error(
name + `${name} doesn't support PBKDF2-hashed passwords on Node.JS versions without crypto support.`,
" doesn't support PBKDF2-hashed passwords on Node.JS versions without crypto support.",
), ),
); );
return; return;
@ -272,11 +270,9 @@ module.exports = (req, res, logFacilities, config, next) => {
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") + : name + " HTTP Basic Authorization"}", charset="UTF-8"`;
'", 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);
@ -353,9 +349,7 @@ module.exports = (req, res, logFacilities, config, next) => {
} }
res.error(401, ha); res.error(401, ha);
logFacilities.errmessage( logFacilities.errmessage(
'User "' + `User "${String(username).replace(/[\r\n]/g, "")}" failed to log in.`,
String(username).replace(/[\r\n]/g, "") +
'" failed to log in.',
); );
} else { } else {
if (bruteProtection) { if (bruteProtection) {
@ -369,9 +363,7 @@ module.exports = (req, res, logFacilities, config, next) => {
} }
} }
logFacilities.reqmessage( logFacilities.reqmessage(
'Client is logged in as "' + `Client is logged in as "${String(username).replace(/[\r\n]/g, "")}".`,
String(username).replace(/[\r\n]/g, "") +
'".',
); );
req.authUser = username; req.authUser = username;
next(); next();

View file

@ -67,11 +67,7 @@ module.exports = (req, res, logFacilities, config, next) => {
hostname = hostname.join(":"); hostname = hostname.join(":");
if (hostname == config.domain && hostname.indexOf("www.") != 0) { if (hostname == config.domain && hostname.indexOf("www.") != 0) {
res.redirect( res.redirect(
(req.socket.encrypted ? "https" : "http") + `${req.socket.encrypted ? "https" : "http"}://www.${hostname}${hostport ? ":" + hostport : ""}${req.url.replace(/\/+/g, "/")}`,
"://www." +
hostname +
(hostport ? ":" + hostport : "") +
req.url.replace(/\/+/g, "/"),
); );
return; return;
} }

View file

@ -87,20 +87,17 @@ module.exports = (req, res, logFacilities, config, next) => {
} }
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" + `http${req.socket.encrypted ? "s" : ""}://${req.headers.host
(req.socket.encrypted ? "s" : "") + ? req.headers.host
"://" + : config.domain
(req.headers.host ? config.domain
? req.headers.host : "unknown.invalid"}`,
: config.domain
? config.domain
: "unknown.invalid"),
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);
@ -134,14 +131,11 @@ module.exports = (req, res, logFacilities, config, next) => {
try { try {
req.parsedURL = new URL( req.parsedURL = new URL(
req.url, req.url,
"http" + `http${req.socket.encrypted ? "s" : ""}://${req.headers.host
(req.socket.encrypted ? "s" : "") + ? req.headers.host
"://" + : config.domain
(req.headers.host ? config.domain
? req.headers.host : "unknown.invalid"}`,
: config.domain
? config.domain
: "unknown.invalid"),
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);

View file

@ -581,66 +581,57 @@ 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><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><style>' + "</title>"
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;") + .replace(/>/g, "&gt;")}</h1><table id="directoryListing"> <tr> <th></th> <th>Filename</th> <th>Size</th> <th>Date</th> </tr>${checkPathLevel(decodeURIComponent(origHref)) < 1
'</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="' +
? ""
: '<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>" + `</table><p><i>${config
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;")) + .replace(/>/g, "&gt;")}</i></p>${customDirListingFooter}${!config.enableDirectoryListingWithDefaultHead || res.foot == ""
"</i></p>" + ? "</body></html>"
customDirListingFooter + : res.foot}`;
(!config.enableDirectoryListingWithDefaultHead || res.foot == ""
? "</body></html>"
: res.foot);
if ( if (
fs.existsSync( fs.existsSync(
@ -745,41 +736,26 @@ 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="' + `<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(
(href + "/" + encodeURI(ename)).replace( /\/+/g,
/\/+/g, "/"
"/", )}">${ename
) + .replace(/&/g, "&amp;")
'">' + .replace(/</g, "&lt;")
ename .replace(/>/g, "&gt;")}</a></td><td>-</td><td>${estats ? estats.mtime.toDateString() : "-"}</td></tr>\r\n`,
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.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(/\/+/g, "/") + ).replace(/\/+/g, "/")}${estats.isDirectory() ? "/" : ""}">${ename
(estats.isDirectory() ? "/" : "") +
'">' +
ename
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") + .replace(/>/g, "&gt;")}</a></td><td>${estats.isDirectory()
"</a></td><td>" + ? "-"
(estats.isDirectory() : sizify(estats.size.toString())}</td><td>${estats.mtime.toDateString()}</td></tr>\r\n`;
? "-"
: 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()) {
@ -788,20 +764,14 @@ module.exports = (req, res, logFacilities, config, next) => {
.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, "/") + ).replace(/\/+/g, "/")}">${ename
'">' +
ename
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") + .replace(/>/g, "&gt;")}</a></td><td>-</td><td>${estats.mtime.toDateString()}</td></tr>\r\n`;
"</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()) {
@ -943,8 +913,7 @@ module.exports = (req, res, logFacilities, config, next) => {
} else { } else {
res.error(501); res.error(501);
logFacilities.errmessage( logFacilities.errmessage(
name + `${name} doesn't support block devices, character devices, FIFOs nor sockets.`,
" doesn't support block devices, character devices, FIFOs nor sockets.",
); );
return; return;
} }

View file

@ -32,91 +32,40 @@ module.exports = (req, res, logFacilities, config, next) => {
//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: " + `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/>`;
new Date().toString() + statusBody += `OS uptime: ${formatRelativeTime(os.uptime())}<br/>`;
"<br/>Thread start time: " + statusBody += `Total request count: ${process.reqcounter}<br/>`;
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 += "Total request count: " + process.reqcounter + "<br/>";
statusBody += statusBody +=
"Average request rate: " + `Average request rate: ${Math.round((process.reqcounter / process.uptime()) * 100) / 100} requests/s<br/>`;
Math.round((process.reqcounter / process.uptime()) * 100) / 100 + statusBody += `Client errors (4xx): ${process.err4xxcounter}<br/>`;
" requests/s<br/>"; statusBody += `Server errors (5xx): ${process.err5xxcounter}<br/>`;
statusBody += "Client errors (4xx): " + process.err4xxcounter + "<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: " + `<br/>Memory usage of thread: ${sizify(process.memoryUsage().rss, true)}B`;
sizify(process.memoryUsage().rss, true) +
"B";
if (process.cpuUsage) if (process.cpuUsage)
statusBody += statusBody +=
"<br/>Total CPU usage by thread: u" + `<br/>Total CPU usage by thread: u${process.cpuUsage().user / 1000}ms s${process.cpuUsage().system / 1000}ms - ${Math.round(
process.cpuUsage().user / 1000 +
"ms s" +
process.cpuUsage().system / 1000 +
"ms - " +
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 == "" `${res.head == ""
? "<!DOCTYPE html><html><head><title>" + ? "<!DOCTYPE html><html><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><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 name
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
@ -125,13 +74,39 @@ module.exports = (req, res, logFacilities, config, next) => {
(req.headers.host == undefined (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;")) +
"</h1>" + "</title>"
statusBody + )}<h1>${name
(res.foot == "" ? "</body></html>" : res.foot), .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

@ -14,21 +14,18 @@ module.exports = (req, res, logFacilities, config, next) => {
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" + `http${req.socket.encrypted ? "s" : ""}://${req.headers.host
(req.socket.encrypted ? "s" : "") + ? req.headers.host
"://" + : config.domain
(req.headers.host ? config.domain
? req.headers.host : "unknown.invalid"}`,
: config.domain
? config.domain
: "unknown.invalid"),
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);
@ -40,7 +37,7 @@ module.exports = (req, res, logFacilities, config, next) => {
} }
} 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;

View file

@ -80,14 +80,11 @@ module.exports = (req, res, logFacilities, config, next) => {
try { try {
req.parsedURL = new URL( req.parsedURL = new URL(
req.url, req.url,
"http" + `http${req.socket.encrypted ? "s" : ""}://${req.headers.host
(req.socket.encrypted ? "s" : "") + ? req.headers.host
"://" + : config.domain
(req.headers.host ? config.domain
? req.headers.host : "unknown.invalid"}`,
: config.domain
? config.domain
: "unknown.invalid"),
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);
@ -115,20 +112,17 @@ module.exports = (req, res, logFacilities, config, next) => {
let rewrittenAgainURL = let rewrittenAgainURL =
sHref + req.parsedURL.search + req.parsedURL.hash; sHref + req.parsedURL.search + req.parsedURL.hash;
logFacilities.resmessage( logFacilities.resmessage(
"URL sanitized: " + req.url + " => " + rewrittenAgainURL, `URL sanitized: ${req.url} => ${rewrittenAgainURL}`,
); );
req.url = rewrittenAgainURL; req.url = rewrittenAgainURL;
try { try {
req.parsedURL = new URL( req.parsedURL = new URL(
req.url, req.url,
"http" + `http${req.socket.encrypted ? "s" : ""}://${req.headers.host
(req.socket.encrypted ? "s" : "") + ? req.headers.host
"://" + : config.domain
(req.headers.host ? config.domain
? req.headers.host : "unknown.invalid"}`,
: config.domain
? config.domain
: "unknown.invalid"),
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);

View file

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