From c2eed2870df269b4547eda0868c28511cec10f1a Mon Sep 17 00:00:00 2001 From: Dorian Niemiec Date: Sun, 1 Sep 2024 21:54:42 +0200 Subject: [PATCH] style: style the code according to new Prettier rules --- src/handlers/clientErrorHandler.js | 50 ++-- src/handlers/noproxyHandler.js | 6 +- src/handlers/proxyHandler.js | 10 +- src/handlers/requestHandler.js | 50 ++-- src/handlers/serverErrorHandler.js | 8 +- src/index.js | 279 +++++++++--------- src/middleware/blocklist.js | 4 +- src/middleware/checkForbiddenPaths.js | 22 +- src/middleware/defaultHandlerChecks.js | 6 +- .../nonStandardCodesAndHttpAuthentication.js | 54 ++-- src/middleware/redirectTrailingSlashes.js | 2 +- src/middleware/redirects.js | 6 +- src/middleware/rewriteURL.js | 14 +- .../staticFileServingAndDirectoryListings.js | 100 +++---- src/middleware/status.js | 10 +- src/middleware/urlSanitizer.js | 4 +- src/middleware/webRootPostfixes.js | 12 +- src/res/httpErrorDescriptions.js | 2 +- src/res/logo.js | 2 +- src/res/serverErrorDescriptions.js | 2 +- src/utils/clusterBunShim.js | 24 +- src/utils/createRegex.js | 2 +- src/utils/forbiddenPaths.js | 7 +- src/utils/generateErrorStack.js | 7 +- src/utils/ipBlockList.js | 14 +- src/utils/ipSubnetUtils.js | 6 +- src/utils/legacyModWrapper.js | 6 +- src/utils/sendStatistics.js | 12 +- src/utils/serverconsole.js | 44 +-- src/utils/sha256.js | 10 +- src/utils/sizify.js | 4 +- src/utils/urlParser.js | 2 +- tests/middleware/blocklist.test.js | 14 +- tests/middleware/checkForbiddenPaths.test.js | 14 +- tests/middleware/defaultHandlerChecks.test.js | 10 +- ...StandardCodesAndHttpAuthentication.test.js | 64 ++-- .../redirectTrailingSlashes.test.js | 4 +- tests/middleware/redirects.test.js | 8 +- tests/middleware/responseHeaders.test.js | 4 +- tests/middleware/rewriteURL.test.js | 52 ++-- ...aticFileServingAndDirectoryListing.test.js | 32 +- tests/middleware/status.test.js | 12 +- tests/middleware/urlSanitizer.test.js | 18 +- tests/middleware/webRootPrefixes.test.js | 10 +- tests/utils/createRegex.test.js | 4 +- tests/utils/deepClone.test.js | 2 +- tests/utils/forbiddenPaths.test.js | 32 +- tests/utils/ipBlockList.test.js | 26 +- tests/utils/ipMatch.test.js | 18 +- tests/utils/ipSubnetUtils.test.js | 38 +-- tests/utils/sha256.test.js | 14 +- tests/utils/urlMojibakeFixer.test.js | 2 +- tests/utils/urlParser.test.js | 4 +- utils/loghighlight.js | 18 +- utils/logviewer.js | 26 +- utils/svrpasswd.js | 44 +-- 56 files changed, 623 insertions(+), 628 deletions(-) diff --git a/src/handlers/clientErrorHandler.js b/src/handlers/clientErrorHandler.js index 280431c..22c6da7 100644 --- a/src/handlers/clientErrorHandler.js +++ b/src/handlers/clientErrorHandler.js @@ -86,7 +86,7 @@ function clientErrorHandler(err, socket) { }); head += "\r\n"; res.write(head); - }, + } }; let reqIdInt = Math.floor(Math.random() * 16777216); @@ -102,7 +102,7 @@ function clientErrorHandler(err, socket) { errmessage: (msg) => serverconsole.errmessage(msg, reqId), locerrmessage: (msg) => serverconsole.locerrmessage(msg, reqId), locwarnmessage: (msg) => serverconsole.locwarnmessage(msg, reqId), - locmessage: (msg) => serverconsole.locmessage(msg, reqId), + locmessage: (msg) => serverconsole.locmessage(msg, reqId) }; socket.on("close", (hasError) => { @@ -158,7 +158,7 @@ function clientErrorHandler(err, socket) { stack ) { throw new TypeError( - "Error stack parameter needs to be either a string or an instance of Error object.", + "Error stack parameter needs to be either a string or an instance of Error object." ); } @@ -193,7 +193,7 @@ function clientErrorHandler(err, socket) { } catch (err2) { callServerError(500, err2); } - }, + } ); } else { try { @@ -246,7 +246,7 @@ function clientErrorHandler(err, socket) { stack = generateErrorStack(new Error("Unknown error")); if (errorCode == 500 || errorCode == 502) { logFacilities.errmessage( - "There was an error while processing the request!", + "There was an error while processing the request!" ); logFacilities.errmessage("Stack:"); logFacilities.errmessage(stack); @@ -275,7 +275,7 @@ function clientErrorHandler(err, socket) { http.STATUS_CODES[errorCode] .replace(/&/g, "&") .replace(//g, ">"), + .replace(/>/g, ">") ) .replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode]) .replace( @@ -287,7 +287,7 @@ function clientErrorHandler(err, socket) { .replace(/\r\n/g, "
") .replace(/\n/g, "
") .replace(/\r/g, "
") - .replace(/ {2}/g, "  "), + .replace(/ {2}/g, "  ") ) .replace( /{server}/g, @@ -299,7 +299,7 @@ function clientErrorHandler(err, socket) { ) .replace(/&/g, "&") .replace(//g, ">"), + .replace(/>/g, ">") ) .replace( /{contact}/g, @@ -308,8 +308,8 @@ function clientErrorHandler(err, socket) { .replace(//g, ">") .replace(/\./g, "[dot]") - .replace(/@/g, "[at]"), - )}`, + .replace(/@/g, "[at]") + )}` ); res.end(); } else { @@ -327,7 +327,7 @@ function clientErrorHandler(err, socket) { http.STATUS_CODES[errorCode] .replace(/&/g, "&") .replace(//g, ">"), + .replace(/>/g, ">") ) .replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode]) .replace( @@ -339,7 +339,7 @@ function clientErrorHandler(err, socket) { .replace(/\r\n/g, "
") .replace(/\n/g, "
") .replace(/\r/g, "
") - .replace(/ {2}/g, "  "), + .replace(/ {2}/g, "  ") ) .replace( /{server}/g, @@ -351,7 +351,7 @@ function clientErrorHandler(err, socket) { ) .replace(/&/g, "&") .replace(//g, ">"), + .replace(/>/g, ">") ) .replace( /{contact}/g, @@ -360,8 +360,8 @@ function clientErrorHandler(err, socket) { .replace(//g, ">") .replace(/\./g, "[dot]") - .replace(/@/g, "[at]"), - ), + .replace(/@/g, "[at]") + ) ); } catch (err) { let additionalError = 500; @@ -392,7 +392,7 @@ function clientErrorHandler(err, socket) { http.STATUS_CODES[errorCode] .replace(/&/g, "&") .replace(//g, ">"), + .replace(/>/g, ">") ) .replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode]) .replace( @@ -404,7 +404,7 @@ function clientErrorHandler(err, socket) { .replace(/\r\n/g, "
") .replace(/\n/g, "
") .replace(/\r/g, "
") - .replace(/ {2}/g, "  "), + .replace(/ {2}/g, "  ") ) .replace( /{server}/g, @@ -416,7 +416,7 @@ function clientErrorHandler(err, socket) { ) .replace(/&/g, "&") .replace(//g, ">"), + .replace(/>/g, ">") ) .replace( /{contact}/g, @@ -425,9 +425,9 @@ function clientErrorHandler(err, socket) { .replace(//g, ">") .replace(/\./g, "[dot]") - .replace(/@/g, "[at]"), + .replace(/@/g, "[at]") ) - .replace(/{additionalError}/g, additionalError.toString()), + .replace(/{additionalError}/g, additionalError.toString()) ); res.end(); } @@ -445,7 +445,7 @@ function clientErrorHandler(err, socket) { config.secure && fromMain ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport : (typeof config.port == "number" ? "port " : "socket ") + config.port - }...`, + }...` ); logFacilities.reqmessage( `Client ${ @@ -453,7 +453,7 @@ function clientErrorHandler(err, socket) { ? "[unknown client]" : reqip + (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "") - } sent invalid request.`, + } sent invalid request.` ); try { head = fs.existsSync("./.head") @@ -482,7 +482,7 @@ function clientErrorHandler(err, socket) { return; } else { logFacilities.errmessage( - `An SSL error occured: ${err.code ? err.code : err.message}`, + `An SSL error occured: ${err.code ? err.code : err.message}` ); callServerError(400); return; @@ -537,7 +537,7 @@ function clientErrorHandler(err, socket) { if (String(packetLine1[0]).indexOf(":") > 0) { if (!checkHeaders(true)) { logFacilities.errmessage( - "The request is invalid (it may be a part of larger invalid request).", + "The request is invalid (it may be a part of larger invalid request)." ); callServerError(400); // Also malformed Packet return; @@ -568,7 +568,7 @@ function clientErrorHandler(err, socket) { // eslint-disable-next-line no-unused-vars } catch (err) { logFacilities.errmessage( - "There was an error while determining type of malformed request.", + "There was an error while determining type of malformed request." ); callServerError(400); } diff --git a/src/handlers/noproxyHandler.js b/src/handlers/noproxyHandler.js index 1f5f126..7224bae 100644 --- a/src/handlers/noproxyHandler.js +++ b/src/handlers/noproxyHandler.js @@ -17,7 +17,7 @@ function noproxyHandler(req, socket, head) { errmessage: (msg) => serverconsole.errmessage(msg, reqId), locerrmessage: (msg) => serverconsole.locerrmessage(msg, reqId), locwarnmessage: (msg) => serverconsole.locwarnmessage(msg, reqId), - locmessage: (msg) => serverconsole.locmessage(msg, reqId), + locmessage: (msg) => serverconsole.locmessage(msg, reqId) }; socket.on("close", (hasError) => { @@ -37,7 +37,7 @@ function noproxyHandler(req, socket, head) { config.secure ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport : (typeof config.port == "number" ? "port " : "socket ") + config.port - }...`, + }...` ); logFacilities.reqmessage( `Client ${ @@ -45,7 +45,7 @@ function noproxyHandler(req, socket, head) { ? "[unknown client]" : reqip + (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "") - } wants to proxy ${req.url} through this server`, + } 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 87b5f45..828446c 100644 --- a/src/handlers/proxyHandler.js +++ b/src/handlers/proxyHandler.js @@ -20,7 +20,7 @@ function proxyHandler(req, socket, head) { errmessage: (msg) => serverconsole.errmessage(msg, reqId), locerrmessage: (msg) => serverconsole.locerrmessage(msg, reqId), locwarnmessage: (msg) => serverconsole.locwarnmessage(msg, reqId), - locmessage: (msg) => serverconsole.locmessage(msg, reqId), + locmessage: (msg) => serverconsole.locmessage(msg, reqId) }; socket.on("close", (hasError) => { @@ -43,7 +43,7 @@ function proxyHandler(req, socket, head) { config.secure ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport : (typeof config.port == "number" ? "port " : "socket ") + config.port - }...`, + }...` ); logFacilities.reqmessage( `Client ${ @@ -51,7 +51,7 @@ function proxyHandler(req, socket, head) { ? "[unknown client]" : reqip + (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "") - } wants to proxy ${req.url} through this server`, + } wants to proxy ${req.url} through this server` ); if (req.headers["user-agent"] != undefined) logFacilities.reqmessage(`Client uses ${req.headers["user-agent"]}`); @@ -69,7 +69,7 @@ function proxyHandler(req, socket, head) { currentMiddleware.proxy(req, socket, head, logFacilities, config, next); } catch (err) { logFacilities.errmessage( - "There was an error while processing the request!", + "There was an error while processing the request!" ); logFacilities.errmessage("Stack:"); logFacilities.errmessage(err.stack); @@ -78,7 +78,7 @@ function proxyHandler(req, socket, head) { } } else { 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"); } diff --git a/src/handlers/requestHandler.js b/src/handlers/requestHandler.js index be2fc14..2bce209 100644 --- a/src/handlers/requestHandler.js +++ b/src/handlers/requestHandler.js @@ -28,7 +28,7 @@ function requestHandler(req, res) { errmessage: (msg) => serverconsole.errmessage(msg, reqId), locerrmessage: (msg) => serverconsole.locerrmessage(msg, reqId), locwarnmessage: (msg) => serverconsole.locwarnmessage(msg, reqId), - locmessage: (msg) => serverconsole.locmessage(msg, reqId), + locmessage: (msg) => serverconsole.locmessage(msg, reqId) }; // SVR.JS configuration object (modified) @@ -116,7 +116,7 @@ function requestHandler(req, res) { req.headers[":method"] == undefined ) { let err = new Error( - 'Either ":path" or ":method" pseudoheader is missing.', + 'Either ":path" or ":method" pseudoheader is missing.' ); if (Buffer.alloc) err.rawPacket = Buffer.alloc(0); if (req.socket && req.socket.server) @@ -156,7 +156,7 @@ function requestHandler(req, res) { ) { if (headWritten) { process.emitWarning("res.writeHead called multiple times.", { - code: "WARN_SVRJS_MULTIPLE_WRITEHEAD", + code: "WARN_SVRJS_MULTIPLE_WRITEHEAD" }); return res; } else { @@ -166,11 +166,11 @@ function requestHandler(req, res) { if (code >= 400 && code <= 499) process.err4xxcounter++; else if (code >= 500 && code <= 599) process.err5xxcounter++; logFacilities.errmessage( - "Server responded with " + code.toString() + " code.", + "Server responded with " + code.toString() + " code." ); } else { logFacilities.resmessage( - "Server responded with " + code.toString() + " code.", + "Server responded with " + code.toString() + " code." ); } if (typeof codeDescription != "string" && http.STATUS_CODES[code]) { @@ -203,7 +203,7 @@ function requestHandler(req, res) { config.secure && fromMain ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport : (typeof config.port == "number" ? "port " : "socket ") + config.port - }...`, + }...` ); if (req.socket == null) { @@ -281,13 +281,13 @@ function requestHandler(req, res) { : 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}`, + }${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"]}`); if (oldHostHeader && oldHostHeader != req.headers.host) logFacilities.resmessage( - `Host name rewritten: ${oldHostHeader} => ${req.headers.host}`, + `Host name rewritten: ${oldHostHeader} => ${req.headers.host}` ); // Header and footer placeholders @@ -332,7 +332,7 @@ function requestHandler(req, res) { stack ) { throw new TypeError( - "Error stack parameter needs to be either a string or an instance of Error object.", + "Error stack parameter needs to be either a string or an instance of Error object." ); } @@ -357,7 +357,7 @@ function requestHandler(req, res) { } catch (err2) { res.error(500, err2); } - }, + } ); } else { try { @@ -418,7 +418,7 @@ function requestHandler(req, res) { if (errorCode == 500 || errorCode == 502) { logFacilities.errmessage( - "There was an error while processing the request!", + "There was an error while processing the request!" ); logFacilities.errmessage("Stack:"); logFacilities.errmessage(stack); @@ -455,7 +455,7 @@ function requestHandler(req, res) { http.STATUS_CODES[errorCode] .replace(/&/g, "&") .replace(//g, ">"), + .replace(/>/g, ">") ) .replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode]) .replace( @@ -467,14 +467,14 @@ function requestHandler(req, res) { .replace(/\r\n/g, "
") .replace(/\n/g, "
") .replace(/\r/g, "
") - .replace(/ {2}/g, "  "), + .replace(/ {2}/g, "  ") ) .replace( /{path}/g, req.url .replace(/&/g, "&") .replace(//g, ">"), + .replace(/>/g, ">") ) .replace( /{server}/g, @@ -494,7 +494,7 @@ function requestHandler(req, res) { String(req.headers.host) .replace(/&/g, "&") .replace(//g, ">")), + .replace(/>/g, ">")) ) .replace( /{contact}/g, @@ -503,8 +503,8 @@ function requestHandler(req, res) { .replace(//g, ">") .replace(/\./g, "[dot]") - .replace(/@/g, "[at]"), - ), + .replace(/@/g, "[at]") + ) ); // Replace placeholders in error response } catch (err) { let additionalError = 500; @@ -537,7 +537,7 @@ function requestHandler(req, res) { http.STATUS_CODES[errorCode] .replace(/&/g, "&") .replace(//g, ">"), + .replace(/>/g, ">") ) .replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode]) .replace( @@ -549,14 +549,14 @@ function requestHandler(req, res) { .replace(/\r\n/g, "
") .replace(/\n/g, "
") .replace(/\r/g, "
") - .replace(/ {2}/g, "  "), + .replace(/ {2}/g, "  ") ) .replace( /{path}/g, req.url .replace(/&/g, "&") .replace(//g, ">"), + .replace(/>/g, ">") ) .replace( /{server}/g, @@ -576,7 +576,7 @@ function requestHandler(req, res) { String(req.headers.host) .replace(/&/g, "&") .replace(//g, ">")), + .replace(/>/g, ">")) ) .replace( /{contact}/g, @@ -585,9 +585,9 @@ function requestHandler(req, res) { .replace(//g, ">") .replace(/\./g, "[dot]") - .replace(/@/g, "[at]"), + .replace(/@/g, "[at]") ) - .replace(/{additionalError}/g, additionalError.toString()), + .replace(/{additionalError}/g, additionalError.toString()) ); // Replace placeholders in error response res.end(); } @@ -676,7 +676,7 @@ function requestHandler(req, res) { // CONNECT requests should be handled in "connect" event. res.error(501); logFacilities.errmessage( - "CONNECT requests aren't supported. Your JS runtime probably doesn't support 'connect' handler for HTTP library.", + "CONNECT requests aren't supported. Your JS runtime probably doesn't support 'connect' handler for HTTP library." ); return; } @@ -697,7 +697,7 @@ function requestHandler(req, res) { ? req.headers.host : config.domain ? config.domain - : "unknown.invalid"), + : "unknown.invalid") ); } catch (err) { res.error(400, err); diff --git a/src/handlers/serverErrorHandler.js b/src/handlers/serverErrorHandler.js index c71ecbc..94b6cf9 100644 --- a/src/handlers/serverErrorHandler.js +++ b/src/handlers/serverErrorHandler.js @@ -12,15 +12,15 @@ function serverErrorHandler(err, isRedirect, server, start) { serverconsole.locerrmessage( serverErrorDescs[err.code] ? serverErrorDescs[err.code] - : serverErrorDescs["UNKNOWN"], + : serverErrorDescs["UNKNOWN"] ); serverconsole.locmessage( - `${isRedirect ? attmtsRedir : attmts} attempts left.`, + `${isRedirect ? attmtsRedir : attmts} attempts left.` ); } else { try { process.send( - "\x12ERRLIST" + (isRedirect ? attmtsRedir : attmts) + err.code, + "\x12ERRLIST" + (isRedirect ? attmtsRedir : attmts) + err.code ); // eslint-disable-next-line no-unused-vars } catch (err) { @@ -59,7 +59,7 @@ process.messageEventListeners.push((worker, serverconsole) => { serverconsole.locerrmessage( serverErrorDescs[errCode] ? serverErrorDescs[errCode] - : serverErrorDescs["UNKNOWN"], + : serverErrorDescs["UNKNOWN"] ); serverconsole.locmessage(`${tries} attempts left.`); } diff --git a/src/index.js b/src/index.js index a30338b..3485a06 100644 --- a/src/index.js +++ b/src/index.js @@ -22,7 +22,7 @@ try { tar = require("tar"); } catch (err) { tar = { - _errored: err, + _errored: err }; } @@ -57,7 +57,7 @@ try { }; } let crypto = { - __disabled__: null, + __disabled__: null }; let https = { createServer: () => { @@ -68,7 +68,7 @@ let https = { }, get: () => { throw new Error("Crypto support is not present"); - }, + } }; try { crypto = require("crypto"); @@ -87,7 +87,7 @@ try { ocspCache = new ocsp.Cache(); } catch (err) { ocsp = { - _errored: err, + _errored: err }; } @@ -136,12 +136,12 @@ for ( ) { console.log(`${name} usage:`); console.log( - "node svr.js [-h] [--help] [-?] [/h] [/?] [--secure] [--reset] [--clean] [--disable-mods] [--single-threaded] [-v] [--version]", + "node svr.js [-h] [--help] [-?] [/h] [/?] [--secure] [--reset] [--clean] [--disable-mods] [--single-threaded] [-v] [--version]" ); console.log("-h -? /h /? --help -- Displays help"); console.log("--clean -- Cleans up files created by " + name); console.log( - `--reset -- Resets ${name} to default settings (WARNING: DANGEROUS)`, + `--reset -- Resets ${name} to default settings (WARNING: DANGEROUS)` ); console.log("--secure -- Runs HTTPS server"); console.log("--disable-mods -- Disables mods (safe mode)"); @@ -181,12 +181,12 @@ for ( console.log(`Unrecognized argument: ${args[i]}`); console.log(`${name} usage:`); console.log( - "node svr.js [-h] [--help] [-?] [/h] [/?] [--secure] [--reset] [--clean] [--disable-mods] [--single-threaded] [-v] [--version]", + "node svr.js [-h] [--help] [-?] [/h] [/?] [--secure] [--reset] [--clean] [--disable-mods] [--single-threaded] [-v] [--version]" ); console.log("-h -? /h /? --help -- Displays help"); console.log("--clean -- Cleans up files created by " + name); console.log( - `--reset -- Resets ${name} to default settings (WARNING: DANGEROUS)`, + `--reset -- Resets ${name} to default settings (WARNING: DANGEROUS)` ); console.log("--secure -- Runs HTTPS server"); console.log("--disable-mods -- Disables mods (safe mode)"); @@ -209,7 +209,7 @@ const legacyModWrapper = require("./utils/legacyModWrapper.js"); const generateErrorStack = require("./utils/generateErrorStack.js"); const { calculateNetworkIPv4FromCidr, - calculateBroadcastIPv4FromCidr, + calculateBroadcastIPv4FromCidr } = require("./utils/ipSubnetUtils.js"); const sendStatistics = require("./utils/sendStatistics.js"); const deepClone = require("./utils/deepClone.js"); @@ -296,7 +296,7 @@ if (process.serverConfig.dontCompress === undefined) "/.*\\.(?:jpe?g|png|bmp|tiff|jfif|gif|webp)$/", "/.*\\.(?:[id]mg|iso|flp)$/", "/.*\\.(?:zip|rar|bz2|[gb7x]z|lzma|tar)$/", - "/.*\\.(?:mp[34]|mov|wm[av]|avi|webm|og[gv]|mk[va])$/", + "/.*\\.(?:mp[34]|mov|wm[av]|avi|webm|og[gv]|mk[va])$/" ]; if (process.serverConfig.enableIPSpoofing === undefined) process.serverConfig.enableIPSpoofing = false; @@ -346,7 +346,7 @@ if (typeof process.serverConfig.port === "string") { process.serverConfig.port = parseInt(process.serverConfig.port); } else { const portLMatch = process.serverConfig.port.match( - /^(\[[^ \]@/\\]+\]|[^ \][:@/\\]+):([0-9]+)$/, + /^(\[[^ \]@/\\]+\]|[^ \][:@/\\]+):([0-9]+)$/ ); if (portLMatch) { listenAddress = portLMatch[1] @@ -361,7 +361,7 @@ if (typeof process.serverConfig.sport === "string") { process.serverConfig.sport = parseInt(process.serverConfig.sport); } else { const sportLMatch = process.serverConfig.sport.match( - /^(\[[^ \]@/\\]+\]|[^ \][:@/\\]+):([0-9]+)$/, + /^(\[[^ \]@/\\]+\]|[^ \][:@/\\]+):([0-9]+)$/ ); if (sportLMatch) { sListenAddress = sportLMatch[1] @@ -376,7 +376,7 @@ const serverconsole = require("./utils/serverconsole.js"); function addListenersToWorker(worker) { process.messageEventListeners.forEach((messageEventListener) => - worker.on("message", messageEventListener(worker, serverconsole)), + worker.on("message", messageEventListener(worker, serverconsole)) ); } @@ -404,7 +404,7 @@ try { process.chdir( process.serverConfig.wwwroot != undefined ? process.serverConfig.wwwroot - : process.dirname, + : process.dirname ); } catch (err) { wwwrootError = err; @@ -531,9 +531,9 @@ if (host != "[offline]" || ifaceEx) { port: crypto.__disabled__ !== undefined ? 80 : 443, path: "/", headers: { - "User-Agent": generateServerString(true), + "User-Agent": generateServerString(true) }, - timeout: 5000, + timeout: 5000 }); if (crypto.__disabled__ === undefined) { @@ -542,9 +542,9 @@ if (host != "[offline]" || ifaceEx) { port: 443, path: "/", headers: { - "User-Agent": generateServerString(true), + "User-Agent": generateServerString(true) }, - timeout: 5000, + timeout: 5000 }); } } else { @@ -585,7 +585,7 @@ if (process.serverConfig.secure) { process.serverConfig.key[0] != "/" && !process.serverConfig.key.match(/^[A-Z0-9]:\\/) ? process.dirname + "/" + process.serverConfig.key - : process.serverConfig.key, + : process.serverConfig.key ) .toString(); cert = fs @@ -593,7 +593,7 @@ if (process.serverConfig.secure) { process.serverConfig.cert[0] != "/" && !process.serverConfig.cert.match(/^[A-Z0-9]:\\/) ? process.dirname + "/" + process.serverConfig.cert - : process.serverConfig.cert, + : process.serverConfig.cert ) .toString(); const sniNames = Object.keys(process.serverConfig.sni); @@ -611,7 +611,7 @@ if (process.serverConfig.secure) { process.serverConfig.sni[sniName].cert[0] != "/" && !process.serverConfig.sni[sniName].cert.match(/^[A-Z0-9]:\\/) ? process.dirname + "/" + process.serverConfig.sni[sniName].cert - : process.serverConfig.sni[sniName].cert, + : process.serverConfig.sni[sniName].cert ) .toString(), key: fs @@ -619,9 +619,9 @@ if (process.serverConfig.secure) { process.serverConfig.sni[sniName].key[0] != "/" && !process.serverConfig.sni[sniName].key.match(/^[A-Z0-9]:\\/) ? process.dirname + "/" + process.serverConfig.sni[sniName].key - : process.serverConfig.sni[sniName].key, + : process.serverConfig.sni[sniName].key ) - .toString(), + .toString() }); }); } catch (err) { @@ -662,13 +662,13 @@ if (!disableMods) { else { modInfos.push({ name: `Unknown mod (${modFileRaw}; module.exports.modInfo not set)`, - version: "ERROR", + version: "ERROR" }); } } catch (err) { modLoadingErrors.push({ error: err, - modName: modFileRaw, + modName: modFileRaw }); } } else { @@ -692,7 +692,7 @@ if (!disableMods) { fs.mkdirSync(process.dirname + "/temp"); try { fs.mkdirSync( - process.dirname + "/temp/" + modloaderFolderName, + process.dirname + "/temp/" + modloaderFolderName ); } catch (err) { // If there was another error, throw it @@ -707,7 +707,7 @@ if (!disableMods) { "/temp/" + modloaderFolderName + "/" + - modFileRaw, + modFileRaw ); } catch (err) { // If there was an error creating the folder, ignore it if it's a known error @@ -727,7 +727,7 @@ if (!disableMods) { "/temp/" + modloaderFolderName + "/" + - modFileRaw, + modFileRaw }); } else { // If it's not a ".tar.gz" file, throw an error about `svrmodpack` support being dropped @@ -736,7 +736,7 @@ if (!disableMods) { name + ' no longer supports "svrmodpack" library for ' + name + - " mods. Please consider using newer mods with .tar.gz format.", + " mods. Please consider using newer mods with .tar.gz format." ); } @@ -749,9 +749,9 @@ if (!disableMods) { modloaderFolderName + "/" + modFileRaw + - "/index.js", - ), - ), + "/index.js" + ) + ) ); // Read the mod's info file @@ -764,21 +764,21 @@ if (!disableMods) { modloaderFolderName + "/" + modFileRaw + - "/mod.info", - ), - ), + "/mod.info" + ) + ) ); } catch (err) { // If failed to read info file, add a placeholder entry to modInfos with an error message modInfos.push({ name: `Unknown mod (${modFileRaw}; ${err.message})`, - version: "ERROR", + version: "ERROR" }); } } catch (err) { modLoadingErrors.push({ error: err, - modName: modFileRaw, + modName: modFileRaw }); } } @@ -823,14 +823,14 @@ if (!disableMods) { // Write the modified server side script to the temp folder fs.writeFileSync( process.dirname + "/temp/" + tempServerSideScriptName, - modhead + fs.readFileSync(SSJSPath) + modfoot, + modhead + fs.readFileSync(SSJSPath) + modfoot ); // Add the server side script to the mods list mods.push( legacyModWrapper( - require(process.dirname + "/temp/" + tempServerSideScriptName), - ), + require(process.dirname + "/temp/" + tempServerSideScriptName) + ) ); } catch (err) { SSJSError = err; @@ -852,28 +852,28 @@ let middleware = [ ...mods, // Load SVR.JS mods as middleware require("./middleware/defaultHandlerChecks.js"), require("./middleware/status.js"), - require("./middleware/staticFileServingAndDirectoryListings.js"), + require("./middleware/staticFileServingAndDirectoryListings.js") ]; // HTTP server handlers const requestHandler = require("./handlers/requestHandler.js")( serverconsole, - middleware, + middleware ); const proxyHandler = require("./handlers/proxyHandler.js")( serverconsole, - middleware, + middleware ); const noproxyHandler = require("./handlers/noproxyHandler.js")(serverconsole); const clientErrorHandler = require("./handlers/clientErrorHandler.js")( - serverconsole, + serverconsole ); const serverErrorHandler = require("./handlers/serverErrorHandler.js")( - serverconsole, + serverconsole ); let messageTransmitted = false; @@ -916,7 +916,7 @@ function listeningMessage() { process.serverConfig.sport == 443 ? "" : ":" + process.serverConfig.sport - }`, + }` ); } else { serverconsole.locmessage("* " + process.serverConfig.sport); // Unix socket or Windows named pipe @@ -933,7 +933,7 @@ function listeningMessage() { serverconsole.locmessage( `* http://localhost${ process.serverConfig.port == 80 ? "" : ":" + process.serverConfig.port - }`, + }` ); } else { serverconsole.locmessage("* " + process.serverConfig.port); // Unix socket or Windows named pipe @@ -950,7 +950,7 @@ function listeningMessage() { process.serverConfig.sport == 443 ? "" : ":" + process.serverConfig.sport - }`, + }` ); if ( !( @@ -964,7 +964,7 @@ function listeningMessage() { serverconsole.locmessage( `* http://${accHost.indexOf(":") > -1 ? "[" + accHost + "]" : accHost}${ process.serverConfig.port == 80 ? "" : ":" + process.serverConfig.port - }`, + }` ); ipStatusCallback(() => { if (pubip != "") { @@ -974,7 +974,7 @@ function listeningMessage() { process.serverConfig.spubport == 443 ? "" : ":" + process.serverConfig.spubport - }`, + }` ); if ( !( @@ -988,7 +988,7 @@ function listeningMessage() { process.serverConfig.pubport == 80 ? "" : ":" + process.serverConfig.pubport - }`, + }` ); } if (domain != "") { @@ -998,7 +998,7 @@ function listeningMessage() { process.serverConfig.spubport == 443 ? "" : ":" + process.serverConfig.spubport - }`, + }` ); if ( !( @@ -1012,7 +1012,7 @@ function listeningMessage() { process.serverConfig.pubport == 80 ? "" : ":" + process.serverConfig.pubport - }`, + }` ); } serverconsole.locmessage('For CLI help, you can type "help"'); @@ -1021,13 +1021,13 @@ function listeningMessage() { if (!process.serverConfig.optOutOfStatisticsServer) { if (crypto.__disabled__ !== undefined) { serverconsole.locwarnmessage( - "Sending data to statistics server is disabled, because the server only supports HTTPS, and your Node.JS version doesn't have crypto support.", + "Sending data to statistics server is disabled, because the server only supports HTTPS, and your Node.JS version doesn't have crypto support." ); } else { sendStatistics(modInfos, (err) => { if (err) serverconsole.locwarnmessage( - `There was a problem, when sending data to statistics server! Reason: ${err.message}`, + `There was a problem, when sending data to statistics server! Reason: ${err.message}` ); }); } @@ -1044,7 +1044,7 @@ let server2 = {}; // Create secondary HTTP server try { server2 = http.createServer({ - requireHostHeader: false, + requireHostHeader: false }); // eslint-disable-next-line no-unused-vars } catch (err) { @@ -1057,7 +1057,7 @@ server2.on("checkExpectation", requestHandler); server2.on("clientError", clientErrorHandler); server2.on( "connect", - process.serverConfig.disableToHTTPSRedirect ? proxyHandler : noproxyHandler, + process.serverConfig.disableToHTTPSRedirect ? proxyHandler : noproxyHandler ); server2.on("error", (err) => { serverErrorHandler(err, true, server2, start); @@ -1083,13 +1083,13 @@ if (process.serverConfig.enableHTTP2 == true) { minVersion: process.serverConfig.tlsMinVersion, maxVersion: process.serverConfig.tlsMaxVersion, sigalgs: process.serverConfig.signatureAlgorithms, - settings: process.serverConfig.http2Settings, + settings: process.serverConfig.http2Settings }); } else { server = http2.createServer({ allowHTTP1: true, requireHostHeader: false, - settings: process.serverConfig.http2Settings, + settings: process.serverConfig.http2Settings }); } } else { @@ -1105,12 +1105,12 @@ if (process.serverConfig.enableHTTP2 == true) { ecdhCurve: process.serverConfig.ecdhCurve, minVersion: process.serverConfig.tlsMinVersion, maxVersion: process.serverConfig.tlsMaxVersion, - sigalgs: process.serverConfig.signatureAlgorithms, + sigalgs: process.serverConfig.signatureAlgorithms }); } else { try { server = http.createServer({ - requireHostHeader: false, + requireHostHeader: false }); // eslint-disable-next-line no-unused-vars } catch (err) { @@ -1125,11 +1125,11 @@ if (process.serverConfig.secure) { sniCredentials.forEach((sniCredentialsSingle) => { server.addContext(sniCredentialsSingle.name, { cert: sniCredentialsSingle.cert, - key: sniCredentialsSingle.key, + key: sniCredentialsSingle.key }); try { let snMatches = sniCredentialsSingle.name.match( - /^([^:[]*|\[[^]]*\]?)((?::.*)?)$/, + /^([^:[]*|\[[^]]*\]?)((?::.*)?)$/ ); if (!snMatches[1][0].match(/^\.+$/)) snMatches[1][0] = snMatches[1][0].replace(/\.+$/, ""); @@ -1140,7 +1140,7 @@ if (process.serverConfig.secure) { .replace(/\*/g, "[^.:]*") + (snMatches[1][0] == "[" || snMatches[1].match( - /^(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/, + /^(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/ ) ? "" : ".?") + @@ -1148,7 +1148,7 @@ if (process.serverConfig.secure) { .replace(/([.^$+?\-\\[\]{}])/g, "\\$1") .replace(/\*/g, "[^.]*") + "$", - "i", + "i" ); // eslint-disable-next-line no-unused-vars } catch (err) { @@ -1238,7 +1238,7 @@ if (process.serverConfig.secure) { const req = ocsp.request.generate(cert, issuer); const options = { url: uri, - ocsp: req.data, + ocsp: req.data }; ocspCache.request(req.id, options, callback); @@ -1276,13 +1276,13 @@ let commands = { process.serverConfig.secure ? process.serverConfig.sport : process.serverConfig.port, - process.serverConfig.secure ? sListenAddress : listenAddress, + process.serverConfig.secure ? sListenAddress : listenAddress ); } else { server.listen( process.serverConfig.secure ? process.serverConfig.sport - : process.serverConfig.port, + : process.serverConfig.port ); } if ( @@ -1378,7 +1378,7 @@ let commands = { if (cluster.isPrimary === undefined) log(`This command is not supported on single-threaded ${name}.`); else log(`This command need to be run in ${name} master.`); - }, + } }; // Load commands from middleware @@ -1407,7 +1407,7 @@ function SVRJSFork() { // Log if (SVRJSInitialized) serverconsole.locmessage( - "Starting next thread, because previous one hung up/crashed...", + "Starting next thread, because previous one hung up/crashed..." ); // Fork new worker let newWorker = {}; @@ -1421,7 +1421,7 @@ function SVRJSFork() { ) { threadLimitWarned = true; serverconsole.locwarnmessage( - `${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.`, + `${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.` ); } if ( @@ -1437,7 +1437,7 @@ function SVRJSFork() { } else { if (SVRJSInitialized) serverconsole.locwarnmessage( - `${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.`, + `${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.` ); } } catch (err) { @@ -1453,7 +1453,7 @@ function SVRJSFork() { ) { threadLimitWarned = true; serverconsole.locwarnmessage( - `${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.`, + `${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.` ); } if ( @@ -1469,7 +1469,7 @@ function SVRJSFork() { } else { if (SVRJSInitialized) serverconsole.locwarnmessage( - `${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.`, + `${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.` ); } } else { @@ -1482,7 +1482,7 @@ function SVRJSFork() { newWorker.on("error", (err) => { if (!exiting) serverconsole.locwarnmessage( - `There was a problem when handling ${name} worker! (from master process side) Reason: ${err.message}`, + `There was a problem when handling ${name} worker! (from master process side) Reason: ${err.message}` ); }); newWorker.on("exit", () => { @@ -1522,7 +1522,7 @@ function forkWorkers(workersToFork, callback) { if (i >= workersToFork - 1) callback(); }; })(i), - i * 6.6, + i * 6.6 ); } } @@ -1545,7 +1545,7 @@ function msgListener(message) { if (message == "\x12END") { for (let i = 0; i < Object.keys(cluster.workers).length; i++) { cluster.workers[Object.keys(cluster.workers)[i]].removeAllListeners( - "message", + "message" ); addListenersToWorker(cluster.workers[Object.keys(cluster.workers)[i]]); } @@ -1564,7 +1564,7 @@ function msgListener(message) { serverconsole.locmessage("Configuration saved."); } else if (message.indexOf("\x12SAVEERR") == 0) { serverconsole.locwarnmessage( - `There was a problem while saving configuration file. Reason: ${message.substring(8)}`, + `There was a problem while saving configuration file. Reason: ${message.substring(8)}` ); } else if (message[0] == "\x12") { // Discard unrecognized control messages @@ -1580,7 +1580,7 @@ function saveConfig() { let configJSONobj = {}; if (fs.existsSync(process.dirname + "/config.json")) configJSONobj = JSON.parse( - fs.readFileSync(process.dirname + "/config.json").toString(), + fs.readFileSync(process.dirname + "/config.json").toString() ); if (configJSONobj.users === undefined) configJSONobj.users = []; if (process.serverConfig.secure) { @@ -1638,7 +1638,7 @@ function saveConfig() { "/.*\\.(?:jpe?g|png|bmp|tiff|jfif|gif|webp)$/", "/.*\\.(?:[id]mg|iso|flp)$/", "/.*\\.(?:zip|rar|bz2|[gb7x]z|lzma|tar)$/", - "/.*\\.(?:mp[34]|mov|wm[av]|avi|webm|og[gv]|mk[va])$/", + "/.*\\.(?:mp[34]|mov|wm[av]|avi|webm|og[gv]|mk[va])$/" ]; if (configJSONobj.enableIPSpoofing === undefined) configJSONobj.enableIPSpoofing = false; @@ -1669,7 +1669,7 @@ function saveConfig() { fs.writeFileSync( process.dirname + "/config.json", - JSON.stringify(configJSONobj, null, 2) + "\n", + JSON.stringify(configJSONobj, null, 2) + "\n" ); break; } catch (err) { @@ -1688,69 +1688,69 @@ function start(init) { for (let i = 0; i < logo.length; i++) console.log(logo[i]); // Print logo console.log(); console.log( - `Welcome to \x1b[1m${name} - a web server running on Node.JS\x1b[0m`, + `Welcome to \x1b[1m${name} - a web server running on Node.JS\x1b[0m` ); // Print warnings if (version.indexOf("Nightly-") === 0) serverconsole.locwarnmessage( - "This version is only for test purposes and may be unstable.", + "This version is only for test purposes and may be unstable." ); if (process.serverConfig.enableHTTP2 && !process.serverConfig.secure) serverconsole.locwarnmessage( - "HTTP/2 without HTTPS may not work in web browsers. Web browsers only support HTTP/2 with HTTPS!", + "HTTP/2 without HTTPS may not work in web browsers. Web browsers only support HTTP/2 with HTTPS!" ); if (process.isBun) { serverconsole.locwarnmessage( - `Bun support is experimental. Some features of ${name}, ${name} mods and ${name} server-side JavaScript may not work as expected.`, + `Bun support is experimental. Some features of ${name}, ${name} mods and ${name} server-side JavaScript may not work as expected.` ); if ( process.isBun && !( process.versions.bun && !process.versions.bun.match( - /^(?:0\.|1\.0\.|1\.1\.[0-9](?![0-9])|1\.1\.1[0-2](?![0-9]))/, + /^(?:0\.|1\.0\.|1\.1\.[0-9](?![0-9])|1\.1\.1[0-2](?![0-9]))/ ) ) && process.serverConfig.users.some((entry) => entry.pbkdf2) ) serverconsole.locwarnmessage( - "PBKDF2 password hashing function in Bun versions older than v1.1.13 blocks the event loop, which may result in denial of service.", + "PBKDF2 password hashing function in Bun versions older than v1.1.13 blocks the event loop, which may result in denial of service." ); } if (cluster.isPrimary === undefined) serverconsole.locwarnmessage( - `You're running ${name} on single thread. Reliability may suffer, as the server is stopped after crash.`, + `You're running ${name} on single thread. Reliability may suffer, as the server is stopped after crash.` ); if (crypto.__disabled__ !== undefined) serverconsole.locwarnmessage( - "Your Node.JS version doesn't have crypto support! The 'crypto' module is essential for providing cryptographic functionality in Node.JS. Without crypto support, certain security features may be unavailable, and some functionality may not work as expected. It's recommended to use a Node.JS version that includes crypto support to ensure the security and proper functioning of your server.", + "Your Node.JS version doesn't have crypto support! The 'crypto' module is essential for providing cryptographic functionality in Node.JS. Without crypto support, certain security features may be unavailable, and some functionality may not work as expected. It's recommended to use a Node.JS version that includes crypto support to ensure the security and proper functioning of your server." ); if (crypto.__disabled__ === undefined && !crypto.scrypt) serverconsole.locwarnmessage( - "Your JavaScript runtime doesn't have native scrypt support. HTTP authentication involving scrypt hashes will not work.", + "Your JavaScript runtime doesn't have native scrypt support. HTTP authentication involving scrypt hashes will not work." ); if ( !process.isBun && /^v(?:[0-9]\.|1[0-7]\.|18\.(?:[0-9]|1[0-8])\.|18\.19\.0|20\.(?:[0-9]|10)\.|20\.11\.0|21\.[0-5]\.|21\.6\.0|21\.6\.1(?![0-9]))/.test( - process.version, + process.version ) ) serverconsole.locwarnmessage( - "Your Node.JS version is vulnerable to HTTP server DoS (CVE-2024-22019).", + "Your Node.JS version is vulnerable to HTTP server DoS (CVE-2024-22019)." ); if ( !process.isBun && /^v(?:[0-9]\.|1[0-7]\.|18\.(?:1?[0-9])\.|18\.20\.0|20\.(?:[0-9]|1[01])\.|20\.12\.0|21\.[0-6]\.|21\.7\.0|21\.7\.1(?![0-9]))/.test( - process.version, + process.version ) ) serverconsole.locwarnmessage( - "Your Node.JS version is vulnerable to HTTP server request smuggling (CVE-2024-27982).", + "Your Node.JS version is vulnerable to HTTP server request smuggling (CVE-2024-27982)." ); if (process.getuid && process.getuid() == 0) serverconsole.locwarnmessage( - `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.`, + `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.` ); if ( !process.isBun && @@ -1761,11 +1761,11 @@ function start(init) { ) { if (new Date() > new Date("11 September 2023")) { serverconsole.locwarnmessage( - "OpenSSL 1.x is no longer receiving security updates after 11th September 2023. Your HTTPS communication might be vulnerable. It is recommended to update to a newer version of Node.JS that includes OpenSSL 3.0 or higher to ensure the security of your server and data.", + "OpenSSL 1.x is no longer receiving security updates after 11th September 2023. Your HTTPS communication might be vulnerable. It is recommended to update to a newer version of Node.JS that includes OpenSSL 3.0 or higher to ensure the security of your server and data." ); } else { serverconsole.locwarnmessage( - "OpenSSL 1.x will no longer receive security updates after 11th September 2023. Your HTTPS communication might be vulnerable in future. It is recommended to update to a newer version of Node.JS that includes OpenSSL 3.0 or higher to ensure the security of your server and data.", + "OpenSSL 1.x will no longer receive security updates after 11th September 2023. Your HTTPS communication might be vulnerable in future. It is recommended to update to a newer version of Node.JS that includes OpenSSL 3.0 or higher to ensure the security of your server and data." ); } } @@ -1775,15 +1775,15 @@ function start(init) { ocsp._errored ) serverconsole.locwarnmessage( - "Can't load OCSP module. OCSP stapling will be disabled. OCSP stapling is a security feature that improves the performance and security of HTTPS connections by caching the certificate status response. If you require this feature, consider updating your Node.JS version or checking for any issues with the 'ocsp' module.", + "Can't load OCSP module. OCSP stapling will be disabled. OCSP stapling is a security feature that improves the performance and security of HTTPS connections by caching the certificate status response. If you require this feature, consider updating your Node.JS version or checking for any issues with the 'ocsp' module." ); if (disableMods) 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) 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(); @@ -1791,16 +1791,16 @@ function start(init) { if (process.isPrimary || process.isPrimary === undefined) { modLoadingErrors.forEach((modLoadingError) => { serverconsole.locwarnmessage( - `There was a problem while loading a "${String(modLoadingError.modName).replace(/[\r\n]/g, "")}" mod.`, + `There was a problem while loading a "${String(modLoadingError.modName).replace(/[\r\n]/g, "")}" mod.` ); serverconsole.locwarnmessage("Stack:"); serverconsole.locwarnmessage( - generateErrorStack(modLoadingError.error), + generateErrorStack(modLoadingError.error) ); }); if (SSJSError) { serverconsole.locwarnmessage( - "There was a problem while loading server-side JavaScript.", + "There was a problem while loading server-side JavaScript." ); serverconsole.locwarnmessage("Stack:"); serverconsole.locwarnmessage(generateErrorStack(SSJSError)); @@ -1816,21 +1816,21 @@ function start(init) { const CPUs = os.cpus(); if (CPUs.length > 0) serverconsole.locmessage( - `CPU: ${CPUs.length > 1 ? CPUs.length + "x " : ""}${CPUs[0].model}`, + `CPU: ${CPUs.length > 1 ? CPUs.length + "x " : ""}${CPUs[0].model}` ); // Throw errors if (vnum < 64) 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) throw new Error( - `Can't read ${name} configuration file: ${configJSONRErr.message}`, + `Can't read ${name} configuration file: ${configJSONRErr.message}` ); if (configJSONPErr) throw new Error( - `${name} configuration parse error: ${configJSONPErr.message}`, + `${name} configuration parse error: ${configJSONPErr.message}` ); if ( process.serverConfig.enableHTTP2 && @@ -1838,20 +1838,20 @@ function start(init) { typeof process.serverConfig.port != "number" ) throw new Error( - `HTTP/2 without HTTPS, along with Unix sockets/Windows named pipes aren't supported by ${name}.`, + `HTTP/2 without HTTPS, along with Unix sockets/Windows named pipes aren't supported by ${name}.` ); if (process.serverConfig.enableHTTP2 && http2.__disabled__ !== undefined) throw new Error( - `HTTP/2 isn't supported by your Node.JS version! You may not be able to use HTTP/2 with ${name}`, + `HTTP/2 isn't supported by your Node.JS version! You may not be able to use HTTP/2 with ${name}` ); if (listenAddress) { if (listenAddress.match(/^[0-9]+$/)) throw new Error( - "Listening network address can't be numeric (it need to be either valid IP address, or valid domain name).", + "Listening network address can't be numeric (it need to be either valid IP address, or valid domain name)." ); if ( listenAddress.match( - /^(?: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.`); @@ -1862,15 +1862,15 @@ function start(init) { } if (certificateError) throw new Error( - `There was a problem with SSL certificate/private key: ${certificateError.message}`, + `There was a problem with SSL certificate/private key: ${certificateError.message}` ); if (wwwrootError) 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) throw new Error( - "Refusing to start, because the current SNI configuration would make the server vulnerable to ReDoS.", + "Refusing to start, because the current SNI configuration would make the server vulnerable to ReDoS." ); } @@ -1890,7 +1890,7 @@ function start(init) { : listenAddress) + ":" : "port " : "" - }${process.serverConfig.port.toString()}...`, + }${process.serverConfig.port.toString()}...` ); if (process.serverConfig.secure) serverconsole.locmessage( @@ -1902,7 +1902,7 @@ function start(init) { : sListenAddress) + ":" : "port " : "" - }${process.serverConfig.sport.toString()}...`, + }${process.serverConfig.sport.toString()}...` ); } @@ -1918,13 +1918,13 @@ function start(init) { process.serverConfig.secure ? process.serverConfig.sport : process.serverConfig.port, - process.serverConfig.secure ? sListenAddress : listenAddress, + process.serverConfig.secure ? sListenAddress : listenAddress ); } else { server.listen( process.serverConfig.secure ? process.serverConfig.sport - : process.serverConfig.port, + : process.serverConfig.port ); } } catch (err) { @@ -2008,7 +2008,7 @@ function start(init) { addListenersToWorker(cluster.workers[goodWorkers[wN]]); } serverconsole.locwarnmessage( - `There was a problem while saving configuration file. Reason: ${err.message}`, + `There was a problem while saving configuration file. Reason: ${err.message}` ); } }); @@ -2071,7 +2071,7 @@ function start(init) { const rla = readline.createInterface({ input: process.stdin, output: process.stdout, - prompt: "", + prompt: "" }); rla.prompt(); rla.on("line", (line) => { @@ -2100,7 +2100,7 @@ function start(init) { } if (stopError) serverconsole.climessage( - `Some ${name} workers might not be stopped.`, + `Some ${name} workers might not be stopped.` ); SVRJSInitialized = false; closedMaster = true; @@ -2185,10 +2185,10 @@ function start(init) { : process.serverConfig.sport, headers: { "X-SVR-JS-From-Main-Thread": "true", - "User-Agent": generateServerString(true), + "User-Agent": generateServerString(true) }, timeout: 1620, - rejectUnauthorized: false, + rejectUnauthorized: false }, (res) => { chksocket.removeAllListeners("timeout"); @@ -2196,7 +2196,7 @@ function start(init) { res.on("data", () => {}); res.on("end", () => {}); crashed = false; - }, + } ) .on("error", () => { if (!exiting) { @@ -2224,10 +2224,7 @@ function start(init) { address = "[" + address + "]"; } const connection = http2.connect( - "http://" + - address + - ":" + - process.serverConfig.port.toString(), + "http://" + address + ":" + process.serverConfig.port.toString() ); connection.on("error", () => { if (!exiting) { @@ -2242,7 +2239,7 @@ function start(init) { chksocket = connection.request({ ":path": "/", "x-svr-js-from-main-thread": "true", - "user-agent": generateServerString(true), + "user-agent": generateServerString(true) }); chksocket.on("response", () => { connection.close(); @@ -2273,9 +2270,9 @@ function start(init) { : process.serverConfig.port, headers: { "X-SVR-JS-From-Main-Thread": "true", - "User-Agent": generateServerString(true), + "User-Agent": generateServerString(true) }, - timeout: 1620, + timeout: 1620 }, (res) => { chksocket.removeAllListeners("timeout"); @@ -2283,7 +2280,7 @@ function start(init) { res.on("data", () => {}); res.on("end", () => {}); crashed = false; - }, + } ) .on("error", () => { if (!exiting) { @@ -2327,7 +2324,7 @@ function start(init) { isWorkerHungUpBuff = true; cluster.workers[allWorkers[_id]].on( "message", - msgListener, + msgListener ); cluster.workers[allWorkers[_id]].send("\x14KILLPING"); setTimeout(() => { @@ -2345,7 +2342,7 @@ function start(init) { } catch (err) { if (cluster.workers[allWorkers[_id]]) { cluster.workers[allWorkers[_id]].removeAllListeners( - "message", + "message" ); addListenersToWorker(cluster.workers[allWorkers[_id]]); } @@ -2361,19 +2358,19 @@ function start(init) { isWorkerHungUpBuff = true; cluster.workers[goodWorkers[wN]].on( "message", - msgListener, + msgListener ); cluster.workers[goodWorkers[wN]].send("\x14KILLREQ"); } } catch (err) { if (cluster.workers[goodWorkers[wN]]) { cluster.workers[goodWorkers[wN]].removeAllListeners( - "message", + "message" ); addListenersToWorker(cluster.workers[goodWorkers[wN]]); } serverconsole.locwarnmessage( - `There was a problem while terminating unused worker process. Reason: ${err.message}`, + `There was a problem while terminating unused worker process. Reason: ${err.message}` ); } } @@ -2394,7 +2391,7 @@ if (cluster.isPrimary || cluster.isPrimary === undefined) { serverconsole.locerrmessage(`${name} main process just crashed!!!`); serverconsole.locerrmessage("Stack:"); serverconsole.locerrmessage( - err.stack ? generateErrorStack(err) : String(err), + err.stack ? generateErrorStack(err) : String(err) ); process.exit(err.errno !== undefined ? err.errno : 1); } @@ -2409,7 +2406,7 @@ if (cluster.isPrimary || cluster.isPrimary === undefined) { } } catch (err) { serverconsole.locwarnmessage( - `There was a problem while saving configuration file. Reason: ${err.message}`, + `There was a problem while saving configuration file. Reason: ${err.message}` ); } try { @@ -2432,7 +2429,7 @@ if (cluster.isPrimary || cluster.isPrimary === undefined) { try { fs.writeFileSync( process.dirname + "/temp/serverSideScript.js", - "// Placeholder server-side JavaScript to workaround Bun bug.\r\n", + "// Placeholder server-side JavaScript to workaround Bun bug.\r\n" ); // eslint-disable-next-line no-unused-vars } catch (err) { @@ -2472,7 +2469,7 @@ if (cluster.isPrimary || cluster.isPrimary === undefined) { serverconsole.locerrmessage(`${name} worker just crashed!!!`); serverconsole.locerrmessage("Stack:"); serverconsole.locerrmessage( - err.stack ? generateErrorStack(err) : String(err), + err.stack ? generateErrorStack(err) : String(err) ); process.exit(err.errno !== undefined ? err.errno : 1); } diff --git a/src/middleware/blocklist.js b/src/middleware/blocklist.js index fa7d294..a204d53 100644 --- a/src/middleware/blocklist.js +++ b/src/middleware/blocklist.js @@ -7,7 +7,7 @@ module.exports = (req, res, logFacilities, config, next) => { blocklist.check( req.socket.realRemoteAddress ? req.socket.realRemoteAddress - : req.socket.remoteAddress, + : req.socket.remoteAddress ) ) { // Invoke 403 Forbidden error @@ -50,7 +50,7 @@ module.exports.commands = { if (!cluster.isPrimary === false) log("IPs successfully unblocked."); passCommand(ip, log); } - }, + } }; module.exports.proxySafe = true; diff --git a/src/middleware/checkForbiddenPaths.js b/src/middleware/checkForbiddenPaths.js index 8a9c72f..ca4bdae 100644 --- a/src/middleware/checkForbiddenPaths.js +++ b/src/middleware/checkForbiddenPaths.js @@ -4,7 +4,7 @@ const { getInitializePath, isForbiddenPath, isIndexOfForbiddenPath, - forbiddenPaths, + forbiddenPaths } = require("../utils/forbiddenPaths.js"); const svrjsInfo = require("../../svrjs.json"); const { name } = svrjsInfo; @@ -13,15 +13,15 @@ forbiddenPaths.config = getInitializePath("./config.json"); forbiddenPaths.certificates = []; if (process.serverConfig.secure) { forbiddenPaths.certificates.push( - getInitializePath(process.serverConfig.cert), + getInitializePath(process.serverConfig.cert) ); forbiddenPaths.certificates.push(getInitializePath(process.serverConfig.key)); Object.keys(process.serverConfig.sni).forEach((sniHostname) => { forbiddenPaths.certificates.push( - getInitializePath(process.serverConfig.sni[sniHostname].cert), + getInitializePath(process.serverConfig.sni[sniHostname].cert) ); forbiddenPaths.certificates.push( - getInitializePath(process.serverConfig.sni[sniHostname].key), + getInitializePath(process.serverConfig.sni[sniHostname].key) ); }); } @@ -29,19 +29,19 @@ forbiddenPaths.svrjs = getInitializePath( "./" + (process.dirname[process.dirname.length - 1] != "/" ? process.filename.replace(process.dirname + "/", "") - : process.filename.replace(process.dirname, "")), + : process.filename.replace(process.dirname, "")) ); forbiddenPaths.serverSideScripts = []; if (process.serverConfig.useWebRootServerSideScript) { forbiddenPaths.serverSideScripts.push("/serverSideScript.js"); } else { forbiddenPaths.serverSideScripts.push( - getInitializePath("./serverSideScript.js"), + getInitializePath("./serverSideScript.js") ); } forbiddenPaths.serverSideScriptDirectories = []; forbiddenPaths.serverSideScriptDirectories.push( - getInitializePath("./node_modules"), + getInitializePath("./node_modules") ); forbiddenPaths.serverSideScriptDirectories.push(getInitializePath("./mods")); forbiddenPaths.temp = getInitializePath("./temp"); @@ -51,7 +51,7 @@ module.exports = (req, res, logFacilities, config, next) => { let decodedHrefWithoutDuplicateSlashes = ""; try { decodedHrefWithoutDuplicateSlashes = decodeURIComponent( - req.parsedURL.pathname, + req.parsedURL.pathname ).replace(/\/+/g, "/"); // eslint-disable-next-line no-unused-vars } catch (err) { @@ -66,7 +66,7 @@ module.exports = (req, res, logFacilities, config, next) => { ) { res.error(403); logFacilities.errmessage( - "Access to configuration file/certificates is denied.", + "Access to configuration file/certificates is denied." ); return; } else if ( @@ -97,11 +97,11 @@ module.exports = (req, res, logFacilities, config, next) => { (isForbiddenPath(decodedHrefWithoutDuplicateSlashes, "svrjs") || isForbiddenPath( decodedHrefWithoutDuplicateSlashes, - "serverSideScripts", + "serverSideScripts" ) || isIndexOfForbiddenPath( decodedHrefWithoutDuplicateSlashes, - "serverSideScriptDirectories", + "serverSideScriptDirectories" )) && !req.isProxy && (config.disableServerSideScriptExpose || diff --git a/src/middleware/defaultHandlerChecks.js b/src/middleware/defaultHandlerChecks.js index 60645d8..5b5ec56 100644 --- a/src/middleware/defaultHandlerChecks.js +++ b/src/middleware/defaultHandlerChecks.js @@ -14,7 +14,7 @@ module.exports = (req, res, logFacilities, config, next) => { .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(/ { .generateServerString() .replace(/&/g, "&") .replace(//g, ">")}

`, + .replace(/>/g, ">")}

` ); res.end(); logFacilities.errmessage( - `${name} doesn't support proxy without proxy mod.`, + `${name} doesn't support proxy without proxy mod.` ); return; } diff --git a/src/middleware/nonStandardCodesAndHttpAuthentication.js b/src/middleware/nonStandardCodesAndHttpAuthentication.js index 7c419e7..bf452ef 100644 --- a/src/middleware/nonStandardCodesAndHttpAuthentication.js +++ b/src/middleware/nonStandardCodesAndHttpAuthentication.js @@ -9,7 +9,7 @@ const svrjsInfo = require("../../svrjs.json"); const { name } = svrjsInfo; let crypto = { - __disabled__: null, + __disabled__: null }; try { crypto = require("crypto"); @@ -43,10 +43,10 @@ process.serverConfig.nonStandardCodes.forEach((nonStandardCodeRaw) => { if (!cluster.isPrimary) { passwordHashCacheIntervalId = setInterval(() => { pbkdf2Cache = pbkdf2Cache.filter( - (entry) => entry.addDate > new Date() - 3600000, + (entry) => entry.addDate > new Date() - 3600000 ); scryptCache = scryptCache.filter( - (entry) => entry.addDate > new Date() - 3600000, + (entry) => entry.addDate > new Date() - 3600000 ); }, 1800000); } @@ -67,13 +67,13 @@ module.exports = (req, res, logFacilities, config, next) => { matchHostname(nonStandardCodes[i].host, req.headers.host) && ipMatch( nonStandardCodes[i].ip, - req.socket ? req.socket.localAddress : undefined, + req.socket ? req.socket.localAddress : undefined ) ) { let isMatch = false; hrefWithoutDuplicateSlashes = req.parsedURL.pathname.replace( /\/+/g, - "/", + "/" ); if (nonStandardCodes[i].regex) { // Regex match @@ -130,7 +130,7 @@ module.exports = (req, res, logFacilities, config, next) => { // Fallback replacement location = hrefWithoutDuplicateSlashes.replace( regexI[nonscodeIndex], - nonscode.location, + nonscode.location ); } } else if ( @@ -146,7 +146,7 @@ module.exports = (req, res, logFacilities, config, next) => { res.redirect( location, nonscode.scode == 302 || nonscode.scode == 307, - nonscode.scode == 307 || nonscode.scode == 308, + nonscode.scode == 307 || nonscode.scode == 308 ); return; } else { @@ -187,14 +187,14 @@ module.exports = (req, res, logFacilities, config, next) => { res.error( 500, new Error( - `${name} doesn't support scrypt-hashed passwords on Node.JS versions without scrypt hash support.`, - ), + `${name} doesn't support scrypt-hashed passwords on Node.JS versions without scrypt hash support.` + ) ); return; } else { cacheEntry = scryptCache.find( (entry) => - entry.password == hashedPassword && entry.salt == list[_i].salt, + entry.password == hashedPassword && entry.salt == list[_i].salt ); if (cacheEntry) { cb(cacheEntry.hash); @@ -208,7 +208,7 @@ module.exports = (req, res, logFacilities, config, next) => { hash: key, password: hashedPassword, salt: list[_i].salt, - addDate: new Date(), + addDate: new Date() }); cb(key); } @@ -220,14 +220,14 @@ module.exports = (req, res, logFacilities, config, next) => { res.error( 500, new Error( - `${name} doesn't support PBKDF2-hashed passwords on Node.JS versions without crypto support.`, - ), + `${name} doesn't support PBKDF2-hashed passwords on Node.JS versions without crypto support.` + ) ); return; } else { cacheEntry = pbkdf2Cache.find( (entry) => - entry.password == hashedPassword && entry.salt == list[_i].salt, + entry.password == hashedPassword && entry.salt == list[_i].salt ); if (cacheEntry) { cb(cacheEntry.hash); @@ -247,11 +247,11 @@ module.exports = (req, res, logFacilities, config, next) => { hash: key, password: hashedPassword, salt: list[_i].salt, - addDate: new Date(), + addDate: new Date() }); cb(key); } - }, + } ); } } @@ -282,7 +282,7 @@ module.exports = (req, res, logFacilities, config, next) => { } const decodedCredentials = Buffer.from( credentialsMatch[1], - "base64", + "base64" ).toString("utf8"); const decodedCredentialsMatch = decodedCredentials.match(/^([^:]*):(.*)$/); @@ -314,7 +314,7 @@ module.exports = (req, res, logFacilities, config, next) => { let fakeCredentials = { name: username, pass: "SVRJSAWebServerRunningOnNodeJS", - salt: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0", + salt: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0" }; if (!process.isBun) { if (scryptCount > sha256Count && scryptCount > pbkdf2Count) { @@ -334,7 +334,7 @@ module.exports = (req, res, logFacilities, config, next) => { } else { if (!bruteForceDb[reqip]) bruteForceDb[reqip] = { - invalidAttempts: 0, + invalidAttempts: 0 }; bruteForceDb[reqip].invalidAttempts++; if (bruteForceDb[reqip].invalidAttempts >= 10) { @@ -344,7 +344,7 @@ module.exports = (req, res, logFacilities, config, next) => { } res.error(401, ha); logFacilities.errmessage( - `User "${String(username).replace(/[\r\n]/g, "")}" failed to log in.`, + `User "${String(username).replace(/[\r\n]/g, "")}" failed to log in.` ); } else { if (bruteProtection) { @@ -353,12 +353,12 @@ module.exports = (req, res, logFacilities, config, next) => { } else { if (bruteForceDb[reqip]) bruteForceDb[reqip] = { - invalidAttempts: 0, + invalidAttempts: 0 }; } } logFacilities.reqmessage( - `Client is logged in as "${String(username).replace(/[\r\n]/g, "")}".`, + `Client is logged in as "${String(username).replace(/[\r\n]/g, "")}".` ); req.authUser = username; next(); @@ -385,7 +385,7 @@ module.exports = (req, res, logFacilities, config, next) => { ) { if (bruteForceDb[reqip] && bruteForceDb[reqip].invalidAttempts >= 10) bruteForceDb[reqip] = { - invalidAttempts: 5, + invalidAttempts: 5 }; authorizedCallback(true); } else { @@ -428,7 +428,7 @@ process.messageEventListeners.push((worker, serverconsole) => { ) { if (bruteForceDb[ip] && bruteForceDb[ip].invalidAttempts >= 10) bruteForceDb[ip] = { - invalidAttempts: 5, + invalidAttempts: 5 }; worker.send("\x14AUTHA" + ip); } else { @@ -438,13 +438,13 @@ process.messageEventListeners.push((worker, serverconsole) => { ip = message.substring(6); if (bruteForceDb[ip]) bruteForceDb[ip] = { - invalidAttempts: 0, + invalidAttempts: 0 }; } else if (message.substring(0, 6) == "\x12AUTHW") { ip = message.substring(6); if (!bruteForceDb[ip]) bruteForceDb[ip] = { - invalidAttempts: 0, + invalidAttempts: 0 }; bruteForceDb[ip].invalidAttempts++; if (bruteForceDb[ip].invalidAttempts >= 10) { @@ -458,7 +458,7 @@ module.exports.commands = { stop: (args, log, passCommand) => { clearInterval(passwordHashCacheIntervalId); passCommand(args, log); - }, + } }; module.exports.proxySafe = true; diff --git a/src/middleware/redirectTrailingSlashes.js b/src/middleware/redirectTrailingSlashes.js index 843cfc9..62f54d7 100644 --- a/src/middleware/redirectTrailingSlashes.js +++ b/src/middleware/redirectTrailingSlashes.js @@ -21,7 +21,7 @@ module.exports = (req, res, logFacilities, config, next) => { req.originalParsedURL.pathname + "/" + (req.parsedURL.search ? req.parsedURL.search : "") + - (req.parsedURL.hash ? req.parsedURL.hash : ""), + (req.parsedURL.hash ? req.parsedURL.hash : "") ); } }); diff --git a/src/middleware/redirects.js b/src/middleware/redirects.js index 5e02caf..47e016b 100644 --- a/src/middleware/redirects.js +++ b/src/middleware/redirects.js @@ -27,7 +27,7 @@ module.exports = (req, res, logFacilities, config, next) => { ? req.socket.realRemoteAddress : req.socket.remoteAddress ).match( - /^(?:localhost$|::1$|f[c-d][0-9a-f]{2}:|(?:::ffff:)?(?:(?:127|10)\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|192\.168\.[0-9]{1,3}\.[0-9]{1,3}|172\.(?:1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3})$)/i, + /^(?:localhost$|::1$|f[c-d][0-9a-f]{2}:|(?:::ffff:)?(?:(?:127|10)\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|192\.168\.[0-9]{1,3}\.[0-9]{1,3}|172\.(?:1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3})$)/i ); let destinationPort = 0; @@ -50,7 +50,7 @@ module.exports = (req, res, logFacilities, config, next) => { "https://" + hostname + (destinationPort == 443 ? "" : ":" + destinationPort) + - req.url, + req.url ); return; } @@ -67,7 +67,7 @@ module.exports = (req, res, logFacilities, config, next) => { hostname = hostname.join(":"); if (hostname == config.domain && hostname.indexOf("www.") != 0) { res.redirect( - `${req.socket.encrypted ? "https" : "http"}://www.${hostname}${hostport ? ":" + hostport : ""}${req.url.replace(/\/+/g, "/")}`, + `${req.socket.encrypted ? "https" : "http"}://www.${hostname}${hostport ? ":" + hostport : ""}${req.url.replace(/\/+/g, "/")}` ); return; } diff --git a/src/middleware/rewriteURL.js b/src/middleware/rewriteURL.js index 1d649e8..1867458 100644 --- a/src/middleware/rewriteURL.js +++ b/src/middleware/rewriteURL.js @@ -41,7 +41,7 @@ module.exports = (req, res, logFacilities, config, next) => { _fileState = 3; } rewriteURL(address, map, callback, _fileState, i); - }, + } ); doCallback = false; break; @@ -56,7 +56,7 @@ module.exports = (req, res, logFacilities, config, next) => { matchHostname(mapEntry.host, req.headers.host) && ipMatch( mapEntry.ip, - req.socket ? req.socket.localAddress : undefined, + req.socket ? req.socket.localAddress : undefined ) && address.match(createRegex(mapEntry.definingRegex)) && !(mapEntry.isNotDirectory && _fileState == 2) && @@ -66,7 +66,7 @@ module.exports = (req, res, logFacilities, config, next) => { mapEntry.replacements.forEach((replacement) => { rewrittenURL = rewrittenURL.replace( createRegex(replacement.regex), - replacement.replacement, + replacement.replacement ); }); if (mapEntry.append) rewrittenURL += mapEntry.append; @@ -100,7 +100,7 @@ module.exports = (req, res, logFacilities, config, next) => { : config.domain ? config.domain : "unknown.invalid" - }`, + }` ); } catch (err) { res.error(400, err); @@ -109,7 +109,7 @@ module.exports = (req, res, logFacilities, config, next) => { const sHref = sanitizeURL( req.parsedURL.pathname, - config.allowDoubleSlashes, + config.allowDoubleSlashes ); const preparedReqUrl2 = req.parsedURL.pathname + @@ -132,7 +132,7 @@ module.exports = (req, res, logFacilities, config, next) => { (req.parsedURL.search ? req.parsedURL.search : "") + (req.parsedURL.hash ? req.parsedURL.hash : ""); logFacilities.resmessage( - `URL sanitized: ${req.url} => ${rewrittenAgainURL}`, + `URL sanitized: ${req.url} => ${rewrittenAgainURL}` ); req.url = rewrittenAgainURL; try { @@ -144,7 +144,7 @@ module.exports = (req, res, logFacilities, config, next) => { : 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 84de2b2..5dfe826 100644 --- a/src/middleware/staticFileServingAndDirectoryListings.js +++ b/src/middleware/staticFileServingAndDirectoryListings.js @@ -18,7 +18,7 @@ let ETagDB = {}; const generateETag = (filePath, stat) => { if (!ETagDB[filePath + "-" + stat.size + "-" + stat.mtime]) ETagDB[filePath + "-" + stat.size + "-" + stat.mtime] = sha256( - filePath + "-" + stat.size + "-" + stat.mtime, + filePath + "-" + stat.size + "-" + stat.mtime ); return ETagDB[filePath + "-" + stat.size + "-" + stat.mtime]; }; @@ -141,7 +141,7 @@ module.exports = (req, res, logFacilities, config, next) => { const clientETag = req.headers["if-none-match"]; if (clientETag === fileETag) { res.writeHead(304, http.STATUS_CODES[304], { - ETag: clientETag, + ETag: clientETag }); res.end(); return; @@ -151,7 +151,7 @@ module.exports = (req, res, logFacilities, config, next) => { const ifMatchETag = req.headers["if-match"]; if (ifMatchETag && ifMatchETag !== "*" && ifMatchETag !== fileETag) { res.error(412, { - ETag: clientETag, + ETag: clientETag }); return; } @@ -164,7 +164,7 @@ module.exports = (req, res, logFacilities, config, next) => { rhd["Accept-Ranges"] = "bytes"; rhd["Content-Range"] = `bytes */${filelen}`; const regexmatch = req.headers["range"].match( - /bytes=([0-9]*)-([0-9]*)/, + /bytes=([0-9]*)-([0-9]*)/ ); if (!regexmatch) { res.error(416, rhd); @@ -217,8 +217,8 @@ module.exports = (req, res, logFacilities, config, next) => { res.end( res.foot.substring( begin - res.head.length - filelen, - end - res.head.length - filelen + 1, - ), + end - res.head.length - filelen + 1 + ) ); return; } @@ -230,7 +230,7 @@ module.exports = (req, res, logFacilities, config, next) => { end: ext == "html" ? Math.min(filelen, end - res.head.length) - : end, + : end }); readStream .on("error", (err) => { @@ -266,8 +266,8 @@ module.exports = (req, res, logFacilities, config, next) => { res.end( res.foot.substring( 0, - end - res.head.length - filelen + 1, - ), + end - res.head.length - filelen + 1 + ) ); }); } @@ -275,7 +275,7 @@ module.exports = (req, res, logFacilities, config, next) => { end: !( res.foot.length > 0 && end > res.head.length + filelen - ), + ) }); }; res.writeHead(206, http.STATUS_CODES[206], rhd); @@ -283,7 +283,7 @@ module.exports = (req, res, logFacilities, config, next) => { afterWriteCallback(); } else if ( !res.write( - res.head.substring(begin, res.head.length - begin), + res.head.substring(begin, res.head.length - begin) ) ) { res.on("drain", afterWriteCallback); @@ -295,7 +295,7 @@ module.exports = (req, res, logFacilities, config, next) => { readStream.pipe(res); } logFacilities.resmessage( - "Client successfully received content.", + "Client successfully received content." ); } catch (err) { res.error(500, err); @@ -352,10 +352,10 @@ module.exports = (req, res, logFacilities, config, next) => { ) { if ( /^Mozilla\/4\.[0-9]+(( *\[[^)]*\] *| *)\([^)\]]*\))? *$/.test( - req.headers["user-agent"], + req.headers["user-agent"] ) && !/https?:\/\/|[bB][oO][tT]|[sS][pP][iI][dD][eE][rR]|[sS][uU][rR][vV][eE][yY]|MSIE/.test( - req.headers["user-agent"], + req.headers["user-agent"] ) ) { isCompressable = false; // Netscape 4.x doesn't handle compressed data properly outside of HTML documents. @@ -365,10 +365,10 @@ module.exports = (req, res, logFacilities, config, next) => { } else { if ( /^Mozilla\/4\.0[6-8](( *\[[^)]*\] *| *)\([^)\]]*\))? *$/.test( - req.headers["user-agent"], + req.headers["user-agent"] ) && !/https?:\/\/|[bB][oO][tT]|[sS][pP][iI][dD][eE][rR]|[sS][uU][rR][vV][eE][yY]|MSIE/.test( - req.headers["user-agent"], + req.headers["user-agent"] ) ) { isCompressable = false; // Netscape 4.06-4.08 doesn't handle compressed data properly. @@ -458,7 +458,7 @@ module.exports = (req, res, logFacilities, config, next) => { }); } readStream.pipe(resStream, { - end: res.foot.length == 0, + end: res.foot.length == 0 }); }; res.writeHead(200, http.STATUS_CODES[200], hdhds); @@ -474,7 +474,7 @@ module.exports = (req, res, logFacilities, config, next) => { readStream.pipe(resStream); } logFacilities.resmessage( - "Client successfully received content.", + "Client successfully received content." ); } catch (err) { res.error(500, err); @@ -494,7 +494,7 @@ module.exports = (req, res, logFacilities, config, next) => { if ( checkForEnabledDirectoryListing( req.headers.host, - req.socket ? req.socket.localAddress : undefined, + req.socket ? req.socket.localAddress : undefined ) ) { let customDirListingHeader = ""; @@ -520,7 +520,7 @@ module.exports = (req, res, logFacilities, config, next) => { customDirListingHeader = data.toString(); callback(); } - }, + } ); } else { callback(); @@ -532,7 +532,7 @@ module.exports = (req, res, logFacilities, config, next) => { customDirListingHeader = data.toString(); callback(); } - }, + } ); }; @@ -556,7 +556,7 @@ module.exports = (req, res, logFacilities, config, next) => { customDirListingFooter = data.toString(); callback(); } - }, + } ); } else { callback(); @@ -568,7 +568,7 @@ module.exports = (req, res, logFacilities, config, next) => { customDirListingFooter = data.toString(); callback(); } - }, + } ); }; @@ -579,7 +579,7 @@ module.exports = (req, res, logFacilities, config, next) => { const headerHasHTMLTag = customDirListingHeader .replace(/)[\s\S])*|)(?:-->|$)/g, "") .match( - /])*(?:>|$)/i, + /])*(?:>|$)/i ); // Generate HTML head and footer based on configuration and custom content @@ -601,7 +601,7 @@ module.exports = (req, res, logFacilities, config, next) => { .replace(/&/g, "&") .replace(//g, ">") + - "", + "" ) : res.head.replace( //i, @@ -610,14 +610,14 @@ module.exports = (req, res, logFacilities, config, next) => { .replace(/&/g, "&") .replace(//g, ">") + - "", + "" )) + (!headerHasHTMLTag ? customDirListingHeader : "") }

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

${ checkPathLevel(decodeURIComponent(origHref)) < 1 ? "" @@ -648,7 +648,7 @@ module.exports = (req, res, logFacilities, config, next) => { fs.existsSync( "." + decodeURIComponent(href) + - "/.maindesc".replace(/\/+/g, "/"), + "/.maindesc".replace(/\/+/g, "/") ) ) { htmlFoot = @@ -656,7 +656,7 @@ module.exports = (req, res, logFacilities, config, next) => { fs.readFileSync( "." + decodeURIComponent(href) + - "/.maindesc".replace(/\/+/g, "/"), + "/.maindesc".replace(/\/+/g, "/") ) + htmlFoot; } @@ -672,7 +672,7 @@ module.exports = (req, res, logFacilities, config, next) => { callback, prefix, pushArray, - index, + index ) => { if (fileList.length == 0) { callback(pushArray); @@ -686,13 +686,13 @@ module.exports = (req, res, logFacilities, config, next) => { fs.lstat( (prefix + "/" + fileList[index]).replace( /\/+/g, - "/", + "/" ), (err, stats) => { pushArray.push({ name: fileList[index], stats: err ? null : stats, - errored: true, + errored: true }); if (index < fileList.length - 1) { getStatsForAllFilesI( @@ -700,18 +700,18 @@ module.exports = (req, res, logFacilities, config, next) => { callback, prefix, pushArray, - index + 1, + index + 1 ); } else { callback(pushArray); } - }, + } ); } else { pushArray.push({ name: fileList[index], stats: stats, - errored: false, + errored: false }); if (index < fileList.length - 1) { getStatsForAllFilesI( @@ -719,13 +719,13 @@ module.exports = (req, res, logFacilities, config, next) => { callback, prefix, pushArray, - index + 1, + index + 1 ); } else { callback(pushArray); } } - }, + } ); }; @@ -756,8 +756,8 @@ module.exports = (req, res, logFacilities, config, next) => { .replace(//g, - ">", - )}\r\n`, + ">" + )}\r\n` ); } else { let entry = `\r\n`; // Determine the special file types (block device, character device, etc.) @@ -819,7 +819,7 @@ module.exports = (req, res, logFacilities, config, next) => { .replace("[img]", "/.dirimages/html.png") .replace( "[alt]", - eext == "xml" ? "[XML]" : "[HTM]", + eext == "xml" ? "[XML]" : "[HTM]" ); } else if (eext == "js") { entry = entry @@ -838,7 +838,7 @@ module.exports = (req, res, logFacilities, config, next) => { .replace("[img]", "/.dirimages/image.png") .replace( "[alt]", - eext == "ico" ? "[ICO]" : "[IMG]", + eext == "ico" ? "[ICO]" : "[IMG]" ); } else if (emime && emime.split("/")[0] == "font") { entry = entry @@ -856,7 +856,7 @@ module.exports = (req, res, logFacilities, config, next) => { .replace("[img]", "/.dirimages/text.png") .replace( "[alt]", - eext == "json" ? "[JSO]" : "[TXT]", + eext == "json" ? "[JSO]" : "[TXT]" ); } else if (emime && emime.split("/")[0] == "video") { entry = entry @@ -885,19 +885,19 @@ module.exports = (req, res, logFacilities, config, next) => { // Push the information about empty directory if (directoryListingRows.length == 0) { directoryListingRows.push( - "", + "" ); } // Send the directory listing response res.writeHead(200, http.STATUS_CODES[200], { - "Content-Type": "text/html; charset=utf-8", + "Content-Type": "text/html; charset=utf-8" }); res.end( - htmlHead + directoryListingRows.join("") + htmlFoot, + htmlHead + directoryListingRows.join("") + htmlFoot ); logFacilities.resmessage( - "Client successfully received content.", + "Client successfully received content." ); }); } catch (err) { @@ -932,7 +932,7 @@ module.exports = (req, res, logFacilities, config, next) => { } else { res.error(501); logFacilities.errmessage( - `${name} doesn't support block devices, character devices, FIFOs nor sockets.`, + `${name} doesn't support block devices, character devices, FIFOs nor sockets.` ); return; } @@ -955,7 +955,7 @@ module.exports = (req, res, logFacilities, config, next) => { readFrom = (readFrom + "/index.xhtml").replace(/\/+/g, "/"); properDirectoryListingAndStaticFileServe(); } - }, + } ); } else { stats = s; diff --git a/src/middleware/status.js b/src/middleware/status.js index af97187..06af4ec 100644 --- a/src/middleware/status.js +++ b/src/middleware/status.js @@ -40,7 +40,7 @@ module.exports = (req, res, logFacilities, config, next) => { statusBody += `Average error rate: ${ Math.round( ((process.err4xxcounter + process.err5xxcounter) / process.reqcounter) * - 10000, + 10000 ) / 100 }%
`; statusBody += `Malformed HTTP requests: ${process.malformedcounter}`; @@ -52,13 +52,13 @@ module.exports = (req, res, logFacilities, config, next) => { ((process.cpuUsage().user + process.cpuUsage().system) / 1000000 / process.uptime()) * - 1000, + 1000 ) / 1000 }%`; statusBody += `
Thread PID: ${process.pid}
`; res.writeHead(200, http.STATUS_CODES[200], { - "Content-Type": "text/html; charset=utf-8", + "Content-Type": "text/html; charset=utf-8" }); res.end( `${ @@ -94,7 +94,7 @@ module.exports = (req, res, logFacilities, config, next) => { .replace(/&/g, "&") .replace(//g, ">")) + - "", + "" ) }

${name .replace(/&/g, "&") @@ -107,7 +107,7 @@ module.exports = (req, res, logFacilities, config, next) => { .replace(/&/g, "&") .replace(//g, ">") - }

${statusBody}${res.foot == "" ? "" : res.foot}`, + }${statusBody}${res.foot == "" ? "" : res.foot}` ); return; } diff --git a/src/middleware/urlSanitizer.js b/src/middleware/urlSanitizer.js index 9321a0e..7fd9ca6 100644 --- a/src/middleware/urlSanitizer.js +++ b/src/middleware/urlSanitizer.js @@ -5,7 +5,7 @@ module.exports = (req, res, logFacilities, config, next) => { // Sanitize URL let sanitizedHref = sanitizeURL( req.parsedURL.pathname, - config.allowDoubleSlashes, + config.allowDoubleSlashes ); let preparedReqUrl = req.parsedURL.pathname + @@ -30,7 +30,7 @@ module.exports = (req, res, logFacilities, config, next) => { : config.domain ? config.domain : "unknown.invalid" - }`, + }` ); } catch (err) { res.error(400, err); diff --git a/src/middleware/webRootPostfixes.js b/src/middleware/webRootPostfixes.js index 819fd21..caaa5a4 100644 --- a/src/middleware/webRootPostfixes.js +++ b/src/middleware/webRootPostfixes.js @@ -59,7 +59,7 @@ module.exports = (req, res, logFacilities, config, next) => { matchHostname(postfixEntry.host) && ipMatch( postfixEntry.ip, - req.socket ? req.socket.localAddress : undefined, + req.socket ? req.socket.localAddress : undefined ) && !( postfixEntry.skipRegex && @@ -75,7 +75,7 @@ module.exports = (req, res, logFacilities, config, next) => { }); if (urlWithPostfix != preparedReqUrl3) { logFacilities.resmessage( - "Added web root postfix: " + req.url + " => " + urlWithPostfix, + "Added web root postfix: " + req.url + " => " + urlWithPostfix ); req.url = urlWithPostfix; try { @@ -87,7 +87,7 @@ module.exports = (req, res, logFacilities, config, next) => { : config.domain ? config.domain : "unknown.invalid" - }`, + }` ); } catch (err) { res.error(400, err); @@ -96,7 +96,7 @@ module.exports = (req, res, logFacilities, config, next) => { const sHref = sanitizeURL( req.parsedURL.pathname, - config.allowDoubleSlashes, + config.allowDoubleSlashes ); const preparedReqUrl2 = req.parsedURL.pathname + @@ -119,7 +119,7 @@ module.exports = (req, res, logFacilities, config, next) => { (req.parsedURL.search ? req.parsedURL.search : "") + (req.parsedURL.hash ? req.parsedURL.hash : ""); logFacilities.resmessage( - `URL sanitized: ${req.url} => ${rewrittenAgainURL}`, + `URL sanitized: ${req.url} => ${rewrittenAgainURL}` ); req.url = rewrittenAgainURL; try { @@ -131,7 +131,7 @@ module.exports = (req, res, logFacilities, config, next) => { : config.domain ? config.domain : "unknown.invalid" - }`, + }` ); } catch (err) { res.error(400, err); diff --git a/src/res/httpErrorDescriptions.js b/src/res/httpErrorDescriptions.js index f8aa70e..bb15f4b 100644 --- a/src/res/httpErrorDescriptions.js +++ b/src/res/httpErrorDescriptions.js @@ -46,7 +46,7 @@ const serverHTTPErrorDescs = { 510: "The server requires an extended HTTP request. The request you made isn't an extended HTTP request.", 511: "You need to authenticate yourself in order to get network access.", 598: "The server couldn't get a response in time while it was acting as a proxy.", - 599: "The server couldn't connect in time while it was acting as a proxy.", + 599: "The server couldn't connect in time while it was acting as a proxy." }; module.exports = serverHTTPErrorDescs; diff --git a/src/res/logo.js b/src/res/logo.js index 6692020..c78b84e 100644 --- a/src/res/logo.js +++ b/src/res/logo.js @@ -39,7 +39,7 @@ const logo = [ "\x1b[0m ,///////,", "", "", - "\x1b[0m", + "\x1b[0m" ]; module.exports = logo; diff --git a/src/res/serverErrorDescriptions.js b/src/res/serverErrorDescriptions.js index 18af9d2..5e980da 100644 --- a/src/res/serverErrorDescriptions.js +++ b/src/res/serverErrorDescriptions.js @@ -30,7 +30,7 @@ const serverErrorDescs = { "Protocol not supported. The requested network protocol is not supported.", ETIMEDOUT: "Connection timed out. The server did not respond within the specified timeout period.", - UNKNOWN: "There was an unknown error with the server.", + UNKNOWN: "There was an unknown error with the server." }; module.exports = serverErrorDescs; diff --git a/src/utils/clusterBunShim.js b/src/utils/clusterBunShim.js index 5c7ced8..e7c375b 100644 --- a/src/utils/clusterBunShim.js +++ b/src/utils/clusterBunShim.js @@ -29,7 +29,7 @@ if (!process.singleThreaded) { isDead: () => false, send: (message, ...params) => { process.send(message, ...params); - }, + } }; if (!process.send) { @@ -52,9 +52,9 @@ if (!process.singleThreaded) { ? path.join( "\\\\?\\pipe", process.dirname, - "temp/.W" + process.pid + ".ipc", + "temp/.W" + process.pid + ".ipc" ) - : process.dirname + "/temp/.W" + process.pid + ".ipc", + : process.dirname + "/temp/.W" + process.pid + ".ipc" ); process.send = (message) => { @@ -64,12 +64,12 @@ if (!process.singleThreaded) { ? path.join( "\\\\?\\pipe", process.dirname, - "temp/.P" + process.pid + ".ipc", + "temp/.P" + process.pid + ".ipc" ) : process.dirname + "/temp/.P" + process.pid + ".ipc", () => { fakeIPCConnection.end(message); - }, + } ); }; @@ -92,7 +92,7 @@ if (!process.singleThreaded) { let command = newArguments.shift(); let newWorker = child_process.spawn(command, newArguments, { env: newEnvironment, - stdio: ["inherit", "inherit", "inherit", "ipc"], + stdio: ["inherit", "inherit", "inherit", "ipc"] }); newWorker.process = newWorker; @@ -158,9 +158,9 @@ if (!process.singleThreaded) { ? path.join( "\\\\?\\pipe", process.dirname, - "temp/.P" + newWorker.process.pid + ".ipc", + "temp/.P" + newWorker.process.pid + ".ipc" ) - : process.dirname + "/temp/.P" + newWorker.process.pid + ".ipc", + : process.dirname + "/temp/.P" + newWorker.process.pid + ".ipc" ); // Cleanup when worker process exits @@ -174,7 +174,7 @@ if (!process.singleThreaded) { fakeParam2, fakeParam3, fakeParam4, - tries, + tries ) { if (!tries) tries = 0; @@ -185,12 +185,12 @@ if (!process.singleThreaded) { ? path.join( "\\\\?\\pipe", process.dirname, - "temp/.W" + newWorker.process.pid + ".ipc", + "temp/.W" + newWorker.process.pid + ".ipc" ) : process.dirname + "/temp/.W" + newWorker.process.pid + ".ipc", () => { fakeWorkerIPCConnection.end(message); - }, + } ); } catch (err) { if (tries > 50) throw err; @@ -199,7 +199,7 @@ if (!process.singleThreaded) { fakeParam2, fakeParam3, fakeParam4, - tries + 1, + tries + 1 ); } }; diff --git a/src/utils/createRegex.js b/src/utils/createRegex.js index c18cfd9..236cd7b 100644 --- a/src/utils/createRegex.js +++ b/src/utils/createRegex.js @@ -4,7 +4,7 @@ function createRegex(regex, isPath) { // The new regular expression supports single unescaped "/" within [], but not two unescaped "/". // We needed to do it, because it's very hard to create the regex that matches two unescaped "/" within "[]" without ReDoS. const regexStrMatch = regex.match( - /^\/((?:\\.|\/+(?:(?:\\.|[^\]\\/])*\])|[^/\\])*)\/([a-zA-Z0-9]*)$/, + /^\/((?:\\.|\/+(?:(?:\\.|[^\]\\/])*\])|[^/\\])*)\/([a-zA-Z0-9]*)$/ ); if (!regexStrMatch) throw new Error("Invalid regular expression: " + regex); const searchString = regexStrMatch[1]; diff --git a/src/utils/forbiddenPaths.js b/src/utils/forbiddenPaths.js index e836e25..e4f517a 100644 --- a/src/utils/forbiddenPaths.js +++ b/src/utils/forbiddenPaths.js @@ -65,11 +65,10 @@ function isIndexOfForbiddenPath(decodedHref, match) { ? forbiddenPath.some( (path) => decodedHrefLower === path.toLowerCase() || - decodedHrefLower.indexOf(path.toLowerCase() + "/") == 0, + decodedHrefLower.indexOf(path.toLowerCase() + "/") == 0 ) : forbiddenPath.some( - (path) => - decodedHref === path || decodedHref.indexOf(path + "/") == 0, + (path) => decodedHref === path || decodedHref.indexOf(path + "/") == 0 ); } @@ -83,5 +82,5 @@ module.exports = { getInitializePath: getInitializePath, isForbiddenPath: isForbiddenPath, isIndexOfForbiddenPath: isIndexOfForbiddenPath, - forbiddenPaths: forbiddenPaths, + forbiddenPaths: forbiddenPaths }; diff --git a/src/utils/generateErrorStack.js b/src/utils/generateErrorStack.js index fe58772..d6ab1ef 100644 --- a/src/utils/generateErrorStack.js +++ b/src/utils/generateErrorStack.js @@ -6,7 +6,7 @@ function generateErrorStack(errorObject) { // If the error stack starts with the error name, return the original stack (it is V8-style then). if ( errorStack.some( - (errorStackLine) => errorStackLine.indexOf(errorObject.name) == 0, + (errorStackLine) => errorStackLine.indexOf(errorObject.name) == 0 ) ) { return errorObject.stack; @@ -16,7 +16,7 @@ function generateErrorStack(errorObject) { let newErrorStack = [ errorObject.name + (errorObject.code ? ": " + errorObject.code : "") + - (errorObject.message == "" ? "" : ": " + errorObject.message), + (errorObject.message == "" ? "" : ": " + errorObject.message) ]; // Process each line of the original error stack. @@ -37,8 +37,7 @@ function generateErrorStack(errorObject) { ? !location || location == "" ? "" : location - : func + - (!location || location == "" ? "" : " (" + location + ")")), + : func + (!location || location == "" ? "" : " (" + location + ")")) ); } }); diff --git a/src/utils/ipBlockList.js b/src/utils/ipBlockList.js index d5f7d00..2d51617 100644 --- a/src/utils/ipBlockList.js +++ b/src/utils/ipBlockList.js @@ -6,7 +6,7 @@ function ipBlockList(rawBlockList) { raw: [], rawtoPreparedMap: [], prepared: [], - cidrs: [], + cidrs: [] }; // Function to normalize IPv4 address (remove leading zeros) @@ -79,7 +79,7 @@ function ipBlockList(rawBlockList) { const ipMax = ipMin + exp - 1; return { min: ipMin, - max: ipMax, + max: ipMax }; }; @@ -106,7 +106,7 @@ function ipBlockList(rawBlockList) { ? i < 7 - fieldsToDelete ? ipBlocks[i] : (ipBlocks[i] >> fieldMaskModify) << fieldMaskModify - : 0, + : 0 ); } for (let i = 0; i < 8; i++) { @@ -117,12 +117,12 @@ function ipBlockList(rawBlockList) { : ((ipBlocks[i] >> fieldMaskModify) << fieldMaskModify) + Math.pow(2, fieldMaskModify) - 1 - : 65535, + : 65535 ); } return { min: ipBlockMin, - max: ipBlockMax, + max: ipBlockMax }; }; @@ -183,13 +183,13 @@ function ipBlockList(rawBlockList) { instance.cidrs.push(cidrLimits); instance.rawtoPreparedMap.push({ cidr: true, - index: cidrIndex, + index: cidrIndex }); } else { instance.prepared.push(rawValue); instance.rawtoPreparedMap.push({ cidr: false, - index: beginIndex, + index: beginIndex }); } }; diff --git a/src/utils/ipSubnetUtils.js b/src/utils/ipSubnetUtils.js index 8a6cfcb..433119f 100644 --- a/src/utils/ipSubnetUtils.js +++ b/src/utils/ipSubnetUtils.js @@ -2,7 +2,7 @@ function calculateBroadcastIPv4FromCidr(ipWithCidr) { // Check if CIDR notation is valid, if it's not, return null if (!ipWithCidr) return null; const ipCA = ipWithCidr.match( - /^((?:(?:25[0-5]|(?:2[0-4]|1\d|[1-9]|)\d)\.?\b){4})\/([0-2][0-9]|3[0-2]|[0-9])$/, + /^((?:(?:25[0-5]|(?:2[0-4]|1\d|[1-9]|)\d)\.?\b){4})\/([0-2][0-9]|3[0-2]|[0-9])$/ ); if (!ipCA) return null; @@ -27,7 +27,7 @@ function calculateNetworkIPv4FromCidr(ipWithCidr) { // Check if CIDR notation is valid, if it's not, return null if (!ipWithCidr) return null; const ipCA = ipWithCidr.match( - /^((?:(?:25[0-5]|(?:2[0-4]|1\d|[1-9]|)\d)\.?\b){4})\/([0-2][0-9]|3[0-2]|[0-9])$/, + /^((?:(?:25[0-5]|(?:2[0-4]|1\d|[1-9]|)\d)\.?\b){4})\/([0-2][0-9]|3[0-2]|[0-9])$/ ); if (!ipCA) return null; @@ -50,5 +50,5 @@ function calculateNetworkIPv4FromCidr(ipWithCidr) { module.exports = { calculateBroadcastIPv4FromCidr: calculateBroadcastIPv4FromCidr, - calculateNetworkIPv4FromCidr: calculateNetworkIPv4FromCidr, + calculateNetworkIPv4FromCidr: calculateNetworkIPv4FromCidr }; diff --git a/src/utils/legacyModWrapper.js b/src/utils/legacyModWrapper.js index 2ce6504..5adef96 100644 --- a/src/utils/legacyModWrapper.js +++ b/src/utils/legacyModWrapper.js @@ -3,7 +3,7 @@ try { formidable = require("formidable"); } catch (err) { formidable = { - _errored: err, + _errored: err }; } @@ -78,7 +78,7 @@ module.exports = (legacyMod) => { req.originalParsedURL.pathname, // origHref res.redirect, // redirect parsePostData, // parsePostData - req.authUser, // authUser + req.authUser // authUser )(); }; @@ -90,7 +90,7 @@ module.exports = (legacyMod) => { head, // head config, // configJSON logFacilities, // serverconsole - next, // elseCallback + next // elseCallback )(); }; } diff --git a/src/utils/sendStatistics.js b/src/utils/sendStatistics.js index 09602cb..e502aa8 100644 --- a/src/utils/sendStatistics.js +++ b/src/utils/sendStatistics.js @@ -3,7 +3,7 @@ const svrjsInfo = require("../../svrjs.json"); const { version, statisticsServerCollectEndpoint } = svrjsInfo; let crypto = { - __disabled__: null, + __disabled__: null }; let https = { createServer: () => { @@ -14,7 +14,7 @@ let https = { }, get: () => { throw new Error("Crypto support is not present"); - }, + } }; try { // eslint-disable-next-line no-unused-vars @@ -30,7 +30,7 @@ function sendStatistics(modInfos, callback) { version: version, runtime: process.isBun ? "Bun" : "Node.js", runtimeVersion: process.isBun ? process.versions.bun : process.version, - mods: modInfos, + mods: modInfos }); const statisticsRequest = https.request( statisticsServerCollectEndpoint, @@ -39,8 +39,8 @@ function sendStatistics(modInfos, callback) { headers: { "User-Agent": generateServerString(true), "Content-Type": "application/json", - "Content-Length": Buffer.byteLength(statisticsToSend), - }, + "Content-Length": Buffer.byteLength(statisticsToSend) + } }, (res) => { const statusCode = res.statusCode; @@ -65,7 +65,7 @@ function sendStatistics(modInfos, callback) { callback(err); } }); - }, + } ); statisticsRequest.on("error", (err) => { callback(err); diff --git a/src/utils/serverconsole.js b/src/utils/serverconsole.js index 60c613e..e944ca4 100644 --- a/src/utils/serverconsole.js +++ b/src/utils/serverconsole.js @@ -23,7 +23,7 @@ function LOG(s) { "-" + timestamp + ".log", - "[" + new Date().toISOString() + "] " + s + "\r\n", + "[" + new Date().toISOString() + "] " + s + "\r\n" ); } else { if (!logFile) { @@ -40,19 +40,19 @@ function LOG(s) { ".log", { flags: "a", - autoClose: false, - }, + autoClose: false + } ); logFile.on("error", (err) => { if ( !s.match( - /^SERVER WARNING MESSAGE(?: \[Request Id: [0-9a-f]{6}\])?: There was a problem while saving logs! Logs will not be kept in log file\. Reason: /, + /^SERVER WARNING MESSAGE(?: \[Request Id: [0-9a-f]{6}\])?: There was a problem while saving logs! Logs will not be kept in log file\. Reason: / ) && !reallyExiting ) serverconsole.locwarnmessage( "There was a problem while saving logs! Logs will not be kept in log file. Reason: " + - err.message, + err.message ); }); } @@ -66,13 +66,13 @@ function LOG(s) { } catch (err) { if ( !s.match( - /^SERVER WARNING MESSAGE(?: \[Request Id: [0-9a-f]{6}\])?: There was a problem while saving logs! Logs will not be kept in log file\. Reason: /, + /^SERVER WARNING MESSAGE(?: \[Request Id: [0-9a-f]{6}\])?: There was a problem while saving logs! Logs will not be kept in log file\. Reason: / ) && !reallyExiting ) serverconsole.locwarnmessage( "There was a problem while saving logs! Logs will not be kept in log file. Reason: " + - err.message, + err.message ); } } @@ -90,13 +90,13 @@ const serverconsole = { "\x1b[1mSERVER CLI MESSAGE\x1b[22m" + (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + - msg, + msg ); LOG( "SERVER CLI MESSAGE" + (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + - msg, + msg ); return; }, @@ -112,13 +112,13 @@ const serverconsole = { (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + msg + - "\x1b[37m\x1b[0m", + "\x1b[37m\x1b[0m" ); LOG( "SERVER REQUEST MESSAGE" + (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + - msg, + msg ); return; }, @@ -134,13 +134,13 @@ const serverconsole = { (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + msg + - "\x1b[37m\x1b[0m", + "\x1b[37m\x1b[0m" ); LOG( "SERVER RESPONSE MESSAGE" + (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + - msg, + msg ); return; }, @@ -156,13 +156,13 @@ const serverconsole = { (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + msg + - "\x1b[37m\x1b[0m", + "\x1b[37m\x1b[0m" ); LOG( "SERVER RESPONSE ERROR MESSAGE" + (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + - msg, + msg ); return; }, @@ -178,13 +178,13 @@ const serverconsole = { (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + msg + - "\x1b[40m\x1b[0m", + "\x1b[40m\x1b[0m" ); LOG( "SERVER ERROR MESSAGE" + (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + - msg, + msg ); return; }, @@ -200,13 +200,13 @@ const serverconsole = { (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + msg + - "\x1b[40m\x1b[0m", + "\x1b[40m\x1b[0m" ); LOG( "SERVER WARNING MESSAGE" + (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + - msg, + msg ); return; }, @@ -221,19 +221,19 @@ const serverconsole = { "\x1b[1mSERVER MESSAGE\x1b[22m" + (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + - msg, + msg ); LOG( "SERVER MESSAGE" + (reqId ? " [Request Id: " + reqId + "]" : "") + ": " + - msg, + msg ); return; }, setProcessExiting: (state) => { reallyExiting = state; - }, + } }; // Wrap around process.exit, so that log contents can be flushed. diff --git a/src/utils/sha256.js b/src/utils/sha256.js index 4ea6abe..ec622ee 100644 --- a/src/utils/sha256.js +++ b/src/utils/sha256.js @@ -96,7 +96,7 @@ function sha256(s) { 0x90befffa, 0xa4506ceb, 0xbef9a3f7, - 0xc67178f2, + 0xc67178f2 ); let HASH = new Array( 0x6a09e667, @@ -106,7 +106,7 @@ function sha256(s) { 0x510e527f, 0x9b05688c, 0x1f83d9ab, - 0x5be0cd19, + 0x5be0cd19 ); let W = new Array(64); let a, b, c, d, e, f, g, h; @@ -131,14 +131,14 @@ function sha256(s) { W[j] = safeAdd( safeAdd( safeAdd(Gamma1256(W[j - 2]), W[j - 7]), - Gamma0256(W[j - 15]), + Gamma0256(W[j - 15]) ), - W[j - 16], + W[j - 16] ); T1 = safeAdd( safeAdd(safeAdd(safeAdd(h, Sigma1256(e)), Ch(e, f, g)), K[j]), - W[j], + W[j] ); T2 = safeAdd(Sigma0256(a), Maj(a, b, c)); diff --git a/src/utils/sizify.js b/src/utils/sizify.js index b8780f1..5f78ae8 100644 --- a/src/utils/sizify.js +++ b/src/utils/sizify.js @@ -5,12 +5,12 @@ function sizify(bytes, addI) { const prefixes = ["", "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"]; const prefixIndex = Math.min( Math.floor(Math.log2(bytes) / 10), - prefixes.length - 1, + prefixes.length - 1 ); const prefixIndexTranslated = Math.pow(2, 10 * prefixIndex); const decimalPoints = Math.max( 2 - Math.floor(Math.log10(bytes / prefixIndexTranslated)), - 0, + 0 ); const size = diff --git a/src/utils/urlParser.js b/src/utils/urlParser.js index cdc4400..150c179 100644 --- a/src/utils/urlParser.js +++ b/src/utils/urlParser.js @@ -13,7 +13,7 @@ function parseURL(uri, prepend) { // Parse the URL using regular expression let parsedURI = uri.match( - /^(?:([^:]+:)(\/\/)?)?(?:([^@/?#*]+)@)?([^:/?#*]+|\[[^*\]/]\])?(?::([0-9]+))?(\*|\/[^?#]*)?(\?[^#]*)?(#[\S\s]*)?/, + /^(?:([^:]+:)(\/\/)?)?(?:([^@/?#*]+)@)?([^:/?#*]+|\[[^*\]/]\])?(?::([0-9]+))?(\*|\/[^?#]*)?(\?[^#]*)?(#[\S\s]*)?/ ); // Match 1: protocol // Match 2: slashes after protocol diff --git a/tests/middleware/blocklist.test.js b/tests/middleware/blocklist.test.js index dba839e..072589f 100644 --- a/tests/middleware/blocklist.test.js +++ b/tests/middleware/blocklist.test.js @@ -13,12 +13,12 @@ middleware.mockImplementation(() => { check: ipBlockListCheck, add: ipBlockListAdd, remove: ipBlockListRemove, - raw: [], + raw: [] }; }); process.serverConfig = { - blacklist: [], + blacklist: [] }; const blocklistMiddleware = require("../../src/middleware/blocklist.js"); @@ -30,14 +30,14 @@ describe("Blocklist middleware", () => { req = { socket: { realRemoteAddress: "127.0.0.1", - remoteAddress: "127.0.0.1", - }, + remoteAddress: "127.0.0.1" + } }; res = { - error: jest.fn(), + error: jest.fn() }; logFacilities = { - errmessage: jest.fn(), + errmessage: jest.fn() }; config = {}; next = jest.fn(); @@ -63,7 +63,7 @@ describe("Blocklist middleware", () => { expect(next).not.toHaveBeenCalled(); expect(res.error).toHaveBeenCalledWith(403); expect(logFacilities.errmessage).toHaveBeenCalledWith( - "Client is in the block list.", + "Client is in the block list." ); }); diff --git a/tests/middleware/checkForbiddenPaths.test.js b/tests/middleware/checkForbiddenPaths.test.js index b8105c4..7856484 100644 --- a/tests/middleware/checkForbiddenPaths.test.js +++ b/tests/middleware/checkForbiddenPaths.test.js @@ -11,13 +11,13 @@ jest.mock("../../src/utils/forbiddenPaths.js", () => ({ serverSideScripts: ["/forbidden"], serverSideScriptDirectories: ["/forbidden"], temp: "/forbidden", - log: "/forbidden", - }, + log: "/forbidden" + } })); process.serverConfig = { secure: true, - sni: [], + sni: [] }; process.dirname = "/usr/lib/mocksvrjs"; @@ -31,19 +31,19 @@ describe("Forbidden path checking middleware", () => { beforeEach(() => { req = { parsedURL: { pathname: "/forbidden" }, - isProxy: false, + isProxy: false }; res = { - error: jest.fn(), + error: jest.fn() }; logFacilities = { - errmessage: jest.fn(), + errmessage: jest.fn() }; config = { enableLogging: true, enableRemoteLogBrowsing: false, exposeServerVersion: false, - disableServerSideScriptExpose: true, + disableServerSideScriptExpose: true }; next = jest.fn(); }); diff --git a/tests/middleware/defaultHandlerChecks.test.js b/tests/middleware/defaultHandlerChecks.test.js index b8d4756..3665a2c 100644 --- a/tests/middleware/defaultHandlerChecks.test.js +++ b/tests/middleware/defaultHandlerChecks.test.js @@ -8,11 +8,11 @@ describe("Default handler checks middleware", () => { req = httpMocks.createRequest(); res = httpMocks.createResponse(); logFacilities = { - errmessage: jest.fn(), + errmessage: jest.fn() }; config = { getCustomHeaders: jest.fn(() => ({})), - generateServerString: jest.fn(() => "Server String"), + generateServerString: jest.fn(() => "Server String") }; next = jest.fn(); }); @@ -22,7 +22,7 @@ describe("Default handler checks middleware", () => { middleware(req, res, logFacilities, config, next); expect(res._getStatusCode()).toBe(501); expect(logFacilities.errmessage).toHaveBeenCalledWith( - expect.stringContaining("doesn't support proxy without proxy mod."), + expect.stringContaining("doesn't support proxy without proxy mod.") ); }); @@ -32,7 +32,7 @@ describe("Default handler checks middleware", () => { expect(res._getStatusCode()).toBe(204); expect(res._getHeaders()).toHaveProperty( "allow", - "GET, POST, HEAD, OPTIONS", + "GET, POST, HEAD, OPTIONS" ); }); @@ -42,7 +42,7 @@ describe("Default handler checks middleware", () => { middleware(req, res, logFacilities, config, next); expect(res.error).toHaveBeenCalledWith(405); expect(logFacilities.errmessage).toHaveBeenCalledWith( - expect.stringContaining("Invaild method: PUT"), + expect.stringContaining("Invaild method: PUT") ); }); diff --git a/tests/middleware/nonStandardCodesAndHttpAuthentication.test.js b/tests/middleware/nonStandardCodesAndHttpAuthentication.test.js index 2c7df98..eb2ca2d 100644 --- a/tests/middleware/nonStandardCodesAndHttpAuthentication.test.js +++ b/tests/middleware/nonStandardCodesAndHttpAuthentication.test.js @@ -22,7 +22,7 @@ jest.mock("crypto", () => { pbkdf2: jest.fn((password, salt, iterations, keylen, digest, callback) => { // Mock implementation for crypto.pbkdf2 callback(null, Buffer.from(mockPbkdf2Hash)); - }), + }) // Add other properties or methods of crypto module if needed }; }); @@ -34,15 +34,15 @@ process.serverConfig = { ip: "192.168.1.1", url: "/test/path", scode: 403, - users: ["127.0.0.1"], + users: ["127.0.0.1"] }, { host: "example.com", ip: "192.168.1.1", url: "/test/path2", - scode: 401, - }, - ], + scode: 401 + } + ] }; process.messageEventListeners = []; @@ -58,32 +58,32 @@ describe("Non-standard codes and HTTP authentication middleware", () => { req = { socket: { realRemoteAddress: "127.0.0.1", - localAddress: "192.168.1.1", + localAddress: "192.168.1.1" }, parsedURL: { - pathname: "/test/path", + pathname: "/test/path" }, url: "/test/path", headers: { - host: "example.com", + host: "example.com" }, - isProxy: false, + isProxy: false }; res = { error: jest.fn(), - redirect: jest.fn(), + redirect: jest.fn() }; logFacilities = { errmessage: jest.fn(), - reqmessage: jest.fn(), + reqmessage: jest.fn() }; config = { getCustomHeaders: jest.fn(), - users: [], + users: [] }; next = jest.fn(); process.serverConfig = { - nonStandardCodes: [], + nonStandardCodes: [] }; cluster.isPrimary = true; @@ -92,7 +92,7 @@ describe("Non-standard codes and HTTP authentication middleware", () => { test("should handle non-standard codes", () => { ipBlockList.mockReturnValue({ - check: jest.fn().mockReturnValue(true), + check: jest.fn().mockReturnValue(true) }); matchHostname.mockReturnValue(true); ipMatch.mockReturnValue(true); @@ -112,8 +112,8 @@ describe("Non-standard codes and HTTP authentication middleware", () => { { name: "test", pass: "test", - salt: "test", - }, + salt: "test" + } ]; sha256.mockReturnValue("test"); req.headers.authorization = "Basic dGVzdDp0ZXN0"; @@ -122,7 +122,7 @@ describe("Non-standard codes and HTTP authentication middleware", () => { expect(next).toHaveBeenCalled(); expect(logFacilities.reqmessage).toHaveBeenCalledWith( - 'Client is logged in as "test".', + 'Client is logged in as "test".' ); }); @@ -136,8 +136,8 @@ describe("Non-standard codes and HTTP authentication middleware", () => { { name: "test", pass: "test2", - salt: "test", - }, + salt: "test" + } ]; sha256.mockReturnValue("test"); req.headers.authorization = "Basic dGVzdDp0ZXN0"; @@ -150,7 +150,7 @@ describe("Non-standard codes and HTTP authentication middleware", () => { expect(next).not.toHaveBeenCalled(); expect(logFacilities.errmessage).toHaveBeenCalledWith( - "Brute force limit reached!", + "Brute force limit reached!" ); }); @@ -164,8 +164,8 @@ describe("Non-standard codes and HTTP authentication middleware", () => { name: "test", pass: "74657374", // "test" converted to hex salt: "test", - scrypt: true, - }, + scrypt: true + } ]; mockScryptHash = "test"; req.headers.authorization = "Basic dGVzdDp0ZXN0"; @@ -174,7 +174,7 @@ describe("Non-standard codes and HTTP authentication middleware", () => { expect(next).toHaveBeenCalled(); expect(logFacilities.reqmessage).toHaveBeenCalledWith( - 'Client is logged in as "test".', + 'Client is logged in as "test".' ); }); @@ -188,8 +188,8 @@ describe("Non-standard codes and HTTP authentication middleware", () => { name: "test", pass: "74657374", // "test" converted to hex salt: "test", - pbkdf2: true, - }, + pbkdf2: true + } ]; mockPbkdf2Hash = "test"; req.headers.authorization = "Basic dGVzdDp0ZXN0"; @@ -198,7 +198,7 @@ describe("Non-standard codes and HTTP authentication middleware", () => { expect(next).toHaveBeenCalled(); expect(logFacilities.reqmessage).toHaveBeenCalledWith( - 'Client is logged in as "test".', + 'Client is logged in as "test".' ); }); @@ -221,8 +221,8 @@ describe("Non-standard codes and HTTP authentication middleware", () => { { name: "test", pass: "test", - salt: "test", - }, + salt: "test" + } ]; sha256.mockReturnValue("test"); req.headers.authorization = "Basic dGVzdDp0ZXN0"; @@ -255,7 +255,7 @@ describe("Non-standard codes and HTTP authentication middleware", () => { const mockWorker = { send: (msg) => { mockHandlers.forEach((handler) => handler(msg)); - }, + } }; const mockServerConsole = { climessage: () => {}, @@ -264,10 +264,10 @@ describe("Non-standard codes and HTTP authentication middleware", () => { errmessage: () => {}, locerrmessage: () => {}, locwarnmessage: () => {}, - locmessage: () => {}, + locmessage: () => {} }; process.messageEventListeners.forEach((listenerWrapper) => - listenerWrapper(mockWorker, mockServerConsole)(message), + listenerWrapper(mockWorker, mockServerConsole)(message) ); }; @@ -275,7 +275,7 @@ describe("Non-standard codes and HTTP authentication middleware", () => { expect(next).toHaveBeenCalled(); expect(logFacilities.reqmessage).toHaveBeenCalledWith( - 'Client is logged in as "test".', + 'Client is logged in as "test".' ); }); }); diff --git a/tests/middleware/redirectTrailingSlashes.test.js b/tests/middleware/redirectTrailingSlashes.test.js index 22e7eb2..8fef834 100644 --- a/tests/middleware/redirectTrailingSlashes.test.js +++ b/tests/middleware/redirectTrailingSlashes.test.js @@ -10,11 +10,11 @@ describe("Trailing slash redirection middleware", () => { req = { isProxy: false, parsedURL: { pathname: "/test", search: "?query=1", hash: "#hash" }, - originalParsedURL: { pathname: "/test" }, + originalParsedURL: { pathname: "/test" } }; res = { redirect: jest.fn(), - error: jest.fn(), + error: jest.fn() }; logFacilities = {}; config = { disableTrailingSlashRedirects: false }; diff --git a/tests/middleware/redirects.test.js b/tests/middleware/redirects.test.js index 9cb5700..d64be37 100644 --- a/tests/middleware/redirects.test.js +++ b/tests/middleware/redirects.test.js @@ -8,14 +8,14 @@ describe("Redirects middleware", () => { headers: {}, socket: { encrypted: false, remoteAddress: "8.8.8.8" }, isProxy: false, - url: "/test", + url: "/test" }; res = { redirect: jest.fn(), - error: jest.fn(), + error: jest.fn() }; logFacilities = { - errmessage: jest.fn(), + errmessage: jest.fn() }; config = { secure: true, @@ -25,7 +25,7 @@ describe("Redirects middleware", () => { sport: 443, spubport: 8443, wwwredirect: true, - domain: "example.com", + domain: "example.com" }; next = jest.fn(); }); diff --git a/tests/middleware/responseHeaders.test.js b/tests/middleware/responseHeaders.test.js index 51c942d..839ee52 100644 --- a/tests/middleware/responseHeaders.test.js +++ b/tests/middleware/responseHeaders.test.js @@ -8,7 +8,7 @@ describe("Response header setting middleware", () => { res = { setHeader: jest.fn() }; next = jest.fn(); config = { - getCustomHeaders: jest.fn(() => ({ "X-Custom-Header": "custom-value" })), + getCustomHeaders: jest.fn(() => ({ "X-Custom-Header": "custom-value" })) }; logFacilities = {}; }); @@ -18,7 +18,7 @@ describe("Response header setting middleware", () => { expect(res.setHeader).toHaveBeenCalledWith( "X-Custom-Header", - "custom-value", + "custom-value" ); expect(next).toHaveBeenCalled(); }); diff --git a/tests/middleware/rewriteURL.test.js b/tests/middleware/rewriteURL.test.js index 13b3c22..14d6e56 100644 --- a/tests/middleware/rewriteURL.test.js +++ b/tests/middleware/rewriteURL.test.js @@ -17,40 +17,40 @@ describe("rewriteURL middleware", () => { parsedURL: { pathname: "/test", search: "", - hash: "", + hash: "" }, url: "/test", headers: { - host: "test.com", + host: "test.com" }, socket: { encrypted: false, - localAddress: "127.0.0.1", - }, + localAddress: "127.0.0.1" + } }; res = { - error: jest.fn(), + error: jest.fn() }; logFacilities = { resmessage: jest.fn(), - errmessage: jest.fn(), + errmessage: jest.fn() }; config = { rewriteMap: [], domain: "test.com", - allowDoubleSlashes: false, + allowDoubleSlashes: false }; next = jest.fn(); // Make mocks call actual functions createRegex.mockImplementation((...params) => - jest.requireActual("../../src/utils/createRegex.js")(...params), + jest.requireActual("../../src/utils/createRegex.js")(...params) ); parseURL.mockImplementation((...params) => - jest.requireActual("../../src/utils/urlParser.js")(...params), + jest.requireActual("../../src/utils/urlParser.js")(...params) ); sanitizeURL.mockImplementation((...params) => - jest.requireActual("../../src/utils/urlSanitizer.js")(...params), + jest.requireActual("../../src/utils/urlSanitizer.js")(...params) ); }); @@ -73,10 +73,10 @@ describe("rewriteURL middleware", () => { replacements: [ { regex: "/.*/", - replacement: "error", - }, - ], - }, + replacement: "error" + } + ] + } ]; createRegex.mockImplementation(() => { throw new Error("Test error"); @@ -93,10 +93,10 @@ describe("rewriteURL middleware", () => { replacements: [ { regex: "/.*/", - replacement: "/new", - }, - ], - }, + replacement: "/new" + } + ] + } ]; parseURL.mockImplementation(() => { throw new Error("Test error"); @@ -113,10 +113,10 @@ describe("rewriteURL middleware", () => { replacements: [ { regex: "/.*/", - replacement: "/new", - }, - ], - }, + replacement: "/new" + } + ] + } ]; sanitizeURL.mockReturnValue("/sanitized"); middleware(req, res, logFacilities, config, next); @@ -132,10 +132,10 @@ describe("rewriteURL middleware", () => { replacements: [ { regex: "/.*/", - replacement: "/new", - }, - ], - }, + replacement: "/new" + } + ] + } ]; middleware(req, res, logFacilities, config, next); expect(next).toHaveBeenCalled(); diff --git a/tests/middleware/staticFileServingAndDirectoryListing.test.js b/tests/middleware/staticFileServingAndDirectoryListing.test.js index db065a0..dd26978 100644 --- a/tests/middleware/staticFileServingAndDirectoryListing.test.js +++ b/tests/middleware/staticFileServingAndDirectoryListing.test.js @@ -15,20 +15,20 @@ describe("Static file serving and directory listings middleware", () => { headers: { host: "example.com", "accept-encoding": "gzip, deflate, br", - "user-agent": "Mozilla/5.0", + "user-agent": "Mozilla/5.0" }, socket: { - localAddress: "127.0.0.1", - }, + localAddress: "127.0.0.1" + } }); req.parsedURL = { - pathname: "/", + pathname: "/" }; req.originalParsedURL = { - pathname: "/", + pathname: "/" }; res = httpMocks.createResponse({ - eventEmitter: require("events").EventEmitter, + eventEmitter: require("events").EventEmitter }); res.error = (statusCode) => { // Very simple replacement of res.error @@ -39,14 +39,14 @@ describe("Static file serving and directory listings middleware", () => { res.foot = ""; logFacilities = { errmessage: jest.fn(), - resmessage: jest.fn(), + resmessage: jest.fn() }; config = { enableDirectoryListing: true, enableDirectoryListingVHost: [], enableCompression: true, dontCompress: [], - generateServerString: jest.fn().mockReturnValue("Server"), + generateServerString: jest.fn().mockReturnValue("Server") }; next = jest.fn(); }); @@ -64,7 +64,7 @@ describe("Static file serving and directory listings middleware", () => { expect(res.statusCode).toBe(404); expect(logFacilities.errmessage).toHaveBeenCalledWith( - "Resource not found.", + "Resource not found." ); }); @@ -78,7 +78,7 @@ describe("Static file serving and directory listings middleware", () => { expect(res.statusCode).toBe(403); expect(logFacilities.errmessage).toHaveBeenCalledWith( - "Directory listing is disabled.", + "Directory listing is disabled." ); }); @@ -122,7 +122,7 @@ describe("Static file serving and directory listings middleware", () => { expect(res.statusCode).toBe(508); expect(logFacilities.errmessage).toHaveBeenCalledWith( - "Symbolic link loop detected.", + "Symbolic link loop detected." ); }); @@ -141,7 +141,7 @@ describe("Static file serving and directory listings middleware", () => { cb(null, { isDirectory: () => false, isFile: () => false, - isBlockDevice: () => true, + isBlockDevice: () => true }); }); @@ -149,7 +149,7 @@ describe("Static file serving and directory listings middleware", () => { expect(res.statusCode).toBe(501); expect(logFacilities.errmessage).toHaveBeenCalledWith( - expect.stringContaining("doesn't support block devices"), + expect.stringContaining("doesn't support block devices") ); }); @@ -172,7 +172,7 @@ describe("Static file serving and directory listings middleware", () => { isDirectory: () => false, isFile: () => true, size: 1024, - mtime: new Date(), + mtime: new Date() }); } }); @@ -198,7 +198,7 @@ describe("Static file serving and directory listings middleware", () => { cb(null, { isDirectory: () => false, isFile: () => true, - size: 9, + size: 9 }); } }); @@ -229,7 +229,7 @@ describe("Static file serving and directory listings middleware", () => { destStream.end("mock data"); } return destStream; - }, + } }; fs.createReadStream.mockImplementation(() => { diff --git a/tests/middleware/status.test.js b/tests/middleware/status.test.js index a5824be..075cf6c 100644 --- a/tests/middleware/status.test.js +++ b/tests/middleware/status.test.js @@ -8,18 +8,18 @@ describe("Status middleware", () => { beforeEach(() => { req = { parsedURL: { pathname: "/svrjsstatus.svr" }, - headers: { host: "localhost" }, + headers: { host: "localhost" } }; res = { writeHead: jest.fn(), end: jest.fn(), head: "", - foot: "", + foot: "" }; logFacilities = {}; config = { allowStatus: true, - generateServerString: () => "Test Server", + generateServerString: () => "Test Server" }; next = jest.fn(); process.reqcounter = 100; @@ -35,7 +35,7 @@ describe("Status middleware", () => { test("should set response headers and body when conditions are met", () => { middleware(req, res, logFacilities, config, next); expect(res.writeHead).toHaveBeenCalledWith(200, http.STATUS_CODES[200], { - "Content-Type": "text/html; charset=utf-8", + "Content-Type": "text/html; charset=utf-8" }); expect(res.end).toHaveBeenCalled(); }); @@ -51,7 +51,7 @@ describe("Status middleware", () => { jest.spyOn(os, "platform").mockReturnValue("win32"); middleware(req, res, logFacilities, config, next); expect(res.writeHead).toHaveBeenCalledWith(200, http.STATUS_CODES[200], { - "Content-Type": "text/html; charset=utf-8", + "Content-Type": "text/html; charset=utf-8" }); expect(res.end).toHaveBeenCalled(); os.platform.mockRestore(); @@ -61,7 +61,7 @@ describe("Status middleware", () => { req.headers.host = undefined; middleware(req, res, logFacilities, config, next); expect(res.writeHead).toHaveBeenCalledWith(200, http.STATUS_CODES[200], { - "Content-Type": "text/html; charset=utf-8", + "Content-Type": "text/html; charset=utf-8" }); expect(res.end).toHaveBeenCalled(); }); diff --git a/tests/middleware/urlSanitizer.test.js b/tests/middleware/urlSanitizer.test.js index 975004d..89c6a9f 100644 --- a/tests/middleware/urlSanitizer.test.js +++ b/tests/middleware/urlSanitizer.test.js @@ -13,28 +13,28 @@ describe("Path sanitizer middleware", () => { parsedURL: { pathname: "/test", search: "?query=test", - hash: "#hash", + hash: "#hash" }, url: "/test?query=test#hash", isProxy: false, headers: { - host: "test.com", + host: "test.com" }, socket: { - encrypted: false, - }, + encrypted: false + } }; res = { redirect: jest.fn(), - error: jest.fn(), + error: jest.fn() }; logFacilities = { - resmessage: jest.fn(), + resmessage: jest.fn() }; config = { allowDoubleSlashes: false, rewriteDirtyURLs: false, - domain: "test.com", + domain: "test.com" }; next = jest.fn(); @@ -52,7 +52,7 @@ describe("Path sanitizer middleware", () => { middleware(req, res, logFacilities, config, next); expect(res.redirect).toHaveBeenCalledWith( "/dirty%20url?query=test#hash", - false, + false ); expect(next).not.toHaveBeenCalled(); }); @@ -71,7 +71,7 @@ describe("Path sanitizer middleware", () => { middleware(req, res, logFacilities, config, next); expect(res.redirect).toHaveBeenCalledWith( "/clean%20url?query=test#hash", - false, + false ); expect(next).not.toHaveBeenCalled(); }); diff --git a/tests/middleware/webRootPrefixes.test.js b/tests/middleware/webRootPrefixes.test.js index c21247c..e0964d5 100644 --- a/tests/middleware/webRootPrefixes.test.js +++ b/tests/middleware/webRootPrefixes.test.js @@ -14,7 +14,7 @@ describe("Web root prefixes middleware", () => { url: "/test", parsedURL: { pathname: "/test" }, headers: { host: "test.com" }, - socket: { localAddress: "127.0.0.1" }, + socket: { localAddress: "127.0.0.1" } }; res = { error: jest.fn() }; logFacilities = { resmessage: jest.fn(), errmessage: jest.fn() }; @@ -22,8 +22,8 @@ describe("Web root prefixes middleware", () => { allowPostfixDoubleSlashes: true, wwwrootPostfixPrefixesVHost: [], wwwrootPostfixesVHost: [ - { host: "test.com", ip: "127.0.0.1", postfix: "postfix" }, - ], + { host: "test.com", ip: "127.0.0.1", postfix: "postfix" } + ] }; next = jest.fn(); @@ -35,7 +35,7 @@ describe("Web root prefixes middleware", () => { middleware(req, res, logFacilities, config, next); expect(req.url).toBe("/postfix/test"); expect(logFacilities.resmessage).toHaveBeenCalledWith( - "Added web root postfix: /test => /postfix/test", + "Added web root postfix: /test => /postfix/test" ); }); @@ -48,7 +48,7 @@ describe("Web root prefixes middleware", () => { test("should not add web root postfix if no matching config is found", () => { config.wwwrootPostfixesVHost = [ - { host: "example.com", ip: "127.0.0.1", postfix: "postfix" }, + { host: "example.com", ip: "127.0.0.1", postfix: "postfix" } ]; middleware(req, res, logFacilities, config, next); expect(req.url).toBe("/test"); diff --git a/tests/utils/createRegex.test.js b/tests/utils/createRegex.test.js index a61562b..a121fd5 100644 --- a/tests/utils/createRegex.test.js +++ b/tests/utils/createRegex.test.js @@ -2,7 +2,7 @@ const createRegex = require("../../src/utils/createRegex.js"); const os = require("os"); jest.mock("os", () => ({ - platform: jest.fn(), + platform: jest.fn() })); describe("Regular expression creation function", () => { @@ -12,7 +12,7 @@ describe("Regular expression creation function", () => { test("should throw an error for invalid regular expression", () => { expect(() => createRegex("invalid/regex", false)).toThrow( - "Invalid regular expression: invalid/regex", + "Invalid regular expression: invalid/regex" ); }); diff --git a/tests/utils/deepClone.test.js b/tests/utils/deepClone.test.js index d288b54..760ec66 100644 --- a/tests/utils/deepClone.test.js +++ b/tests/utils/deepClone.test.js @@ -63,7 +63,7 @@ describe("Deep cloning function", () => { const original = { a: 1, b: [2, 3, { c: 4 }], - d: { e: 5, f: [6, { g: 7 }] }, + d: { e: 5, f: [6, { g: 7 }] } }; const cloned = deepClone(original); expect(cloned).toEqual(original); diff --git a/tests/utils/forbiddenPaths.test.js b/tests/utils/forbiddenPaths.test.js index 7e0372b..9c77867 100644 --- a/tests/utils/forbiddenPaths.test.js +++ b/tests/utils/forbiddenPaths.test.js @@ -2,12 +2,12 @@ const { getInitializePath, isForbiddenPath, isIndexOfForbiddenPath, - forbiddenPaths, + forbiddenPaths } = require("../../src/utils/forbiddenPaths.js"); const os = require("os"); jest.mock("os", () => ({ - platform: jest.fn(), + platform: jest.fn() })); describe("Forbidden paths handling", () => { @@ -16,10 +16,10 @@ describe("Forbidden paths handling", () => { forbiddenPaths.config = getInitializePath("./config.json"); forbiddenPaths.serverSideScriptDirectories = []; forbiddenPaths.serverSideScriptDirectories.push( - getInitializePath("./node_modules"), + getInitializePath("./node_modules") ); forbiddenPaths.serverSideScriptDirectories.push( - getInitializePath("./mods"), + getInitializePath("./mods") ); process.cwd = () => "/usr/lib/mocksvrjs"; process.dirname = "/usr/lib/mocksvrjs"; @@ -43,7 +43,7 @@ describe("Forbidden paths handling", () => { test("should handle absolute paths on Unix", () => { os.platform.mockReturnValue("linux"); expect(getInitializePath("/absolute/path")).toBe( - "/../../../absolute/path", + "/../../../absolute/path" ); }); @@ -91,13 +91,13 @@ describe("Forbidden paths handling", () => { test("should handle array of forbidden paths", () => { os.platform.mockReturnValue("linux"); expect( - isForbiddenPath("/node_modules", "serverSideScriptDirectories"), + isForbiddenPath("/node_modules", "serverSideScriptDirectories") ).toBe(true); expect(isForbiddenPath("/mods", "serverSideScriptDirectories")).toBe( - true, + true ); expect( - isForbiddenPath("/notforbidden", "serverSideScriptDirectories"), + isForbiddenPath("/notforbidden", "serverSideScriptDirectories") ).toBe(false); }); }); @@ -107,7 +107,7 @@ describe("Forbidden paths handling", () => { os.platform.mockReturnValue("linux"); expect(isIndexOfForbiddenPath("/config.json", "config")).toBe(true); expect( - isIndexOfForbiddenPath("/node_modules/", "serverSideScriptDirectories"), + isIndexOfForbiddenPath("/node_modules/", "serverSideScriptDirectories") ).toBe(true); }); @@ -115,14 +115,14 @@ describe("Forbidden paths handling", () => { os.platform.mockReturnValue("linux"); expect(isIndexOfForbiddenPath("/notconfig.json", "config")).toBe(false); expect( - isIndexOfForbiddenPath("/notforbidden/", "serverSideScriptDirectories"), + isIndexOfForbiddenPath("/notforbidden/", "serverSideScriptDirectories") ).toBe(false); expect(isIndexOfForbiddenPath("/config.json.fake", "config")).toBe(false); expect( isIndexOfForbiddenPath( "/node_modules_fake/", - "serverSideScriptDirectories", - ), + "serverSideScriptDirectories" + ) ).toBe(false); }); @@ -133,20 +133,20 @@ describe("Forbidden paths handling", () => { os.platform.mockReturnValue("win32"); expect(isIndexOfForbiddenPath("/CONFIG.JSON", "config")).toBe(true); expect( - isIndexOfForbiddenPath("/NODE_MODULES/", "serverSideScriptDirectories"), + isIndexOfForbiddenPath("/NODE_MODULES/", "serverSideScriptDirectories") ).toBe(true); }); test("should handle array of forbidden paths", () => { os.platform.mockReturnValue("linux"); expect( - isIndexOfForbiddenPath("/node_modules/", "serverSideScriptDirectories"), + isIndexOfForbiddenPath("/node_modules/", "serverSideScriptDirectories") ).toBe(true); expect( - isIndexOfForbiddenPath("/mods/", "serverSideScriptDirectories"), + isIndexOfForbiddenPath("/mods/", "serverSideScriptDirectories") ).toBe(true); expect( - isIndexOfForbiddenPath("/notforbidden/", "serverSideScriptDirectories"), + isIndexOfForbiddenPath("/notforbidden/", "serverSideScriptDirectories") ).toBe(false); }); }); diff --git a/tests/utils/ipBlockList.test.js b/tests/utils/ipBlockList.test.js index 7446bdc..c34c77c 100644 --- a/tests/utils/ipBlockList.test.js +++ b/tests/utils/ipBlockList.test.js @@ -16,10 +16,10 @@ describe("IP block list functionality", () => { test("should add and check IPv6 address", () => { blockList.add("2001:0db8:85a3:0000:0000:8a2e:0370:7334"); expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe( - true, + true ); expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7335")).toBe( - false, + false ); }); @@ -33,13 +33,13 @@ describe("IP block list functionality", () => { test("should add and check IPv6 CIDR block", () => { blockList.add("2001:0db8:85a3::/64"); expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe( - true, + true ); expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7335")).toBe( - true, + true ); expect(blockList.check("2001:0db8:85a4:0000:0000:8a2e:0370:7334")).toBe( - false, + false ); }); @@ -53,11 +53,11 @@ describe("IP block list functionality", () => { test("should remove IPv6 address", () => { blockList.add("2001:0db8:85a3:0000:0000:8a2e:0370:7334"); expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe( - true, + true ); blockList.remove("2001:0db8:85a3:0000:0000:8a2e:0370:7334"); expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe( - false, + false ); }); @@ -71,11 +71,11 @@ describe("IP block list functionality", () => { test("should remove IPv6 CIDR block", () => { blockList.add("2001:0db8:85a3::/64"); expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe( - true, + true ); blockList.remove("2001:0db8:85a3::/64"); expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe( - false, + false ); }); @@ -90,16 +90,16 @@ describe("IP block list functionality", () => { test("should handle edge cases for IPv6 addresses", () => { blockList.add("2001:0db8:85a3::/64"); expect(blockList.check("2001:0db8:85a2:ffff:ffff:ffff:ffff:ffff")).toBe( - false, + false ); expect(blockList.check("2001:0db8:85a3:0000:0000:0000:0000:0000")).toBe( - true, + true ); expect(blockList.check("2001:0db8:85a3:0000:ffff:ffff:ffff:ffff")).toBe( - true, + true ); expect(blockList.check("2001:0db8:85a3:0001:0000:0000:0000:0000")).toBe( - false, + false ); }); }); diff --git a/tests/utils/ipMatch.test.js b/tests/utils/ipMatch.test.js index 28c5132..1e44711 100644 --- a/tests/utils/ipMatch.test.js +++ b/tests/utils/ipMatch.test.js @@ -29,8 +29,8 @@ describe("IP address matching function", () => { expect( ipMatch( "2001:0db8:85a3:0000:0000:8a2e:0370:7334", - "2001:db8:85a3::8a2e:370:7334", - ), + "2001:db8:85a3::8a2e:370:7334" + ) ).toBe(true); }); @@ -38,8 +38,8 @@ describe("IP address matching function", () => { expect( ipMatch( "2001:0db8:85a3:0000:0000:8a2e:0370:7334", - "2001:db8:85a3::8a2e:370:7335", - ), + "2001:db8:85a3::8a2e:370:7335" + ) ).toBe(false); }); @@ -58,7 +58,7 @@ describe("IP address matching function", () => { test("should handle mixed case IP addresses", () => { expect(ipMatch("192.168.1.1", "192.168.1.1")).toBe(true); expect( - ipMatch("2001:DB8:85A3::8A2E:370:7334", "2001:db8:85a3::8a2e:370:7334"), + ipMatch("2001:DB8:85A3::8A2E:370:7334", "2001:db8:85a3::8a2e:370:7334") ).toBe(true); }); @@ -66,8 +66,8 @@ describe("IP address matching function", () => { expect( ipMatch( "2001:0db8:85a3:0000:0000:8a2e:0370:7334", - "2001:db8:85a3::8a2e:370:7334", - ), + "2001:db8:85a3::8a2e:370:7334" + ) ).toBe(true); }); @@ -75,8 +75,8 @@ describe("IP address matching function", () => { expect( ipMatch( "2001:0DB8:85A3:0000:0000:8A2E:0370:7334", - "2001:db8:85a3::8a2e:370:7334", - ), + "2001:db8:85a3::8a2e:370:7334" + ) ).toBe(true); }); }); diff --git a/tests/utils/ipSubnetUtils.test.js b/tests/utils/ipSubnetUtils.test.js index 41c3dea..e636e8b 100644 --- a/tests/utils/ipSubnetUtils.test.js +++ b/tests/utils/ipSubnetUtils.test.js @@ -1,37 +1,37 @@ const { calculateBroadcastIPv4FromCidr, - calculateNetworkIPv4FromCidr, + calculateNetworkIPv4FromCidr } = require("../../src/utils/ipSubnetUtils.js"); describe("IPv4 subnet utilties", () => { describe("calculateBroadcastIPv4FromCidr", () => { test("should return the broadcast address for a given CIDR", () => { expect(calculateBroadcastIPv4FromCidr("192.168.1.0/24")).toBe( - "192.168.1.255", + "192.168.1.255" ); expect(calculateBroadcastIPv4FromCidr("192.168.1.0/25")).toBe( - "192.168.1.127", + "192.168.1.127" ); expect(calculateBroadcastIPv4FromCidr("192.168.1.0/26")).toBe( - "192.168.1.63", + "192.168.1.63" ); expect(calculateBroadcastIPv4FromCidr("192.168.1.0/27")).toBe( - "192.168.1.31", + "192.168.1.31" ); expect(calculateBroadcastIPv4FromCidr("192.168.1.0/28")).toBe( - "192.168.1.15", + "192.168.1.15" ); expect(calculateBroadcastIPv4FromCidr("192.168.1.0/29")).toBe( - "192.168.1.7", + "192.168.1.7" ); expect(calculateBroadcastIPv4FromCidr("192.168.1.0/30")).toBe( - "192.168.1.3", + "192.168.1.3" ); expect(calculateBroadcastIPv4FromCidr("192.168.1.0/31")).toBe( - "192.168.1.1", + "192.168.1.1" ); expect(calculateBroadcastIPv4FromCidr("192.168.1.0/32")).toBe( - "192.168.1.0", + "192.168.1.0" ); }); @@ -46,31 +46,31 @@ describe("IPv4 subnet utilties", () => { describe("calculateNetworkIPv4FromCidr", () => { test("should return the network address for a given CIDR", () => { expect(calculateNetworkIPv4FromCidr("192.168.1.0/24")).toBe( - "192.168.1.0", + "192.168.1.0" ); expect(calculateNetworkIPv4FromCidr("192.168.1.0/25")).toBe( - "192.168.1.0", + "192.168.1.0" ); expect(calculateNetworkIPv4FromCidr("192.168.1.0/26")).toBe( - "192.168.1.0", + "192.168.1.0" ); expect(calculateNetworkIPv4FromCidr("192.168.1.0/27")).toBe( - "192.168.1.0", + "192.168.1.0" ); expect(calculateNetworkIPv4FromCidr("192.168.1.0/28")).toBe( - "192.168.1.0", + "192.168.1.0" ); expect(calculateNetworkIPv4FromCidr("192.168.1.0/29")).toBe( - "192.168.1.0", + "192.168.1.0" ); expect(calculateNetworkIPv4FromCidr("192.168.1.0/30")).toBe( - "192.168.1.0", + "192.168.1.0" ); expect(calculateNetworkIPv4FromCidr("192.168.1.0/31")).toBe( - "192.168.1.0", + "192.168.1.0" ); expect(calculateNetworkIPv4FromCidr("192.168.1.0/32")).toBe( - "192.168.1.0", + "192.168.1.0" ); }); diff --git a/tests/utils/sha256.test.js b/tests/utils/sha256.test.js index 13447bf..25eb51a 100644 --- a/tests/utils/sha256.test.js +++ b/tests/utils/sha256.test.js @@ -5,8 +5,8 @@ const crypto = require("crypto"); jest.mock("crypto", () => ({ createHash: jest.fn(() => ({ update: jest.fn(), - digest: jest.fn(() => "mockedHash"), - })), + digest: jest.fn(() => "mockedHash") + })) })); describe("SHA256 hash", () => { @@ -20,7 +20,7 @@ describe("SHA256 hash", () => { crypto.__disabled__ = null; const result = sha256("test"); expect(result).toBe( - "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", + "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08" ); }); @@ -28,7 +28,7 @@ describe("SHA256 hash", () => { crypto.__disabled__ = null; const result = sha256(""); expect(result).toBe( - "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ); }); @@ -36,7 +36,7 @@ describe("SHA256 hash", () => { crypto.__disabled__ = null; const result = sha256("!@#$%^&*()"); expect(result).toBe( - "95ce789c5c9d18490972709838ca3a9719094bca3ac16332cfec0652b0236141", + "95ce789c5c9d18490972709838ca3a9719094bca3ac16332cfec0652b0236141" ); }); @@ -45,7 +45,7 @@ describe("SHA256 hash", () => { const longString = "a".repeat(1000); const result = sha256(longString); expect(result).toBe( - "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3", + "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3" ); }); @@ -53,7 +53,7 @@ describe("SHA256 hash", () => { crypto.__disabled__ = null; const result = sha256("éñ"); expect(result).toBe( - "c53435f74d8215688e74112f1c6527ad31fd3b72939769a75d09a14cd8a80cfe", + "c53435f74d8215688e74112f1c6527ad31fd3b72939769a75d09a14cd8a80cfe" ); }); }); diff --git a/tests/utils/urlMojibakeFixer.test.js b/tests/utils/urlMojibakeFixer.test.js index 50373cc..4cc2e92 100644 --- a/tests/utils/urlMojibakeFixer.test.js +++ b/tests/utils/urlMojibakeFixer.test.js @@ -36,7 +36,7 @@ describe("URL mojibake fixer", () => { test("should handle strings with mixed characters", () => { expect(fixNodeMojibakeURL("hello123 é world ñ!@#$%^&*()")).toBe( - "hello123 %E9 world %F1!@#$%^&*()", + "hello123 %E9 world %F1!@#$%^&*()" ); }); }); diff --git a/tests/utils/urlParser.test.js b/tests/utils/urlParser.test.js index f5953aa..b46d9b8 100644 --- a/tests/utils/urlParser.test.js +++ b/tests/utils/urlParser.test.js @@ -62,7 +62,7 @@ describe("URL parser", () => { test("should parse a URL with all components", () => { const parsedUrl = parseURL( - "http://user:pass@example.com:8080/path/to/resource?query=string#fragment", + "http://user:pass@example.com:8080/path/to/resource?query=string#fragment" ); expect(parsedUrl.protocol).toBe("http:"); expect(parsedUrl.auth).toBe("user:pass"); @@ -74,7 +74,7 @@ describe("URL parser", () => { expect(parsedUrl.hash).toBe("#fragment"); expect(parsedUrl.path).toBe("/path/to/resource?query=string"); expect(parsedUrl.href).toBe( - "http://user:pass@example.com:8080/path/to/resource?query=string#fragment", + "http://user:pass@example.com:8080/path/to/resource?query=string#fragment" ); }); }); diff --git a/utils/loghighlight.js b/utils/loghighlight.js index f32486f..b713f9e 100644 --- a/utils/loghighlight.js +++ b/utils/loghighlight.js @@ -20,7 +20,7 @@ for ( ) { console.log("SVR.JS log highlighter usage:"); console.log( - " | node loghighlight.js [-h] [--help] [-?] [/h] [/?]", + " | node loghighlight.js [-h] [--help] [-?] [/h] [/?]" ); console.log("-h -? /h /? --help -- Displays help"); process.exit(0); @@ -28,7 +28,7 @@ for ( console.log("Unrecognized argument: " + args[i]); console.log("SVR.JS log highlighter usage:"); console.log( - " | node loghighlight.js [-h] [--help] [-?] [/h] [/?]", + " | node loghighlight.js [-h] [--help] [-?] [/h] [/?]" ); console.log("-h -? /h /? --help -- Displays help"); process.exit(1); @@ -39,7 +39,7 @@ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false, - prompt: "", + prompt: "" }); rl.prompt(); rl.on("line", (line) => { @@ -54,36 +54,36 @@ function viewLog(log) { log[i] = log[i].replace( "SERVER REQUEST MESSAGE", - "\x1b[34m\x1b[1mSERVER REQUEST MESSAGE\x1b[22m", + "\x1b[34m\x1b[1mSERVER REQUEST MESSAGE\x1b[22m" ) + "\x1b[37m\x1b[0m"; } else if (log[i].indexOf("SERVER RESPONSE MESSAGE") != -1) { log[i] = log[i].replace( "SERVER RESPONSE MESSAGE", - "\x1b[32m\x1b[1mSERVER RESPONSE MESSAGE\x1b[22m", + "\x1b[32m\x1b[1mSERVER RESPONSE MESSAGE\x1b[22m" ) + "\x1b[37m\x1b[0m"; } else if (log[i].indexOf("SERVER RESPONSE ERROR MESSAGE") != -1) { log[i] = log[i].replace( "SERVER RESPONSE ERROR MESSAGE", - "\x1b[31m\x1b[1mSERVER RESPONSE ERROR MESSAGE\x1b[22m", + "\x1b[31m\x1b[1mSERVER RESPONSE ERROR MESSAGE\x1b[22m" ) + "\x1b[37m\x1b[0m"; } else if (log[i].indexOf("SERVER ERROR MESSAGE") != -1) { log[i] = log[i].replace( "SERVER ERROR MESSAGE", - "\x1b[41m\x1b[1mSERVER ERROR MESSAGE\x1b[22m", + "\x1b[41m\x1b[1mSERVER ERROR MESSAGE\x1b[22m" ) + "\x1b[40m\x1b[0m"; } else if (log[i].indexOf("SERVER WARNING MESSAGE") != -1) { log[i] = log[i].replace( "SERVER WARNING MESSAGE", - "\x1b[43m\x1b[1mSERVER WARNING MESSAGE\x1b[22m", + "\x1b[43m\x1b[1mSERVER WARNING MESSAGE\x1b[22m" ) + "\x1b[40m\x1b[0m"; } else if (log[i].indexOf("SERVER MESSAGE") != -1) { log[i] = log[i].replace( "SERVER MESSAGE", - "\x1b[1mSERVER MESSAGE\x1b[22m", + "\x1b[1mSERVER MESSAGE\x1b[22m" ); } console.log(log[i]); diff --git a/utils/logviewer.js b/utils/logviewer.js index 33c8454..6a0092f 100644 --- a/utils/logviewer.js +++ b/utils/logviewer.js @@ -72,7 +72,7 @@ const logo = [ "\x1b[0m ,///////,", "", "", - "\x1b[0m", + "\x1b[0m" ]; for (let i = 0; i < logo.length; i++) { @@ -89,7 +89,7 @@ function prompt(options) { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, - prompt: "logviewer> ", + prompt: "logviewer> " }); console.log("Options:"); for (let i = 0; i < options.length; i++) { @@ -120,36 +120,36 @@ function viewLog(log) { log[i] = log[i].replace( "SERVER REQUEST MESSAGE", - "\x1b[34m\x1b[1mSERVER REQUEST MESSAGE\x1b[22m", + "\x1b[34m\x1b[1mSERVER REQUEST MESSAGE\x1b[22m" ) + "\x1b[37m\x1b[0m"; } else if (log[i].indexOf("SERVER RESPONSE MESSAGE") != -1) { log[i] = log[i].replace( "SERVER RESPONSE MESSAGE", - "\x1b[32m\x1b[1mSERVER RESPONSE MESSAGE\x1b[22m", + "\x1b[32m\x1b[1mSERVER RESPONSE MESSAGE\x1b[22m" ) + "\x1b[37m\x1b[0m"; } else if (log[i].indexOf("SERVER RESPONSE ERROR MESSAGE") != -1) { log[i] = log[i].replace( "SERVER RESPONSE ERROR MESSAGE", - "\x1b[31m\x1b[1mSERVER RESPONSE ERROR MESSAGE\x1b[22m", + "\x1b[31m\x1b[1mSERVER RESPONSE ERROR MESSAGE\x1b[22m" ) + "\x1b[37m\x1b[0m"; } else if (log[i].indexOf("SERVER ERROR MESSAGE") != -1) { log[i] = log[i].replace( "SERVER ERROR MESSAGE", - "\x1b[41m\x1b[1mSERVER ERROR MESSAGE\x1b[22m", + "\x1b[41m\x1b[1mSERVER ERROR MESSAGE\x1b[22m" ) + "\x1b[40m\x1b[0m"; } else if (log[i].indexOf("SERVER WARNING MESSAGE") != -1) { log[i] = log[i].replace( "SERVER WARNING MESSAGE", - "\x1b[43m\x1b[1mSERVER WARNING MESSAGE\x1b[22m", + "\x1b[43m\x1b[1mSERVER WARNING MESSAGE\x1b[22m" ) + "\x1b[40m\x1b[0m"; } else if (log[i].indexOf("SERVER MESSAGE") != -1) { log[i] = log[i].replace( "SERVER MESSAGE", - "\x1b[1mSERVER MESSAGE\x1b[22m", + "\x1b[1mSERVER MESSAGE\x1b[22m" ); } console.log(log[i]); @@ -173,7 +173,7 @@ function viewMasterLogs() { fs .readFileSync(__dirname + "/log/" + latestLogFileName) .toString() - .split("\n"), + .split("\n") ); prompt(mainOptions); } @@ -242,7 +242,7 @@ function viewFilteredWorkerLogsPrompt() { var rl2 = readline.createInterface({ input: process.stdin, output: process.stdout, - prompt: "filter> ", + prompt: "filter> " }); console.log("Input filter:"); rl2.prompt(); @@ -257,15 +257,15 @@ var mainOptions = [ { name: "View 5 latest worker logs", callback: viewWorkerLogs }, { name: "View filtered worker logs (latest 20 logs)", - callback: viewFilteredWorkerLogsPrompt, + callback: viewFilteredWorkerLogsPrompt }, { name: "Exit log viewer", callback: () => { console.log("Bye!"); process.exit(0); - }, - }, + } + } ]; prompt(mainOptions); diff --git a/utils/svrpasswd.js b/utils/svrpasswd.js index 86f33ec..25c6820 100644 --- a/utils/svrpasswd.js +++ b/utils/svrpasswd.js @@ -123,7 +123,7 @@ try { 0x90befffa, 0xa4506ceb, 0xbef9a3f7, - 0xc67178f2, + 0xc67178f2 ); let HASH = new Array( 0x6a09e667, @@ -133,7 +133,7 @@ try { 0x510e527f, 0x9b05688c, 0x1f83d9ab, - 0x5be0cd19, + 0x5be0cd19 ); let W = new Array(64); let a, b, c, d, e, f, g, h; @@ -158,14 +158,14 @@ try { W[j] = safeAdd( safeAdd( safeAdd(Gamma1256(W[j - 2]), W[j - 7]), - Gamma0256(W[j - 15]), + Gamma0256(W[j - 15]) ), - W[j - 16], + W[j - 16] ); T1 = safeAdd( safeAdd(safeAdd(safeAdd(h, Sigma1256(e)), Ch(e, f, g)), K[j]), - W[j], + W[j] ); T2 = safeAdd(Sigma0256(a), Maj(a, b, c)); @@ -229,7 +229,7 @@ try { for (let i = 0; i < binarray.length * 4; i++) { str += hexTab.charAt( - (binarray[i >> 2] >> ((3 - (i % 4)) * 8 + 4)) & 0xf, + (binarray[i >> 2] >> ((3 - (i % 4)) * 8 + 4)) & 0xf ) + hexTab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8)) & 0xf); } @@ -244,7 +244,7 @@ try { hx.push(parseInt(str[i] + str[i + 1], 16)); } return Buffer.from(hx); - }, + } }; }; } @@ -279,7 +279,7 @@ function saveConfig() { let configJSONobj = {}; if (fs.existsSync(__dirname + "/config.json")) configJSONobj = JSON.parse( - fs.readFileSync(__dirname + "/config.json").toString(), + fs.readFileSync(__dirname + "/config.json").toString() ); configJSONobj.users = users; const configString = JSON.stringify(configJSONobj, null, 2); @@ -314,7 +314,7 @@ for ( ) { console.log("SVR.JS user tool usage:"); console.log( - "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] ", + "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] " ); console.log("-h -? /h /? --help -- Displays help"); console.log("-a --add -- Add an user"); @@ -325,7 +325,7 @@ for ( if (action != "change") { console.log("Multiple actions specified."); console.log( - "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] ", + "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] " ); console.log("-h -? /h /? --help -- Displays help"); console.log("-a --add -- Add an user"); @@ -338,7 +338,7 @@ for ( if (action != "change") { console.log("Multiple actions specified."); console.log( - "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] ", + "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] " ); console.log("-h -? /h /? --help -- Displays help"); console.log("-a --add -- Add an user"); @@ -351,7 +351,7 @@ for ( if (forcechange) { console.log("Multiple -x options specified."); console.log( - "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] ", + "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] " ); console.log("-h -? /h /? --help -- Displays help"); console.log("-a --add -- Add an user"); @@ -364,7 +364,7 @@ for ( if (user != "") { console.log("Multiple users specified."); console.log( - "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] ", + "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] " ); console.log("-h -? /h /? --help -- Displays help"); console.log("-a --add -- Add an user"); @@ -379,7 +379,7 @@ for ( if (user == "") { console.log("No user specified."); console.log( - "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] ", + "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] " ); console.log("-h -? /h /? --help -- Displays help"); console.log("-a --add -- Add an user"); @@ -419,7 +419,7 @@ function password(callback) { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, - prompt: "Password: ", + prompt: "Password: " }); rl.prompt(); process.stdout.writeold = process.stdout.write; @@ -431,7 +431,7 @@ function password(callback) { var rl = readline.createInterface({ input: process.stdin, output: process.stdout, - prompt: "Confirm password: ", + prompt: "Confirm password: " }); rl.prompt(); process.stdout.writeold = process.stdout.write; @@ -464,7 +464,7 @@ function promptAlgorithms(callback, bypass, pbkdf2, scrypt) { pbkdf2: "PBKDF2 (PBKDF2-HMAC-SHA512, 36250 iterations) - more secure and uses less memory, but slower", scrypt: - "scrypt (N=2^14, r=8, p=1) - faster and more secure, but uses more memory", + "scrypt (N=2^14, r=8, p=1) - faster and more secure, but uses more memory" }; if ( !crypto.pbkdf2 || @@ -472,7 +472,7 @@ function promptAlgorithms(callback, bypass, pbkdf2, scrypt) { !( process.versions.bun && !process.versions.bun.match( - /^(?:0\.|1\.0\.|1\.1\.[0-9](?![0-9])|1\.1\.1[0-2](?![0-9]))/, + /^(?:0\.|1\.0\.|1\.1\.[0-9](?![0-9])|1\.1\.1[0-2](?![0-9]))/ ) )) ) @@ -486,7 +486,7 @@ function promptAlgorithms(callback, bypass, pbkdf2, scrypt) { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, - prompt: "Algorithm: ", + prompt: "Algorithm: " }); rl.prompt(); rl.on("line", (line) => { @@ -537,7 +537,7 @@ if (action == "delete") { salt: salt, pbkdf2: algorithm == "pbkdf2" ? true : undefined, scrypt: algorithm == "scrypt" ? true : undefined, - __svrpasswd_l2: true, + __svrpasswd_l2: true }); saveConfig(); console.log("User added successfully"); @@ -574,7 +574,7 @@ if (action == "delete") { salt: salt, pbkdf2: algorithm == "pbkdf2" ? true : undefined, scrypt: algorithm == "scrypt" ? true : undefined, - __svrpasswd_l2: true, + __svrpasswd_l2: true }; saveConfig(); console.log("Password changed successfully"); @@ -584,6 +584,6 @@ if (action == "delete") { }, users[userindex].__svrpasswd_l2 && !forcechange, users[userindex].pbkdf2, - users[userindex].scrypt, + users[userindex].scrypt ); }
Filename Size Date
-${estats ? estats.mtime.toDateString() : "-"}
-${estats ? estats.mtime.toDateString() : "-"}
[alt]${ename .replace(/&/g, "&") .replace(/ { .replace(//g, - ">", + ">" )}-${estats.mtime.toDateString()}
No files found
No files found