From 2f783ce1a2e78d887c2e589e80976886e6dd4bcc Mon Sep 17 00:00:00 2001 From: Dorian Niemiec Date: Mon, 26 Aug 2024 19:23:52 +0200 Subject: [PATCH] Lint out the codebase --- src/handlers/clientErrorHandler.js | 43 ++--- src/handlers/noproxyHandler.js | 19 ++- src/handlers/proxyHandler.js | 19 ++- src/handlers/requestHandler.js | 35 +++-- src/index.js | 120 +++++++------- src/middleware/defaultHandlerChecks.js | 19 ++- .../nonStandardCodesAndHttpAuthentication.js | 7 +- src/middleware/rewriteURL.js | 28 ++-- .../staticFileServingAndDirectoryListings.js | 148 ++++++++++-------- src/middleware/status.js | 109 ++++++------- src/middleware/urlSanitizer.js | 20 ++- src/middleware/webRootPostfixes.js | 24 +-- src/utils/generateServerString.js | 8 +- 13 files changed, 326 insertions(+), 273 deletions(-) diff --git a/src/handlers/clientErrorHandler.js b/src/handlers/clientErrorHandler.js index 679dafe..f21fc99 100644 --- a/src/handlers/clientErrorHandler.js +++ b/src/handlers/clientErrorHandler.js @@ -268,11 +268,11 @@ function clientErrorHandler(err, socket) { .replace( /{errorMessage}/g, errorCode.toString() + - " " + - http.STATUS_CODES[errorCode] - .replace(/&/g, "&") - .replace(//g, ">") + " " + + http.STATUS_CODES[errorCode] + .replace(/&/g, "&") + .replace(//g, ">"), ) .replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode]) .replace( @@ -284,7 +284,7 @@ function clientErrorHandler(err, socket) { .replace(/\r\n/g, "
") .replace(/\n/g, "
") .replace(/\r/g, "
") - .replace(/ {2}/g, "  ") + .replace(/ {2}/g, "  "), ) .replace( /{server}/g, @@ -296,7 +296,7 @@ function clientErrorHandler(err, socket) { ) .replace(/&/g, "&") .replace(//g, ">") + .replace(/>/g, ">"), ) .replace( /{contact}/g, @@ -305,7 +305,7 @@ function clientErrorHandler(err, socket) { .replace(//g, ">") .replace(/\./g, "[dot]") - .replace(/@/g, "[at]") + .replace(/@/g, "[at]"), )}`, ); res.end(); @@ -377,11 +377,11 @@ function clientErrorHandler(err, socket) { } res.writeHead(errorCode, http.STATUS_CODES[errorCode], cheaders); res.write( - ( - `{errorMessage}

{errorMessage}

{errorDesc}

${additionalError == 404 + `{errorMessage}

{errorMessage}

{errorDesc}

${ + additionalError == 404 ? "" - : "

Additionally, a {additionalError} error occurred while loading an error page.

"}

{server}

` - ) + : "

Additionally, a {additionalError} error occurred while loading an error page.

" + }

{server}

` .replace( /{errorMessage}/g, errorCode.toString() + @@ -438,16 +438,19 @@ function clientErrorHandler(err, socket) { process.reqcounter++; process.malformedcounter++; logFacilities.locmessage( - `Somebody connected to ${config.secure && fromMain - ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport - : (typeof config.port == "number" ? "port " : "socket ") + - config.port}...`, + `Somebody connected to ${ + config.secure && fromMain + ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport + : (typeof config.port == "number" ? "port " : "socket ") + config.port + }...`, ); logFacilities.reqmessage( - `Client ${!reqip || reqip == "" - ? "[unknown client]" - : reqip + - (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")} sent invalid request.`, + `Client ${ + !reqip || reqip == "" + ? "[unknown client]" + : reqip + + (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "") + } sent invalid request.`, ); try { head = fs.existsSync("./.head") diff --git a/src/handlers/noproxyHandler.js b/src/handlers/noproxyHandler.js index fe71178..76e3916 100644 --- a/src/handlers/noproxyHandler.js +++ b/src/handlers/noproxyHandler.js @@ -33,16 +33,19 @@ function noproxyHandler(req, socket, head) { var reqport = socket.remotePort; process.reqcounter++; logFacilities.locmessage( - `Somebody connected to ${config.secure - ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport - : (typeof config.port == "number" ? "port " : "socket ") + - config.port}...`, + `Somebody connected to ${ + config.secure + ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport + : (typeof config.port == "number" ? "port " : "socket ") + config.port + }...`, ); logFacilities.reqmessage( - `Client ${!reqip || reqip == "" - ? "[unknown client]" - : reqip + - (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")} wants to proxy ${req.url} through this server`, + `Client ${ + !reqip || reqip == "" + ? "[unknown client]" + : reqip + + (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "") + } wants to proxy ${req.url} through this server`, ); if (req.headers["user-agent"] != undefined) logFacilities.reqmessage("Client uses " + req.headers["user-agent"]); diff --git a/src/handlers/proxyHandler.js b/src/handlers/proxyHandler.js index 0f88c7e..c6a8f04 100644 --- a/src/handlers/proxyHandler.js +++ b/src/handlers/proxyHandler.js @@ -39,16 +39,19 @@ function proxyHandler(req, socket, head) { var reqport = socket.remotePort; process.reqcounter++; logFacilities.locmessage( - `Somebody connected to ${config.secure - ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport - : (typeof config.port == "number" ? "port " : "socket ") + - config.port}...`, + `Somebody connected to ${ + config.secure + ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport + : (typeof config.port == "number" ? "port " : "socket ") + config.port + }...`, ); logFacilities.reqmessage( - `Client ${!reqip || reqip == "" - ? "[unknown client]" - : reqip + - (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")} wants to proxy ${req.url} through this server`, + `Client ${ + !reqip || reqip == "" + ? "[unknown client]" + : reqip + + (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "") + } wants to proxy ${req.url} through this server`, ); if (req.headers["user-agent"] != undefined) logFacilities.reqmessage("Client uses " + req.headers["user-agent"]); diff --git a/src/handlers/requestHandler.js b/src/handlers/requestHandler.js index 130ab40..04bda74 100644 --- a/src/handlers/requestHandler.js +++ b/src/handlers/requestHandler.js @@ -134,9 +134,7 @@ function requestHandler(req, res) { req.socket.remoteAddress == "::1" || req.socket.remoteAddress == "::ffff:127.0.0.1" || req.socket.remoteAddress == "127.0.0.1" || - req.socket.remoteAddress == "localhost" || - req.socket.remoteAddress == host || - req.socket.remoteAddress == "::ffff:" + host) + req.socket.remoteAddress == "localhost") ) { let headers = config.getCustomHeaders(); res.writeHead(204, http.STATUS_CODES[204], headers); @@ -204,10 +202,11 @@ function requestHandler(req, res) { req.isProxy = false; if (req.url[0] != "/" && req.url != "*") req.isProxy = true; logFacilities.locmessage( - `Somebody connected to ${config.secure && fromMain - ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport - : (typeof config.port == "number" ? "port " : "socket ") + - config.port}...`, + `Somebody connected to ${ + config.secure && fromMain + ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport + : (typeof config.port == "number" ? "port " : "socket ") + config.port + }...`, ); if (req.socket == null) { @@ -267,10 +266,13 @@ function requestHandler(req, res) { } logFacilities.reqmessage( - `Client ${!reqip || reqip == "" - ? "[unknown client]" - : reqip + - (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")} wants ${req.method == "GET" + `Client ${ + !reqip || reqip == "" + ? "[unknown client]" + : reqip + + (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "") + } wants ${ + req.method == "GET" ? "content in " : req.method == "POST" ? "to post content in " @@ -280,7 +282,8 @@ function requestHandler(req, res) { ? "to delete content in " : req.method == "PATCH" ? "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) 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.write( - ( - `{errorMessage}

{errorMessage}

{errorDesc}

${additionalError == 404 + `{errorMessage}

{errorMessage}

{errorDesc}

${ + additionalError == 404 ? "" - : "

Additionally, a {additionalError} error occurred while loading an error page.

"}

{server}

` - ) + : "

Additionally, a {additionalError} error occurred while loading an error page.

" + }

{server}

` .replace( /{errorMessage}/g, errorCode.toString() + diff --git a/src/index.js b/src/index.js index 31e1abb..16acf50 100644 --- a/src/index.js +++ b/src/index.js @@ -657,8 +657,7 @@ if (!disableMods) { if (mod.modInfo) modInfos.push(mod.modInfo); else { modInfos.push({ - name: - `Unknown mod (${modFileRaw}; module.exports.modInfo not set)`, + name: `Unknown mod (${modFileRaw}; module.exports.modInfo not set)`, version: "ERROR", }); } @@ -772,12 +771,15 @@ if (!disableMods) { if (fs.existsSync(SSJSPath) && fs.statSync(SSJSPath).isFile()) { try { // Prepend necessary modules and variables to the custom server side script - 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${hexstrbase64 === undefined + 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${ + hexstrbase64 === undefined ? "" - : "var hexstrbase64 = require('../hexstrbase64/index.js');\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`; + : "var hexstrbase64 = require('../hexstrbase64/index.js');\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 = "\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 @@ -872,9 +874,11 @@ function listeningMessage() { if (process.serverConfig.secure && (sListenToLocalhost || sListenToAny)) { if (typeof process.serverConfig.sport === "number") { serverconsole.locmessage( - `* https://localhost${process.serverConfig.sport == 443 - ? "" - : ":" + process.serverConfig.sport}`, + `* https://localhost${ + process.serverConfig.sport == 443 + ? "" + : ":" + process.serverConfig.sport + }`, ); } else { serverconsole.locmessage("* " + process.serverConfig.sport); // Unix socket or Windows named pipe @@ -889,9 +893,9 @@ function listeningMessage() { ) { if (typeof process.serverConfig.port === "number") { serverconsole.locmessage( - `* http://localhost${process.serverConfig.port == 80 - ? "" - : ":" + process.serverConfig.port}`, + `* http://localhost${ + process.serverConfig.port == 80 ? "" : ":" + process.serverConfig.port + }`, ); } else { serverconsole.locmessage("* " + process.serverConfig.port); // Unix socket or Windows named pipe @@ -904,9 +908,11 @@ function listeningMessage() { (!sListenToAny || (host != "" && host != "[offline]")) ) serverconsole.locmessage( - `* https://${sAccHost.indexOf(":") > -1 ? "[" + sAccHost + "]" : sAccHost}${process.serverConfig.sport == 443 - ? "" - : ":" + process.serverConfig.sport}`, + `* https://${sAccHost.indexOf(":") > -1 ? "[" + sAccHost + "]" : sAccHost}${ + process.serverConfig.sport == 443 + ? "" + : ":" + process.serverConfig.sport + }`, ); if ( !( @@ -918,17 +924,19 @@ function listeningMessage() { typeof process.serverConfig.port === "number" ) serverconsole.locmessage( - `* http://${accHost.indexOf(":") > -1 ? "[" + accHost + "]" : accHost}${process.serverConfig.port == 80 - ? "" - : ":" + process.serverConfig.port}`, + `* http://${accHost.indexOf(":") > -1 ? "[" + accHost + "]" : accHost}${ + process.serverConfig.port == 80 ? "" : ":" + process.serverConfig.port + }`, ); ipStatusCallback(() => { if (pubip != "") { if (process.serverConfig.secure && !sListenToLocalhost) serverconsole.locmessage( - `* https://${pubip.indexOf(":") > -1 ? "[" + pubip + "]" : pubip}${process.serverConfig.spubport == 443 - ? "" - : ":" + process.serverConfig.spubport}`, + `* https://${pubip.indexOf(":") > -1 ? "[" + pubip + "]" : pubip}${ + process.serverConfig.spubport == 443 + ? "" + : ":" + process.serverConfig.spubport + }`, ); if ( !( @@ -938,17 +946,21 @@ function listeningMessage() { !listenToLocalhost ) serverconsole.locmessage( - `* http://${pubip.indexOf(":") > -1 ? "[" + pubip + "]" : pubip}${process.serverConfig.pubport == 80 - ? "" - : ":" + process.serverConfig.pubport}`, + `* http://${pubip.indexOf(":") > -1 ? "[" + pubip + "]" : pubip}${ + process.serverConfig.pubport == 80 + ? "" + : ":" + process.serverConfig.pubport + }`, ); } if (domain != "") { if (process.serverConfig.secure && !sListenToLocalhost) serverconsole.locmessage( - `* https://${domain}${process.serverConfig.spubport == 443 - ? "" - : ":" + process.serverConfig.spubport}`, + `* https://${domain}${ + process.serverConfig.spubport == 443 + ? "" + : ":" + process.serverConfig.spubport + }`, ); if ( !( @@ -958,9 +970,11 @@ function listeningMessage() { !listenToLocalhost ) serverconsole.locmessage( - `* http://${domain}${process.serverConfig.pubport == 80 - ? "" - : ":" + process.serverConfig.pubport}`, + `* http://${domain}${ + process.serverConfig.pubport == 80 + ? "" + : ":" + process.serverConfig.pubport + }`, ); } serverconsole.locmessage('For CLI help, you can type "help"'); @@ -1248,9 +1262,7 @@ let commands = { mods: (args, log) => { log("Mods:"); for (let i = 0; i < modInfos.length; i++) { - log( - `${(i + 1).toString()}. ${modInfos[i].name} ${modInfos[i].version}`, - ); + log(`${(i + 1).toString()}. ${modInfos[i].name} ${modInfos[i].version}`); } if (modInfos.length == 0) { log("No mods installed."); @@ -1823,23 +1835,27 @@ function start(init) { ) ) serverconsole.locmessage( - `Starting HTTP server at ${typeof process.serverConfig.port == "number" - ? listenAddress - ? (listenAddress.indexOf(":") > -1 - ? "[" + listenAddress + "]" - : listenAddress) + ":" - : "port " - : ""}${process.serverConfig.port.toString()}...`, + `Starting HTTP server at ${ + typeof process.serverConfig.port == "number" + ? listenAddress + ? (listenAddress.indexOf(":") > -1 + ? "[" + listenAddress + "]" + : listenAddress) + ":" + : "port " + : "" + }${process.serverConfig.port.toString()}...`, ); if (process.serverConfig.secure) serverconsole.locmessage( - `Starting HTTPS server at ${typeof process.serverConfig.sport == "number" - ? sListenAddress - ? (sListenAddress.indexOf(":") > -1 - ? "[" + sListenAddress + "]" - : sListenAddress) + ":" - : "port " - : ""}${process.serverConfig.sport.toString()}...`, + `Starting HTTPS server at ${ + typeof process.serverConfig.sport == "number" + ? sListenAddress + ? (sListenAddress.indexOf(":") > -1 + ? "[" + sListenAddress + "]" + : sListenAddress) + ":" + : "port " + : "" + }${process.serverConfig.sport.toString()}...`, ); } @@ -1997,9 +2013,7 @@ function start(init) { } } catch (err) { if (line != "") { - process.send( - `Can't execute command \"${line.split(" ")[0]}".`, - ); + process.send(`Can't execute command \"${line.split(" ")[0]}".`); process.send("\x12END"); } } @@ -2065,9 +2079,7 @@ function start(init) { cluster.workers[clusterID].removeAllListeners("message"); addListenersToWorker(cluster.workers[clusterID]); } - serverconsole.climessage( - `Can't run command "${command}".`, - ); + serverconsole.climessage(`Can't run command "${command}".`); } }); if (command == "stop") { diff --git a/src/middleware/defaultHandlerChecks.js b/src/middleware/defaultHandlerChecks.js index 5597727..60645d8 100644 --- a/src/middleware/defaultHandlerChecks.js +++ b/src/middleware/defaultHandlerChecks.js @@ -12,14 +12,17 @@ module.exports = (req, res, logFacilities, config, next) => { `Proxy not implemented

Proxy not implemented

${name .replace(/&/g, "&") .replace(//g, ">")} 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, "&") - .replace(//g, ">")} as a proxy.

${config - .generateServerString() - .replace(/&/g, "&") - .replace(//g, ">")}

`, + .replace( + />/g, + ">", + )} 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, "&") + .replace(//g, ">")} as a proxy.

${config + .generateServerString() + .replace(/&/g, "&") + .replace(//g, ">")}

`, ); res.end(); logFacilities.errmessage( diff --git a/src/middleware/nonStandardCodesAndHttpAuthentication.js b/src/middleware/nonStandardCodesAndHttpAuthentication.js index 844a5d5..fe6f666 100644 --- a/src/middleware/nonStandardCodesAndHttpAuthentication.js +++ b/src/middleware/nonStandardCodesAndHttpAuthentication.js @@ -269,10 +269,11 @@ module.exports = (req, res, logFacilities, config, next) => { const authorizedCallback = (bruteProtection) => { try { const ha = config.getCustomHeaders(); - ha["WWW-Authenticate"] = - `Basic realm="${authcode.realm + ha["WWW-Authenticate"] = `Basic realm="${ + authcode.realm ? authcode.realm.replace(/(\\|")/g, "\\$1") - : name + " HTTP Basic Authorization"}", charset="UTF-8"`; + : name + " HTTP Basic Authorization" + }", charset="UTF-8"`; const credentials = req.headers["authorization"]; if (!credentials) { res.error(401, ha); diff --git a/src/middleware/rewriteURL.js b/src/middleware/rewriteURL.js index 2ca190b..fff02f3 100644 --- a/src/middleware/rewriteURL.js +++ b/src/middleware/rewriteURL.js @@ -86,18 +86,18 @@ module.exports = (req, res, logFacilities, config, next) => { return; } if (rewrittenURL != req.url) { - logFacilities.resmessage( - `URL rewritten: ${req.url} => ${rewrittenURL}`, - ); + logFacilities.resmessage(`URL rewritten: ${req.url} => ${rewrittenURL}`); req.url = rewrittenURL; try { req.parsedURL = new URL( req.url, - `http${req.socket.encrypted ? "s" : ""}://${req.headers.host - ? req.headers.host - : config.domain - ? config.domain - : "unknown.invalid"}`, + `http${req.socket.encrypted ? "s" : ""}://${ + req.headers.host + ? req.headers.host + : config.domain + ? config.domain + : "unknown.invalid" + }`, ); } catch (err) { res.error(400, err); @@ -131,11 +131,13 @@ module.exports = (req, res, logFacilities, config, next) => { try { req.parsedURL = new URL( req.url, - `http${req.socket.encrypted ? "s" : ""}://${req.headers.host - ? req.headers.host - : config.domain - ? config.domain - : "unknown.invalid"}`, + `http${req.socket.encrypted ? "s" : ""}://${ + req.headers.host + ? req.headers.host + : config.domain + ? config.domain + : "unknown.invalid" + }`, ); } catch (err) { res.error(400, err); diff --git a/src/middleware/staticFileServingAndDirectoryListings.js b/src/middleware/staticFileServingAndDirectoryListings.js index b72f44c..697b373 100644 --- a/src/middleware/staticFileServingAndDirectoryListings.js +++ b/src/middleware/staticFileServingAndDirectoryListings.js @@ -580,58 +580,66 @@ module.exports = (req, res, logFacilities, config, next) => { ); // Generate HTML head and footer based on configuration and custom content - let htmlHead = - `${(!config.enableDirectoryListingWithDefaultHead || res.head == "" + let htmlHead = `${ + (!config.enableDirectoryListingWithDefaultHead || res.head == "" ? !headerHasHTMLTag ? "Directory: " + - decodeURIComponent(origHref) - .replace(/&/g, "&") - .replace(/</g, "<") - .replace(/>/g, ">") + - '" - : customDirListingHeader.replace( - //i, - "Directory: " + decodeURIComponent(origHref) .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") + - "" - ) + '" + : customDirListingHeader.replace( + //i, + "Directory: " + + decodeURIComponent(origHref) + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + + "", + ) : res.head.replace( - //i, - "Directory: " + - decodeURIComponent(origHref) - .replace(/&/g, "&") - .replace(/</g, "<") - .replace(/>/g, ">") + - "" - )) + - (!headerHasHTMLTag ? customDirListingHeader : "")}

Directory: ${decodeURIComponent(origHref) - .replace(/&/g, "&") - .replace(//g, ">")}

${checkPathLevel(decodeURIComponent(origHref)) < 1 - ? "" - : '
Filename Size Date
[RET]Directory: " + + decodeURIComponent(origHref) + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + + "", + )) + (!headerHasHTMLTag ? customDirListingHeader : "") + }

Directory: ${decodeURIComponent(origHref) + .replace(/&/g, "&") + .replace(//g, + ">", + )}

${ + checkPathLevel(decodeURIComponent(origHref)) < 1 + ? "" + : ''}`; + '">Return' + }`; - let htmlFoot = - `
Filename Size Date
[RET]Return

${config - .generateServerString() - .replace(/&/g, "&") - .replace(//g, ">")}${req.headers.host == undefined - ? "" - : " on " + + let htmlFoot = `

${config + .generateServerString() + .replace(/&/g, "&") + .replace(//g, ">")}${ + req.headers.host == undefined + ? "" + : " on " + String(req.headers.host) .replace(/&/g, "&") .replace(//g, ">")}

${customDirListingFooter}${!config.enableDirectoryListingWithDefaultHead || res.foot == "" - ? "" - : res.foot}`; + .replace(/>/g, ">") + }

${customDirListingFooter}${ + !config.enableDirectoryListingWithDefaultHead || res.foot == "" + ? "" + : res.foot + }`; if ( fs.existsSync( @@ -736,26 +744,34 @@ module.exports = (req, res, logFacilities, config, next) => { const emime = eext ? mime.contentType(eext) : false; if (filelist[i].errored) { directoryListingRows.push( - `[BAD]${ename + `[BAD]${ename .replace(/&/g, "&") .replace(//g, ">")}-${estats ? estats.mtime.toDateString() : "-"}\r\n`, + .replace( + />/g, + ">", + )}-${estats ? estats.mtime.toDateString() : "-"}\r\n`, ); } else { - let entry = - `[alt]${ename - .replace(/&/g, "&") - .replace(//g, ">")}${estats.isDirectory() - ? "-" - : sizify(estats.size.toString())}${estats.mtime.toDateString()}\r\n`; + let entry = `[alt]${ename + .replace(/&/g, "&") + .replace(//g, ">")}${ + estats.isDirectory() + ? "-" + : sizify(estats.size.toString()) + }${estats.mtime.toDateString()}\r\n`; // Determine the file type and set the appropriate image and alt text if (estats.isDirectory()) { @@ -763,15 +779,17 @@ module.exports = (req, res, logFacilities, config, next) => { .replace("[img]", "/.dirimages/directory.png") .replace("[alt]", "[DIR]"); } else if (!estats.isFile()) { - entry = - `[alt]${ename - .replace(/&/g, "&") - .replace(//g, ">")}-${estats.mtime.toDateString()}\r\n`; + entry = `[alt]${ename + .replace(/&/g, "&") + .replace(//g, + ">", + )}-${estats.mtime.toDateString()}\r\n`; // Determine the special file types (block device, character device, etc.) if (estats.isBlockDevice()) { diff --git a/src/middleware/status.js b/src/middleware/status.js index f1b4ef0..af97187 100644 --- a/src/middleware/status.js +++ b/src/middleware/status.js @@ -31,82 +31,83 @@ module.exports = (req, res, logFacilities, config, next) => { "Server version: " + config.generateServerString() + "

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

${name + .replace(/&/g, "&") + .replace(//g, ">")} status${ + req.headers.host == undefined ? "" : " for " + - String(req.headers.host) - .replace(/&/g, "&") - .replace(//g, ">")) + - '" - : res.head.replace( - //i, - "" + - name - .replace(/&/g, "&") - .replace(/</g, "<") - .replace(/>/g, ">") + - " status" + - (req.headers.host == undefined - ? "" - : " for " + String(req.headers.host) .replace(/&/g, "&") .replace(/</g, "<") - .replace(/>/g, ">")) + - "" - )}

${name - .replace(/&/g, "&") - .replace(//g, ">")} status${req.headers.host == undefined - ? "" - : " for " + - String(req.headers.host) - .replace(/&/g, "&") - .replace(//g, ">")}

${statusBody}${res.foot == "" ? "" : res.foot}`, + .replace(/>/g, ">") + }${statusBody}${res.foot == "" ? "" : res.foot}`, ); return; } diff --git a/src/middleware/urlSanitizer.js b/src/middleware/urlSanitizer.js index 7f21f9e..cf866cf 100644 --- a/src/middleware/urlSanitizer.js +++ b/src/middleware/urlSanitizer.js @@ -13,19 +13,19 @@ module.exports = (req, res, logFacilities, config, next) => { if (req.parsedURL.pathname != sanitizedHref && !req.isProxy) { let sanitizedURL = sanitizedHref + req.parsedURL.search + req.parsedURL.hash; - logFacilities.resmessage( - `URL sanitized: ${req.url} => ${sanitizedURL}`, - ); + logFacilities.resmessage(`URL sanitized: ${req.url} => ${sanitizedURL}`); if (config.rewriteDirtyURLs) { req.url = sanitizedURL; try { req.parsedURL = new URL( req.url, - `http${req.socket.encrypted ? "s" : ""}://${req.headers.host - ? req.headers.host - : config.domain - ? config.domain - : "unknown.invalid"}`, + `http${req.socket.encrypted ? "s" : ""}://${ + req.headers.host + ? req.headers.host + : config.domain + ? config.domain + : "unknown.invalid" + }`, ); } catch (err) { res.error(400, err); @@ -36,9 +36,7 @@ module.exports = (req, res, logFacilities, config, next) => { return; } } else if (req.url != preparedReqUrl && !req.isProxy) { - logFacilities.resmessage( - `URL sanitized: ${req.url} => ${preparedReqUrl}`, - ); + logFacilities.resmessage(`URL sanitized: ${req.url} => ${preparedReqUrl}`); if (config.rewriteDirtyURLs) { req.url = preparedReqUrl; } else { diff --git a/src/middleware/webRootPostfixes.js b/src/middleware/webRootPostfixes.js index 24af9f4..92cfcc6 100644 --- a/src/middleware/webRootPostfixes.js +++ b/src/middleware/webRootPostfixes.js @@ -80,11 +80,13 @@ module.exports = (req, res, logFacilities, config, next) => { try { req.parsedURL = new URL( req.url, - `http${req.socket.encrypted ? "s" : ""}://${req.headers.host - ? req.headers.host - : config.domain - ? config.domain - : "unknown.invalid"}`, + `http${req.socket.encrypted ? "s" : ""}://${ + req.headers.host + ? req.headers.host + : config.domain + ? config.domain + : "unknown.invalid" + }`, ); } catch (err) { res.error(400, err); @@ -118,11 +120,13 @@ module.exports = (req, res, logFacilities, config, next) => { try { req.parsedURL = new URL( req.url, - `http${req.socket.encrypted ? "s" : ""}://${req.headers.host - ? req.headers.host - : config.domain - ? config.domain - : "unknown.invalid"}`, + `http${req.socket.encrypted ? "s" : ""}://${ + req.headers.host + ? req.headers.host + : config.domain + ? config.domain + : "unknown.invalid" + }`, ); } catch (err) { res.error(400, err); diff --git a/src/utils/generateServerString.js b/src/utils/generateServerString.js index 874a228..ccd5a74 100644 --- a/src/utils/generateServerString.js +++ b/src/utils/generateServerString.js @@ -4,9 +4,11 @@ const getOS = require("./getOS.js"); function generateServerString(exposeServerVersion) { return exposeServerVersion - ? `${name.replace(/ /g, "-")}/${version} (${getOS()}; ${process.isBun - ? "Bun/v" + process.versions.bun + "; like Node.JS/" + process.version - : "Node.JS/" + process.version})` + ? `${name.replace(/ /g, "-")}/${version} (${getOS()}; ${ + process.isBun + ? "Bun/v" + process.versions.bun + "; like Node.JS/" + process.version + : "Node.JS/" + process.version + })` : name.replace(/ /g, "-"); }