1
0
Fork 0
forked from svrjs/svrjs

style: style the code according to new Prettier rules

This commit is contained in:
Dorian Niemiec 2024-09-01 21:54:42 +02:00
parent 48b112f98b
commit c2eed2870d
56 changed files with 623 additions and 628 deletions

View file

@ -86,7 +86,7 @@ function clientErrorHandler(err, socket) {
}); });
head += "\r\n"; head += "\r\n";
res.write(head); res.write(head);
}, }
}; };
let reqIdInt = Math.floor(Math.random() * 16777216); let reqIdInt = Math.floor(Math.random() * 16777216);
@ -102,7 +102,7 @@ function clientErrorHandler(err, socket) {
errmessage: (msg) => serverconsole.errmessage(msg, reqId), errmessage: (msg) => serverconsole.errmessage(msg, reqId),
locerrmessage: (msg) => serverconsole.locerrmessage(msg, reqId), locerrmessage: (msg) => serverconsole.locerrmessage(msg, reqId),
locwarnmessage: (msg) => serverconsole.locwarnmessage(msg, reqId), locwarnmessage: (msg) => serverconsole.locwarnmessage(msg, reqId),
locmessage: (msg) => serverconsole.locmessage(msg, reqId), locmessage: (msg) => serverconsole.locmessage(msg, reqId)
}; };
socket.on("close", (hasError) => { socket.on("close", (hasError) => {
@ -158,7 +158,7 @@ function clientErrorHandler(err, socket) {
stack stack
) { ) {
throw new TypeError( 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) { } catch (err2) {
callServerError(500, err2); callServerError(500, err2);
} }
}, }
); );
} else { } else {
try { try {
@ -246,7 +246,7 @@ function clientErrorHandler(err, socket) {
stack = generateErrorStack(new Error("Unknown error")); stack = generateErrorStack(new Error("Unknown error"));
if (errorCode == 500 || errorCode == 502) { if (errorCode == 500 || errorCode == 502) {
logFacilities.errmessage( logFacilities.errmessage(
"There was an error while processing the request!", "There was an error while processing the request!"
); );
logFacilities.errmessage("Stack:"); logFacilities.errmessage("Stack:");
logFacilities.errmessage(stack); logFacilities.errmessage(stack);
@ -275,7 +275,7 @@ function clientErrorHandler(err, socket) {
http.STATUS_CODES[errorCode] http.STATUS_CODES[errorCode]
.replace(/&/g, "&") .replace(/&/g, "&")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;"), .replace(/>/g, "&gt;")
) )
.replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode]) .replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode])
.replace( .replace(
@ -287,7 +287,7 @@ function clientErrorHandler(err, socket) {
.replace(/\r\n/g, "<br/>") .replace(/\r\n/g, "<br/>")
.replace(/\n/g, "<br/>") .replace(/\n/g, "<br/>")
.replace(/\r/g, "<br/>") .replace(/\r/g, "<br/>")
.replace(/ {2}/g, "&nbsp;&nbsp;"), .replace(/ {2}/g, "&nbsp;&nbsp;")
) )
.replace( .replace(
/{server}/g, /{server}/g,
@ -299,7 +299,7 @@ function clientErrorHandler(err, socket) {
) )
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;"), .replace(/>/g, "&gt;")
) )
.replace( .replace(
/{contact}/g, /{contact}/g,
@ -308,8 +308,8 @@ function clientErrorHandler(err, socket) {
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") .replace(/>/g, "&gt;")
.replace(/\./g, "[dot]") .replace(/\./g, "[dot]")
.replace(/@/g, "[at]"), .replace(/@/g, "[at]")
)}`, )}`
); );
res.end(); res.end();
} else { } else {
@ -327,7 +327,7 @@ function clientErrorHandler(err, socket) {
http.STATUS_CODES[errorCode] http.STATUS_CODES[errorCode]
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;"), .replace(/>/g, "&gt;")
) )
.replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode]) .replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode])
.replace( .replace(
@ -339,7 +339,7 @@ function clientErrorHandler(err, socket) {
.replace(/\r\n/g, "<br/>") .replace(/\r\n/g, "<br/>")
.replace(/\n/g, "<br/>") .replace(/\n/g, "<br/>")
.replace(/\r/g, "<br/>") .replace(/\r/g, "<br/>")
.replace(/ {2}/g, "&nbsp;&nbsp;"), .replace(/ {2}/g, "&nbsp;&nbsp;")
) )
.replace( .replace(
/{server}/g, /{server}/g,
@ -351,7 +351,7 @@ function clientErrorHandler(err, socket) {
) )
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;"), .replace(/>/g, "&gt;")
) )
.replace( .replace(
/{contact}/g, /{contact}/g,
@ -360,8 +360,8 @@ function clientErrorHandler(err, socket) {
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") .replace(/>/g, "&gt;")
.replace(/\./g, "[dot]") .replace(/\./g, "[dot]")
.replace(/@/g, "[at]"), .replace(/@/g, "[at]")
), )
); );
} catch (err) { } catch (err) {
let additionalError = 500; let additionalError = 500;
@ -392,7 +392,7 @@ function clientErrorHandler(err, socket) {
http.STATUS_CODES[errorCode] http.STATUS_CODES[errorCode]
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;"), .replace(/>/g, "&gt;")
) )
.replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode]) .replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode])
.replace( .replace(
@ -404,7 +404,7 @@ function clientErrorHandler(err, socket) {
.replace(/\r\n/g, "<br/>") .replace(/\r\n/g, "<br/>")
.replace(/\n/g, "<br/>") .replace(/\n/g, "<br/>")
.replace(/\r/g, "<br/>") .replace(/\r/g, "<br/>")
.replace(/ {2}/g, "&nbsp;&nbsp;"), .replace(/ {2}/g, "&nbsp;&nbsp;")
) )
.replace( .replace(
/{server}/g, /{server}/g,
@ -416,7 +416,7 @@ function clientErrorHandler(err, socket) {
) )
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;"), .replace(/>/g, "&gt;")
) )
.replace( .replace(
/{contact}/g, /{contact}/g,
@ -425,9 +425,9 @@ function clientErrorHandler(err, socket) {
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") .replace(/>/g, "&gt;")
.replace(/\./g, "[dot]") .replace(/\./g, "[dot]")
.replace(/@/g, "[at]"), .replace(/@/g, "[at]")
) )
.replace(/{additionalError}/g, additionalError.toString()), .replace(/{additionalError}/g, additionalError.toString())
); );
res.end(); res.end();
} }
@ -445,7 +445,7 @@ function clientErrorHandler(err, socket) {
config.secure && fromMain config.secure && fromMain
? (typeof config.sport == "number" ? "port " : "socket ") + config.sport ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport
: (typeof config.port == "number" ? "port " : "socket ") + config.port : (typeof config.port == "number" ? "port " : "socket ") + config.port
}...`, }...`
); );
logFacilities.reqmessage( logFacilities.reqmessage(
`Client ${ `Client ${
@ -453,7 +453,7 @@ function clientErrorHandler(err, socket) {
? "[unknown client]" ? "[unknown client]"
: reqip + : reqip +
(reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "") (reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "")
} sent invalid request.`, } sent invalid request.`
); );
try { try {
head = fs.existsSync("./.head") head = fs.existsSync("./.head")
@ -482,7 +482,7 @@ function clientErrorHandler(err, socket) {
return; return;
} else { } else {
logFacilities.errmessage( logFacilities.errmessage(
`An SSL error occured: ${err.code ? err.code : err.message}`, `An SSL error occured: ${err.code ? err.code : err.message}`
); );
callServerError(400); callServerError(400);
return; return;
@ -537,7 +537,7 @@ function clientErrorHandler(err, socket) {
if (String(packetLine1[0]).indexOf(":") > 0) { if (String(packetLine1[0]).indexOf(":") > 0) {
if (!checkHeaders(true)) { if (!checkHeaders(true)) {
logFacilities.errmessage( 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 callServerError(400); // Also malformed Packet
return; return;
@ -568,7 +568,7 @@ function clientErrorHandler(err, socket) {
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
} catch (err) { } catch (err) {
logFacilities.errmessage( logFacilities.errmessage(
"There was an error while determining type of malformed request.", "There was an error while determining type of malformed request."
); );
callServerError(400); callServerError(400);
} }

View file

@ -17,7 +17,7 @@ function noproxyHandler(req, socket, head) {
errmessage: (msg) => serverconsole.errmessage(msg, reqId), errmessage: (msg) => serverconsole.errmessage(msg, reqId),
locerrmessage: (msg) => serverconsole.locerrmessage(msg, reqId), locerrmessage: (msg) => serverconsole.locerrmessage(msg, reqId),
locwarnmessage: (msg) => serverconsole.locwarnmessage(msg, reqId), locwarnmessage: (msg) => serverconsole.locwarnmessage(msg, reqId),
locmessage: (msg) => serverconsole.locmessage(msg, reqId), locmessage: (msg) => serverconsole.locmessage(msg, reqId)
}; };
socket.on("close", (hasError) => { socket.on("close", (hasError) => {
@ -37,7 +37,7 @@ function noproxyHandler(req, socket, head) {
config.secure config.secure
? (typeof config.sport == "number" ? "port " : "socket ") + config.sport ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport
: (typeof config.port == "number" ? "port " : "socket ") + config.port : (typeof config.port == "number" ? "port " : "socket ") + config.port
}...`, }...`
); );
logFacilities.reqmessage( logFacilities.reqmessage(
`Client ${ `Client ${
@ -45,7 +45,7 @@ function noproxyHandler(req, socket, head) {
? "[unknown client]" ? "[unknown client]"
: reqip + : reqip +
(reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "") (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) if (req.headers["user-agent"] != undefined)
logFacilities.reqmessage(`Client uses ${req.headers["user-agent"]}`); logFacilities.reqmessage(`Client uses ${req.headers["user-agent"]}`);

View file

@ -20,7 +20,7 @@ function proxyHandler(req, socket, head) {
errmessage: (msg) => serverconsole.errmessage(msg, reqId), errmessage: (msg) => serverconsole.errmessage(msg, reqId),
locerrmessage: (msg) => serverconsole.locerrmessage(msg, reqId), locerrmessage: (msg) => serverconsole.locerrmessage(msg, reqId),
locwarnmessage: (msg) => serverconsole.locwarnmessage(msg, reqId), locwarnmessage: (msg) => serverconsole.locwarnmessage(msg, reqId),
locmessage: (msg) => serverconsole.locmessage(msg, reqId), locmessage: (msg) => serverconsole.locmessage(msg, reqId)
}; };
socket.on("close", (hasError) => { socket.on("close", (hasError) => {
@ -43,7 +43,7 @@ function proxyHandler(req, socket, head) {
config.secure config.secure
? (typeof config.sport == "number" ? "port " : "socket ") + config.sport ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport
: (typeof config.port == "number" ? "port " : "socket ") + config.port : (typeof config.port == "number" ? "port " : "socket ") + config.port
}...`, }...`
); );
logFacilities.reqmessage( logFacilities.reqmessage(
`Client ${ `Client ${
@ -51,7 +51,7 @@ function proxyHandler(req, socket, head) {
? "[unknown client]" ? "[unknown client]"
: reqip + : reqip +
(reqport && reqport !== 0 && reqport != "" ? ":" + reqport : "") (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) if (req.headers["user-agent"] != undefined)
logFacilities.reqmessage(`Client uses ${req.headers["user-agent"]}`); 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); currentMiddleware.proxy(req, socket, head, logFacilities, config, next);
} catch (err) { } catch (err) {
logFacilities.errmessage( logFacilities.errmessage(
"There was an error while processing the request!", "There was an error while processing the request!"
); );
logFacilities.errmessage("Stack:"); logFacilities.errmessage("Stack:");
logFacilities.errmessage(err.stack); logFacilities.errmessage(err.stack);
@ -78,7 +78,7 @@ function proxyHandler(req, socket, head) {
} }
} else { } else {
logFacilities.errmessage( logFacilities.errmessage(
`${name} doesn't support proxy without proxy mod.`, `${name} doesn't support proxy without proxy mod.`
); );
if (!socket.destroyed) socket.end("HTTP/1.1 501 Not Implemented\n\n"); if (!socket.destroyed) socket.end("HTTP/1.1 501 Not Implemented\n\n");
} }

View file

@ -28,7 +28,7 @@ function requestHandler(req, res) {
errmessage: (msg) => serverconsole.errmessage(msg, reqId), errmessage: (msg) => serverconsole.errmessage(msg, reqId),
locerrmessage: (msg) => serverconsole.locerrmessage(msg, reqId), locerrmessage: (msg) => serverconsole.locerrmessage(msg, reqId),
locwarnmessage: (msg) => serverconsole.locwarnmessage(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) // SVR.JS configuration object (modified)
@ -116,7 +116,7 @@ function requestHandler(req, res) {
req.headers[":method"] == undefined req.headers[":method"] == undefined
) { ) {
let err = new Error( 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 (Buffer.alloc) err.rawPacket = Buffer.alloc(0);
if (req.socket && req.socket.server) if (req.socket && req.socket.server)
@ -156,7 +156,7 @@ function requestHandler(req, res) {
) { ) {
if (headWritten) { if (headWritten) {
process.emitWarning("res.writeHead called multiple times.", { process.emitWarning("res.writeHead called multiple times.", {
code: "WARN_SVRJS_MULTIPLE_WRITEHEAD", code: "WARN_SVRJS_MULTIPLE_WRITEHEAD"
}); });
return res; return res;
} else { } else {
@ -166,11 +166,11 @@ function requestHandler(req, res) {
if (code >= 400 && code <= 499) process.err4xxcounter++; if (code >= 400 && code <= 499) process.err4xxcounter++;
else if (code >= 500 && code <= 599) process.err5xxcounter++; else if (code >= 500 && code <= 599) process.err5xxcounter++;
logFacilities.errmessage( logFacilities.errmessage(
"Server responded with " + code.toString() + " code.", "Server responded with " + code.toString() + " code."
); );
} else { } else {
logFacilities.resmessage( logFacilities.resmessage(
"Server responded with " + code.toString() + " code.", "Server responded with " + code.toString() + " code."
); );
} }
if (typeof codeDescription != "string" && http.STATUS_CODES[code]) { if (typeof codeDescription != "string" && http.STATUS_CODES[code]) {
@ -203,7 +203,7 @@ function requestHandler(req, res) {
config.secure && fromMain config.secure && fromMain
? (typeof config.sport == "number" ? "port " : "socket ") + config.sport ? (typeof config.sport == "number" ? "port " : "socket ") + config.sport
: (typeof config.port == "number" ? "port " : "socket ") + config.port : (typeof config.port == "number" ? "port " : "socket ") + config.port
}...`, }...`
); );
if (req.socket == null) { if (req.socket == null) {
@ -281,13 +281,13 @@ function requestHandler(req, res) {
: req.method == "PATCH" : req.method == "PATCH"
? "to patch content in " ? "to patch content in "
: "to access content using " + req.method + " method in " : "to access content using " + req.method + " method in "
}${req.headers.host == undefined || req.isProxy ? "" : req.headers.host}${req.url}`, }${req.headers.host == undefined || req.isProxy ? "" : req.headers.host}${req.url}`
); );
if (req.headers["user-agent"] != undefined) if (req.headers["user-agent"] != undefined)
logFacilities.reqmessage(`Client uses ${req.headers["user-agent"]}`); logFacilities.reqmessage(`Client uses ${req.headers["user-agent"]}`);
if (oldHostHeader && oldHostHeader != req.headers.host) if (oldHostHeader && oldHostHeader != req.headers.host)
logFacilities.resmessage( logFacilities.resmessage(
`Host name rewritten: ${oldHostHeader} => ${req.headers.host}`, `Host name rewritten: ${oldHostHeader} => ${req.headers.host}`
); );
// Header and footer placeholders // Header and footer placeholders
@ -332,7 +332,7 @@ function requestHandler(req, res) {
stack stack
) { ) {
throw new TypeError( 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) { } catch (err2) {
res.error(500, err2); res.error(500, err2);
} }
}, }
); );
} else { } else {
try { try {
@ -418,7 +418,7 @@ function requestHandler(req, res) {
if (errorCode == 500 || errorCode == 502) { if (errorCode == 500 || errorCode == 502) {
logFacilities.errmessage( logFacilities.errmessage(
"There was an error while processing the request!", "There was an error while processing the request!"
); );
logFacilities.errmessage("Stack:"); logFacilities.errmessage("Stack:");
logFacilities.errmessage(stack); logFacilities.errmessage(stack);
@ -455,7 +455,7 @@ function requestHandler(req, res) {
http.STATUS_CODES[errorCode] http.STATUS_CODES[errorCode]
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;"), .replace(/>/g, "&gt;")
) )
.replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode]) .replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode])
.replace( .replace(
@ -467,14 +467,14 @@ function requestHandler(req, res) {
.replace(/\r\n/g, "<br/>") .replace(/\r\n/g, "<br/>")
.replace(/\n/g, "<br/>") .replace(/\n/g, "<br/>")
.replace(/\r/g, "<br/>") .replace(/\r/g, "<br/>")
.replace(/ {2}/g, "&nbsp;&nbsp;"), .replace(/ {2}/g, "&nbsp;&nbsp;")
) )
.replace( .replace(
/{path}/g, /{path}/g,
req.url req.url
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;"), .replace(/>/g, "&gt;")
) )
.replace( .replace(
/{server}/g, /{server}/g,
@ -494,7 +494,7 @@ function requestHandler(req, res) {
String(req.headers.host) String(req.headers.host)
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;")), .replace(/>/g, "&gt;"))
) )
.replace( .replace(
/{contact}/g, /{contact}/g,
@ -503,8 +503,8 @@ function requestHandler(req, res) {
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") .replace(/>/g, "&gt;")
.replace(/\./g, "[dot]") .replace(/\./g, "[dot]")
.replace(/@/g, "[at]"), .replace(/@/g, "[at]")
), )
); // Replace placeholders in error response ); // Replace placeholders in error response
} catch (err) { } catch (err) {
let additionalError = 500; let additionalError = 500;
@ -537,7 +537,7 @@ function requestHandler(req, res) {
http.STATUS_CODES[errorCode] http.STATUS_CODES[errorCode]
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;"), .replace(/>/g, "&gt;")
) )
.replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode]) .replace(/{errorDesc}/g, serverHTTPErrorDescs[errorCode])
.replace( .replace(
@ -549,14 +549,14 @@ function requestHandler(req, res) {
.replace(/\r\n/g, "<br/>") .replace(/\r\n/g, "<br/>")
.replace(/\n/g, "<br/>") .replace(/\n/g, "<br/>")
.replace(/\r/g, "<br/>") .replace(/\r/g, "<br/>")
.replace(/ {2}/g, "&nbsp;&nbsp;"), .replace(/ {2}/g, "&nbsp;&nbsp;")
) )
.replace( .replace(
/{path}/g, /{path}/g,
req.url req.url
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;"), .replace(/>/g, "&gt;")
) )
.replace( .replace(
/{server}/g, /{server}/g,
@ -576,7 +576,7 @@ function requestHandler(req, res) {
String(req.headers.host) String(req.headers.host)
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;")), .replace(/>/g, "&gt;"))
) )
.replace( .replace(
/{contact}/g, /{contact}/g,
@ -585,9 +585,9 @@ function requestHandler(req, res) {
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") .replace(/>/g, "&gt;")
.replace(/\./g, "[dot]") .replace(/\./g, "[dot]")
.replace(/@/g, "[at]"), .replace(/@/g, "[at]")
) )
.replace(/{additionalError}/g, additionalError.toString()), .replace(/{additionalError}/g, additionalError.toString())
); // Replace placeholders in error response ); // Replace placeholders in error response
res.end(); res.end();
} }
@ -676,7 +676,7 @@ function requestHandler(req, res) {
// CONNECT requests should be handled in "connect" event. // CONNECT requests should be handled in "connect" event.
res.error(501); res.error(501);
logFacilities.errmessage( 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; return;
} }
@ -697,7 +697,7 @@ function requestHandler(req, res) {
? req.headers.host ? req.headers.host
: config.domain : config.domain
? config.domain ? config.domain
: "unknown.invalid"), : "unknown.invalid")
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);

View file

@ -12,15 +12,15 @@ function serverErrorHandler(err, isRedirect, server, start) {
serverconsole.locerrmessage( serverconsole.locerrmessage(
serverErrorDescs[err.code] serverErrorDescs[err.code]
? serverErrorDescs[err.code] ? serverErrorDescs[err.code]
: serverErrorDescs["UNKNOWN"], : serverErrorDescs["UNKNOWN"]
); );
serverconsole.locmessage( serverconsole.locmessage(
`${isRedirect ? attmtsRedir : attmts} attempts left.`, `${isRedirect ? attmtsRedir : attmts} attempts left.`
); );
} else { } else {
try { try {
process.send( process.send(
"\x12ERRLIST" + (isRedirect ? attmtsRedir : attmts) + err.code, "\x12ERRLIST" + (isRedirect ? attmtsRedir : attmts) + err.code
); );
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
} catch (err) { } catch (err) {
@ -59,7 +59,7 @@ process.messageEventListeners.push((worker, serverconsole) => {
serverconsole.locerrmessage( serverconsole.locerrmessage(
serverErrorDescs[errCode] serverErrorDescs[errCode]
? serverErrorDescs[errCode] ? serverErrorDescs[errCode]
: serverErrorDescs["UNKNOWN"], : serverErrorDescs["UNKNOWN"]
); );
serverconsole.locmessage(`${tries} attempts left.`); serverconsole.locmessage(`${tries} attempts left.`);
} }

View file

@ -22,7 +22,7 @@ try {
tar = require("tar"); tar = require("tar");
} catch (err) { } catch (err) {
tar = { tar = {
_errored: err, _errored: err
}; };
} }
@ -57,7 +57,7 @@ try {
}; };
} }
let crypto = { let crypto = {
__disabled__: null, __disabled__: null
}; };
let https = { let https = {
createServer: () => { createServer: () => {
@ -68,7 +68,7 @@ let https = {
}, },
get: () => { get: () => {
throw new Error("Crypto support is not present"); throw new Error("Crypto support is not present");
}, }
}; };
try { try {
crypto = require("crypto"); crypto = require("crypto");
@ -87,7 +87,7 @@ try {
ocspCache = new ocsp.Cache(); ocspCache = new ocsp.Cache();
} catch (err) { } catch (err) {
ocsp = { ocsp = {
_errored: err, _errored: err
}; };
} }
@ -136,12 +136,12 @@ for (
) { ) {
console.log(`${name} usage:`); console.log(`${name} usage:`);
console.log( 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("-h -? /h /? --help -- Displays help");
console.log("--clean -- Cleans up files created by " + name); console.log("--clean -- Cleans up files created by " + name);
console.log( 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("--secure -- Runs HTTPS server");
console.log("--disable-mods -- Disables mods (safe mode)"); console.log("--disable-mods -- Disables mods (safe mode)");
@ -181,12 +181,12 @@ for (
console.log(`Unrecognized argument: ${args[i]}`); console.log(`Unrecognized argument: ${args[i]}`);
console.log(`${name} usage:`); console.log(`${name} usage:`);
console.log( 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("-h -? /h /? --help -- Displays help");
console.log("--clean -- Cleans up files created by " + name); console.log("--clean -- Cleans up files created by " + name);
console.log( 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("--secure -- Runs HTTPS server");
console.log("--disable-mods -- Disables mods (safe mode)"); 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 generateErrorStack = require("./utils/generateErrorStack.js");
const { const {
calculateNetworkIPv4FromCidr, calculateNetworkIPv4FromCidr,
calculateBroadcastIPv4FromCidr, calculateBroadcastIPv4FromCidr
} = require("./utils/ipSubnetUtils.js"); } = require("./utils/ipSubnetUtils.js");
const sendStatistics = require("./utils/sendStatistics.js"); const sendStatistics = require("./utils/sendStatistics.js");
const deepClone = require("./utils/deepClone.js"); const deepClone = require("./utils/deepClone.js");
@ -296,7 +296,7 @@ if (process.serverConfig.dontCompress === undefined)
"/.*\\.(?:jpe?g|png|bmp|tiff|jfif|gif|webp)$/", "/.*\\.(?:jpe?g|png|bmp|tiff|jfif|gif|webp)$/",
"/.*\\.(?:[id]mg|iso|flp)$/", "/.*\\.(?:[id]mg|iso|flp)$/",
"/.*\\.(?:zip|rar|bz2|[gb7x]z|lzma|tar)$/", "/.*\\.(?: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) if (process.serverConfig.enableIPSpoofing === undefined)
process.serverConfig.enableIPSpoofing = false; process.serverConfig.enableIPSpoofing = false;
@ -346,7 +346,7 @@ if (typeof process.serverConfig.port === "string") {
process.serverConfig.port = parseInt(process.serverConfig.port); process.serverConfig.port = parseInt(process.serverConfig.port);
} else { } else {
const portLMatch = process.serverConfig.port.match( const portLMatch = process.serverConfig.port.match(
/^(\[[^ \]@/\\]+\]|[^ \][:@/\\]+):([0-9]+)$/, /^(\[[^ \]@/\\]+\]|[^ \][:@/\\]+):([0-9]+)$/
); );
if (portLMatch) { if (portLMatch) {
listenAddress = portLMatch[1] listenAddress = portLMatch[1]
@ -361,7 +361,7 @@ if (typeof process.serverConfig.sport === "string") {
process.serverConfig.sport = parseInt(process.serverConfig.sport); process.serverConfig.sport = parseInt(process.serverConfig.sport);
} else { } else {
const sportLMatch = process.serverConfig.sport.match( const sportLMatch = process.serverConfig.sport.match(
/^(\[[^ \]@/\\]+\]|[^ \][:@/\\]+):([0-9]+)$/, /^(\[[^ \]@/\\]+\]|[^ \][:@/\\]+):([0-9]+)$/
); );
if (sportLMatch) { if (sportLMatch) {
sListenAddress = sportLMatch[1] sListenAddress = sportLMatch[1]
@ -376,7 +376,7 @@ const serverconsole = require("./utils/serverconsole.js");
function addListenersToWorker(worker) { function addListenersToWorker(worker) {
process.messageEventListeners.forEach((messageEventListener) => process.messageEventListeners.forEach((messageEventListener) =>
worker.on("message", messageEventListener(worker, serverconsole)), worker.on("message", messageEventListener(worker, serverconsole))
); );
} }
@ -404,7 +404,7 @@ try {
process.chdir( process.chdir(
process.serverConfig.wwwroot != undefined process.serverConfig.wwwroot != undefined
? process.serverConfig.wwwroot ? process.serverConfig.wwwroot
: process.dirname, : process.dirname
); );
} catch (err) { } catch (err) {
wwwrootError = err; wwwrootError = err;
@ -531,9 +531,9 @@ if (host != "[offline]" || ifaceEx) {
port: crypto.__disabled__ !== undefined ? 80 : 443, port: crypto.__disabled__ !== undefined ? 80 : 443,
path: "/", path: "/",
headers: { headers: {
"User-Agent": generateServerString(true), "User-Agent": generateServerString(true)
}, },
timeout: 5000, timeout: 5000
}); });
if (crypto.__disabled__ === undefined) { if (crypto.__disabled__ === undefined) {
@ -542,9 +542,9 @@ if (host != "[offline]" || ifaceEx) {
port: 443, port: 443,
path: "/", path: "/",
headers: { headers: {
"User-Agent": generateServerString(true), "User-Agent": generateServerString(true)
}, },
timeout: 5000, timeout: 5000
}); });
} }
} else { } else {
@ -585,7 +585,7 @@ if (process.serverConfig.secure) {
process.serverConfig.key[0] != "/" && process.serverConfig.key[0] != "/" &&
!process.serverConfig.key.match(/^[A-Z0-9]:\\/) !process.serverConfig.key.match(/^[A-Z0-9]:\\/)
? process.dirname + "/" + process.serverConfig.key ? process.dirname + "/" + process.serverConfig.key
: process.serverConfig.key, : process.serverConfig.key
) )
.toString(); .toString();
cert = fs cert = fs
@ -593,7 +593,7 @@ if (process.serverConfig.secure) {
process.serverConfig.cert[0] != "/" && process.serverConfig.cert[0] != "/" &&
!process.serverConfig.cert.match(/^[A-Z0-9]:\\/) !process.serverConfig.cert.match(/^[A-Z0-9]:\\/)
? process.dirname + "/" + process.serverConfig.cert ? process.dirname + "/" + process.serverConfig.cert
: process.serverConfig.cert, : process.serverConfig.cert
) )
.toString(); .toString();
const sniNames = Object.keys(process.serverConfig.sni); 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[0] != "/" &&
!process.serverConfig.sni[sniName].cert.match(/^[A-Z0-9]:\\/) !process.serverConfig.sni[sniName].cert.match(/^[A-Z0-9]:\\/)
? process.dirname + "/" + process.serverConfig.sni[sniName].cert ? process.dirname + "/" + process.serverConfig.sni[sniName].cert
: process.serverConfig.sni[sniName].cert, : process.serverConfig.sni[sniName].cert
) )
.toString(), .toString(),
key: fs key: fs
@ -619,9 +619,9 @@ if (process.serverConfig.secure) {
process.serverConfig.sni[sniName].key[0] != "/" && process.serverConfig.sni[sniName].key[0] != "/" &&
!process.serverConfig.sni[sniName].key.match(/^[A-Z0-9]:\\/) !process.serverConfig.sni[sniName].key.match(/^[A-Z0-9]:\\/)
? process.dirname + "/" + process.serverConfig.sni[sniName].key ? process.dirname + "/" + process.serverConfig.sni[sniName].key
: process.serverConfig.sni[sniName].key, : process.serverConfig.sni[sniName].key
) )
.toString(), .toString()
}); });
}); });
} catch (err) { } catch (err) {
@ -662,13 +662,13 @@ if (!disableMods) {
else { else {
modInfos.push({ modInfos.push({
name: `Unknown mod (${modFileRaw}; module.exports.modInfo not set)`, name: `Unknown mod (${modFileRaw}; module.exports.modInfo not set)`,
version: "ERROR", version: "ERROR"
}); });
} }
} catch (err) { } catch (err) {
modLoadingErrors.push({ modLoadingErrors.push({
error: err, error: err,
modName: modFileRaw, modName: modFileRaw
}); });
} }
} else { } else {
@ -692,7 +692,7 @@ if (!disableMods) {
fs.mkdirSync(process.dirname + "/temp"); fs.mkdirSync(process.dirname + "/temp");
try { try {
fs.mkdirSync( fs.mkdirSync(
process.dirname + "/temp/" + modloaderFolderName, process.dirname + "/temp/" + modloaderFolderName
); );
} catch (err) { } catch (err) {
// If there was another error, throw it // If there was another error, throw it
@ -707,7 +707,7 @@ if (!disableMods) {
"/temp/" + "/temp/" +
modloaderFolderName + modloaderFolderName +
"/" + "/" +
modFileRaw, modFileRaw
); );
} catch (err) { } catch (err) {
// If there was an error creating the folder, ignore it if it's a known error // If there was an error creating the folder, ignore it if it's a known error
@ -727,7 +727,7 @@ if (!disableMods) {
"/temp/" + "/temp/" +
modloaderFolderName + modloaderFolderName +
"/" + "/" +
modFileRaw, modFileRaw
}); });
} else { } else {
// If it's not a ".tar.gz" file, throw an error about `svrmodpack` support being dropped // If it's not a ".tar.gz" file, throw an error about `svrmodpack` support being dropped
@ -736,7 +736,7 @@ if (!disableMods) {
name + name +
' no longer supports "svrmodpack" library for ' + ' no longer supports "svrmodpack" library for ' +
name + 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 + modloaderFolderName +
"/" + "/" +
modFileRaw + modFileRaw +
"/index.js", "/index.js"
), )
), )
); );
// Read the mod's info file // Read the mod's info file
@ -764,21 +764,21 @@ if (!disableMods) {
modloaderFolderName + modloaderFolderName +
"/" + "/" +
modFileRaw + modFileRaw +
"/mod.info", "/mod.info"
), )
), )
); );
} catch (err) { } catch (err) {
// If failed to read info file, add a placeholder entry to modInfos with an error message // If failed to read info file, add a placeholder entry to modInfos with an error message
modInfos.push({ modInfos.push({
name: `Unknown mod (${modFileRaw}; ${err.message})`, name: `Unknown mod (${modFileRaw}; ${err.message})`,
version: "ERROR", version: "ERROR"
}); });
} }
} catch (err) { } catch (err) {
modLoadingErrors.push({ modLoadingErrors.push({
error: err, error: err,
modName: modFileRaw, modName: modFileRaw
}); });
} }
} }
@ -823,14 +823,14 @@ if (!disableMods) {
// Write the modified server side script to the temp folder // Write the modified server side script to the temp folder
fs.writeFileSync( fs.writeFileSync(
process.dirname + "/temp/" + tempServerSideScriptName, process.dirname + "/temp/" + tempServerSideScriptName,
modhead + fs.readFileSync(SSJSPath) + modfoot, modhead + fs.readFileSync(SSJSPath) + modfoot
); );
// Add the server side script to the mods list // Add the server side script to the mods list
mods.push( mods.push(
legacyModWrapper( legacyModWrapper(
require(process.dirname + "/temp/" + tempServerSideScriptName), require(process.dirname + "/temp/" + tempServerSideScriptName)
), )
); );
} catch (err) { } catch (err) {
SSJSError = err; SSJSError = err;
@ -852,28 +852,28 @@ let middleware = [
...mods, // Load SVR.JS mods as middleware ...mods, // Load SVR.JS mods as middleware
require("./middleware/defaultHandlerChecks.js"), require("./middleware/defaultHandlerChecks.js"),
require("./middleware/status.js"), require("./middleware/status.js"),
require("./middleware/staticFileServingAndDirectoryListings.js"), require("./middleware/staticFileServingAndDirectoryListings.js")
]; ];
// HTTP server handlers // HTTP server handlers
const requestHandler = require("./handlers/requestHandler.js")( const requestHandler = require("./handlers/requestHandler.js")(
serverconsole, serverconsole,
middleware, middleware
); );
const proxyHandler = require("./handlers/proxyHandler.js")( const proxyHandler = require("./handlers/proxyHandler.js")(
serverconsole, serverconsole,
middleware, middleware
); );
const noproxyHandler = require("./handlers/noproxyHandler.js")(serverconsole); const noproxyHandler = require("./handlers/noproxyHandler.js")(serverconsole);
const clientErrorHandler = require("./handlers/clientErrorHandler.js")( const clientErrorHandler = require("./handlers/clientErrorHandler.js")(
serverconsole, serverconsole
); );
const serverErrorHandler = require("./handlers/serverErrorHandler.js")( const serverErrorHandler = require("./handlers/serverErrorHandler.js")(
serverconsole, serverconsole
); );
let messageTransmitted = false; let messageTransmitted = false;
@ -916,7 +916,7 @@ function listeningMessage() {
process.serverConfig.sport == 443 process.serverConfig.sport == 443
? "" ? ""
: ":" + process.serverConfig.sport : ":" + process.serverConfig.sport
}`, }`
); );
} else { } else {
serverconsole.locmessage("* " + process.serverConfig.sport); // Unix socket or Windows named pipe serverconsole.locmessage("* " + process.serverConfig.sport); // Unix socket or Windows named pipe
@ -933,7 +933,7 @@ function listeningMessage() {
serverconsole.locmessage( serverconsole.locmessage(
`* http://localhost${ `* http://localhost${
process.serverConfig.port == 80 ? "" : ":" + process.serverConfig.port process.serverConfig.port == 80 ? "" : ":" + process.serverConfig.port
}`, }`
); );
} else { } else {
serverconsole.locmessage("* " + process.serverConfig.port); // Unix socket or Windows named pipe serverconsole.locmessage("* " + process.serverConfig.port); // Unix socket or Windows named pipe
@ -950,7 +950,7 @@ function listeningMessage() {
process.serverConfig.sport == 443 process.serverConfig.sport == 443
? "" ? ""
: ":" + process.serverConfig.sport : ":" + process.serverConfig.sport
}`, }`
); );
if ( if (
!( !(
@ -964,7 +964,7 @@ function listeningMessage() {
serverconsole.locmessage( serverconsole.locmessage(
`* http://${accHost.indexOf(":") > -1 ? "[" + accHost + "]" : accHost}${ `* http://${accHost.indexOf(":") > -1 ? "[" + accHost + "]" : accHost}${
process.serverConfig.port == 80 ? "" : ":" + process.serverConfig.port process.serverConfig.port == 80 ? "" : ":" + process.serverConfig.port
}`, }`
); );
ipStatusCallback(() => { ipStatusCallback(() => {
if (pubip != "") { if (pubip != "") {
@ -974,7 +974,7 @@ function listeningMessage() {
process.serverConfig.spubport == 443 process.serverConfig.spubport == 443
? "" ? ""
: ":" + process.serverConfig.spubport : ":" + process.serverConfig.spubport
}`, }`
); );
if ( if (
!( !(
@ -988,7 +988,7 @@ function listeningMessage() {
process.serverConfig.pubport == 80 process.serverConfig.pubport == 80
? "" ? ""
: ":" + process.serverConfig.pubport : ":" + process.serverConfig.pubport
}`, }`
); );
} }
if (domain != "") { if (domain != "") {
@ -998,7 +998,7 @@ function listeningMessage() {
process.serverConfig.spubport == 443 process.serverConfig.spubport == 443
? "" ? ""
: ":" + process.serverConfig.spubport : ":" + process.serverConfig.spubport
}`, }`
); );
if ( if (
!( !(
@ -1012,7 +1012,7 @@ function listeningMessage() {
process.serverConfig.pubport == 80 process.serverConfig.pubport == 80
? "" ? ""
: ":" + process.serverConfig.pubport : ":" + process.serverConfig.pubport
}`, }`
); );
} }
serverconsole.locmessage('For CLI help, you can type "help"'); serverconsole.locmessage('For CLI help, you can type "help"');
@ -1021,13 +1021,13 @@ function listeningMessage() {
if (!process.serverConfig.optOutOfStatisticsServer) { if (!process.serverConfig.optOutOfStatisticsServer) {
if (crypto.__disabled__ !== undefined) { if (crypto.__disabled__ !== undefined) {
serverconsole.locwarnmessage( 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 { } else {
sendStatistics(modInfos, (err) => { sendStatistics(modInfos, (err) => {
if (err) if (err)
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
`There was a problem, when sending data to statistics server! Reason: ${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 // Create secondary HTTP server
try { try {
server2 = http.createServer({ server2 = http.createServer({
requireHostHeader: false, requireHostHeader: false
}); });
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
} catch (err) { } catch (err) {
@ -1057,7 +1057,7 @@ server2.on("checkExpectation", requestHandler);
server2.on("clientError", clientErrorHandler); server2.on("clientError", clientErrorHandler);
server2.on( server2.on(
"connect", "connect",
process.serverConfig.disableToHTTPSRedirect ? proxyHandler : noproxyHandler, process.serverConfig.disableToHTTPSRedirect ? proxyHandler : noproxyHandler
); );
server2.on("error", (err) => { server2.on("error", (err) => {
serverErrorHandler(err, true, server2, start); serverErrorHandler(err, true, server2, start);
@ -1083,13 +1083,13 @@ if (process.serverConfig.enableHTTP2 == true) {
minVersion: process.serverConfig.tlsMinVersion, minVersion: process.serverConfig.tlsMinVersion,
maxVersion: process.serverConfig.tlsMaxVersion, maxVersion: process.serverConfig.tlsMaxVersion,
sigalgs: process.serverConfig.signatureAlgorithms, sigalgs: process.serverConfig.signatureAlgorithms,
settings: process.serverConfig.http2Settings, settings: process.serverConfig.http2Settings
}); });
} else { } else {
server = http2.createServer({ server = http2.createServer({
allowHTTP1: true, allowHTTP1: true,
requireHostHeader: false, requireHostHeader: false,
settings: process.serverConfig.http2Settings, settings: process.serverConfig.http2Settings
}); });
} }
} else { } else {
@ -1105,12 +1105,12 @@ if (process.serverConfig.enableHTTP2 == true) {
ecdhCurve: process.serverConfig.ecdhCurve, ecdhCurve: process.serverConfig.ecdhCurve,
minVersion: process.serverConfig.tlsMinVersion, minVersion: process.serverConfig.tlsMinVersion,
maxVersion: process.serverConfig.tlsMaxVersion, maxVersion: process.serverConfig.tlsMaxVersion,
sigalgs: process.serverConfig.signatureAlgorithms, sigalgs: process.serverConfig.signatureAlgorithms
}); });
} else { } else {
try { try {
server = http.createServer({ server = http.createServer({
requireHostHeader: false, requireHostHeader: false
}); });
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
} catch (err) { } catch (err) {
@ -1125,11 +1125,11 @@ if (process.serverConfig.secure) {
sniCredentials.forEach((sniCredentialsSingle) => { sniCredentials.forEach((sniCredentialsSingle) => {
server.addContext(sniCredentialsSingle.name, { server.addContext(sniCredentialsSingle.name, {
cert: sniCredentialsSingle.cert, cert: sniCredentialsSingle.cert,
key: sniCredentialsSingle.key, key: sniCredentialsSingle.key
}); });
try { try {
let snMatches = sniCredentialsSingle.name.match( let snMatches = sniCredentialsSingle.name.match(
/^([^:[]*|\[[^]]*\]?)((?::.*)?)$/, /^([^:[]*|\[[^]]*\]?)((?::.*)?)$/
); );
if (!snMatches[1][0].match(/^\.+$/)) if (!snMatches[1][0].match(/^\.+$/))
snMatches[1][0] = snMatches[1][0].replace(/\.+$/, ""); snMatches[1][0] = snMatches[1][0].replace(/\.+$/, "");
@ -1140,7 +1140,7 @@ if (process.serverConfig.secure) {
.replace(/\*/g, "[^.:]*") + .replace(/\*/g, "[^.:]*") +
(snMatches[1][0] == "[" || (snMatches[1][0] == "[" ||
snMatches[1].match( 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, "\\$1")
.replace(/\*/g, "[^.]*") + .replace(/\*/g, "[^.]*") +
"$", "$",
"i", "i"
); );
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
} catch (err) { } catch (err) {
@ -1238,7 +1238,7 @@ if (process.serverConfig.secure) {
const req = ocsp.request.generate(cert, issuer); const req = ocsp.request.generate(cert, issuer);
const options = { const options = {
url: uri, url: uri,
ocsp: req.data, ocsp: req.data
}; };
ocspCache.request(req.id, options, callback); ocspCache.request(req.id, options, callback);
@ -1276,13 +1276,13 @@ let commands = {
process.serverConfig.secure process.serverConfig.secure
? process.serverConfig.sport ? process.serverConfig.sport
: process.serverConfig.port, : process.serverConfig.port,
process.serverConfig.secure ? sListenAddress : listenAddress, process.serverConfig.secure ? sListenAddress : listenAddress
); );
} else { } else {
server.listen( server.listen(
process.serverConfig.secure process.serverConfig.secure
? process.serverConfig.sport ? process.serverConfig.sport
: process.serverConfig.port, : process.serverConfig.port
); );
} }
if ( if (
@ -1378,7 +1378,7 @@ let commands = {
if (cluster.isPrimary === undefined) if (cluster.isPrimary === undefined)
log(`This command is not supported on single-threaded ${name}.`); log(`This command is not supported on single-threaded ${name}.`);
else log(`This command need to be run in ${name} master.`); else log(`This command need to be run in ${name} master.`);
}, }
}; };
// Load commands from middleware // Load commands from middleware
@ -1407,7 +1407,7 @@ function SVRJSFork() {
// Log // Log
if (SVRJSInitialized) if (SVRJSInitialized)
serverconsole.locmessage( serverconsole.locmessage(
"Starting next thread, because previous one hung up/crashed...", "Starting next thread, because previous one hung up/crashed..."
); );
// Fork new worker // Fork new worker
let newWorker = {}; let newWorker = {};
@ -1421,7 +1421,7 @@ function SVRJSFork() {
) { ) {
threadLimitWarned = true; threadLimitWarned = true;
serverconsole.locwarnmessage( 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 ( if (
@ -1437,7 +1437,7 @@ function SVRJSFork() {
} else { } else {
if (SVRJSInitialized) if (SVRJSInitialized)
serverconsole.locwarnmessage( 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) { } catch (err) {
@ -1453,7 +1453,7 @@ function SVRJSFork() {
) { ) {
threadLimitWarned = true; threadLimitWarned = true;
serverconsole.locwarnmessage( 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 ( if (
@ -1469,7 +1469,7 @@ function SVRJSFork() {
} else { } else {
if (SVRJSInitialized) if (SVRJSInitialized)
serverconsole.locwarnmessage( 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 { } else {
@ -1482,7 +1482,7 @@ function SVRJSFork() {
newWorker.on("error", (err) => { newWorker.on("error", (err) => {
if (!exiting) if (!exiting)
serverconsole.locwarnmessage( 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", () => { newWorker.on("exit", () => {
@ -1522,7 +1522,7 @@ function forkWorkers(workersToFork, callback) {
if (i >= workersToFork - 1) callback(); if (i >= workersToFork - 1) callback();
}; };
})(i), })(i),
i * 6.6, i * 6.6
); );
} }
} }
@ -1545,7 +1545,7 @@ function msgListener(message) {
if (message == "\x12END") { if (message == "\x12END") {
for (let i = 0; i < Object.keys(cluster.workers).length; i++) { for (let i = 0; i < Object.keys(cluster.workers).length; i++) {
cluster.workers[Object.keys(cluster.workers)[i]].removeAllListeners( cluster.workers[Object.keys(cluster.workers)[i]].removeAllListeners(
"message", "message"
); );
addListenersToWorker(cluster.workers[Object.keys(cluster.workers)[i]]); addListenersToWorker(cluster.workers[Object.keys(cluster.workers)[i]]);
} }
@ -1564,7 +1564,7 @@ function msgListener(message) {
serverconsole.locmessage("Configuration saved."); serverconsole.locmessage("Configuration saved.");
} else if (message.indexOf("\x12SAVEERR") == 0) { } else if (message.indexOf("\x12SAVEERR") == 0) {
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
`There was a problem while saving configuration file. Reason: ${message.substring(8)}`, `There was a problem while saving configuration file. Reason: ${message.substring(8)}`
); );
} else if (message[0] == "\x12") { } else if (message[0] == "\x12") {
// Discard unrecognized control messages // Discard unrecognized control messages
@ -1580,7 +1580,7 @@ function saveConfig() {
let configJSONobj = {}; let configJSONobj = {};
if (fs.existsSync(process.dirname + "/config.json")) if (fs.existsSync(process.dirname + "/config.json"))
configJSONobj = JSON.parse( configJSONobj = JSON.parse(
fs.readFileSync(process.dirname + "/config.json").toString(), fs.readFileSync(process.dirname + "/config.json").toString()
); );
if (configJSONobj.users === undefined) configJSONobj.users = []; if (configJSONobj.users === undefined) configJSONobj.users = [];
if (process.serverConfig.secure) { if (process.serverConfig.secure) {
@ -1638,7 +1638,7 @@ function saveConfig() {
"/.*\\.(?:jpe?g|png|bmp|tiff|jfif|gif|webp)$/", "/.*\\.(?:jpe?g|png|bmp|tiff|jfif|gif|webp)$/",
"/.*\\.(?:[id]mg|iso|flp)$/", "/.*\\.(?:[id]mg|iso|flp)$/",
"/.*\\.(?:zip|rar|bz2|[gb7x]z|lzma|tar)$/", "/.*\\.(?: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) if (configJSONobj.enableIPSpoofing === undefined)
configJSONobj.enableIPSpoofing = false; configJSONobj.enableIPSpoofing = false;
@ -1669,7 +1669,7 @@ function saveConfig() {
fs.writeFileSync( fs.writeFileSync(
process.dirname + "/config.json", process.dirname + "/config.json",
JSON.stringify(configJSONobj, null, 2) + "\n", JSON.stringify(configJSONobj, null, 2) + "\n"
); );
break; break;
} catch (err) { } catch (err) {
@ -1688,69 +1688,69 @@ function start(init) {
for (let i = 0; i < logo.length; i++) console.log(logo[i]); // Print logo for (let i = 0; i < logo.length; i++) console.log(logo[i]); // Print logo
console.log(); console.log();
console.log( console.log(
`Welcome to \x1b[1m${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 // Print warnings
if (version.indexOf("Nightly-") === 0) if (version.indexOf("Nightly-") === 0)
serverconsole.locwarnmessage( 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) if (process.serverConfig.enableHTTP2 && !process.serverConfig.secure)
serverconsole.locwarnmessage( 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) { if (process.isBun) {
serverconsole.locwarnmessage( 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 ( if (
process.isBun && process.isBun &&
!( !(
process.versions.bun && process.versions.bun &&
!process.versions.bun.match( !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) process.serverConfig.users.some((entry) => entry.pbkdf2)
) )
serverconsole.locwarnmessage( 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) if (cluster.isPrimary === undefined)
serverconsole.locwarnmessage( 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) if (crypto.__disabled__ !== undefined)
serverconsole.locwarnmessage( 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) if (crypto.__disabled__ === undefined && !crypto.scrypt)
serverconsole.locwarnmessage( 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 ( if (
!process.isBun && !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( /^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( 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 ( if (
!process.isBun && !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( /^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( 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) if (process.getuid && process.getuid() == 0)
serverconsole.locwarnmessage( 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 ( if (
!process.isBun && !process.isBun &&
@ -1761,11 +1761,11 @@ function start(init) {
) { ) {
if (new Date() > new Date("11 September 2023")) { if (new Date() > new Date("11 September 2023")) {
serverconsole.locwarnmessage( 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 { } else {
serverconsole.locwarnmessage( 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 ocsp._errored
) )
serverconsole.locwarnmessage( 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) if (disableMods)
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
`${name} is running without mods and server-side JavaScript enabled. Web applications may not work as expected`, `${name} is running without mods and server-side JavaScript enabled. Web applications may not work as expected`
); );
if (process.serverConfig.optOutOfStatisticsServer) if (process.serverConfig.optOutOfStatisticsServer)
serverconsole.locmessage( serverconsole.locmessage(
`${name} is configured to opt out of sending data to the statistics server.`, `${name} is configured to opt out of sending data to the statistics server.`
); );
console.log(); console.log();
@ -1791,16 +1791,16 @@ function start(init) {
if (process.isPrimary || process.isPrimary === undefined) { if (process.isPrimary || process.isPrimary === undefined) {
modLoadingErrors.forEach((modLoadingError) => { modLoadingErrors.forEach((modLoadingError) => {
serverconsole.locwarnmessage( 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("Stack:");
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
generateErrorStack(modLoadingError.error), generateErrorStack(modLoadingError.error)
); );
}); });
if (SSJSError) { if (SSJSError) {
serverconsole.locwarnmessage( 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("Stack:");
serverconsole.locwarnmessage(generateErrorStack(SSJSError)); serverconsole.locwarnmessage(generateErrorStack(SSJSError));
@ -1816,21 +1816,21 @@ function start(init) {
const CPUs = os.cpus(); const CPUs = os.cpus();
if (CPUs.length > 0) if (CPUs.length > 0)
serverconsole.locmessage( serverconsole.locmessage(
`CPU: ${CPUs.length > 1 ? CPUs.length + "x " : ""}${CPUs[0].model}`, `CPU: ${CPUs.length > 1 ? CPUs.length + "x " : ""}${CPUs[0].model}`
); );
// Throw errors // Throw errors
if (vnum < 64) if (vnum < 64)
throw new Error( throw new Error(
`${name} requires Node.JS 10.0.0 and newer, but your Node.JS version isn't supported by ${name}.`, `${name} requires Node.JS 10.0.0 and newer, but your Node.JS version isn't supported by ${name}.`
); );
if (configJSONRErr) if (configJSONRErr)
throw new Error( throw new Error(
`Can't read ${name} configuration file: ${configJSONRErr.message}`, `Can't read ${name} configuration file: ${configJSONRErr.message}`
); );
if (configJSONPErr) if (configJSONPErr)
throw new Error( throw new Error(
`${name} configuration parse error: ${configJSONPErr.message}`, `${name} configuration parse error: ${configJSONPErr.message}`
); );
if ( if (
process.serverConfig.enableHTTP2 && process.serverConfig.enableHTTP2 &&
@ -1838,20 +1838,20 @@ function start(init) {
typeof process.serverConfig.port != "number" typeof process.serverConfig.port != "number"
) )
throw new Error( throw new Error(
`HTTP/2 without HTTPS, along with Unix sockets/Windows named pipes aren't supported by ${name}.`, `HTTP/2 without HTTPS, along with Unix sockets/Windows named pipes aren't supported by ${name}.`
); );
if (process.serverConfig.enableHTTP2 && http2.__disabled__ !== undefined) if (process.serverConfig.enableHTTP2 && http2.__disabled__ !== undefined)
throw new Error( throw new Error(
`HTTP/2 isn't supported by your Node.JS version! You may not be able to use HTTP/2 with ${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) {
if (listenAddress.match(/^[0-9]+$/)) if (listenAddress.match(/^[0-9]+$/))
throw new Error( 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 ( if (
listenAddress.match( 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.`); throw new Error(`${name} can't listen on multicast address.`);
@ -1862,15 +1862,15 @@ function start(init) {
} }
if (certificateError) if (certificateError)
throw new Error( 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) if (wwwrootError)
throw new Error( throw new Error(
`There was a problem with your web root: ${wwwrootError.message}`, `There was a problem with your web root: ${wwwrootError.message}`
); );
if (sniReDos) if (sniReDos)
throw new Error( throw new Error(
"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) + ":" : listenAddress) + ":"
: "port " : "port "
: "" : ""
}${process.serverConfig.port.toString()}...`, }${process.serverConfig.port.toString()}...`
); );
if (process.serverConfig.secure) if (process.serverConfig.secure)
serverconsole.locmessage( serverconsole.locmessage(
@ -1902,7 +1902,7 @@ function start(init) {
: sListenAddress) + ":" : sListenAddress) + ":"
: "port " : "port "
: "" : ""
}${process.serverConfig.sport.toString()}...`, }${process.serverConfig.sport.toString()}...`
); );
} }
@ -1918,13 +1918,13 @@ function start(init) {
process.serverConfig.secure process.serverConfig.secure
? process.serverConfig.sport ? process.serverConfig.sport
: process.serverConfig.port, : process.serverConfig.port,
process.serverConfig.secure ? sListenAddress : listenAddress, process.serverConfig.secure ? sListenAddress : listenAddress
); );
} else { } else {
server.listen( server.listen(
process.serverConfig.secure process.serverConfig.secure
? process.serverConfig.sport ? process.serverConfig.sport
: process.serverConfig.port, : process.serverConfig.port
); );
} }
} catch (err) { } catch (err) {
@ -2008,7 +2008,7 @@ function start(init) {
addListenersToWorker(cluster.workers[goodWorkers[wN]]); addListenersToWorker(cluster.workers[goodWorkers[wN]]);
} }
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
`There was a problem while saving configuration file. Reason: ${err.message}`, `There was a problem while saving configuration file. Reason: ${err.message}`
); );
} }
}); });
@ -2071,7 +2071,7 @@ function start(init) {
const rla = readline.createInterface({ const rla = readline.createInterface({
input: process.stdin, input: process.stdin,
output: process.stdout, output: process.stdout,
prompt: "", prompt: ""
}); });
rla.prompt(); rla.prompt();
rla.on("line", (line) => { rla.on("line", (line) => {
@ -2100,7 +2100,7 @@ function start(init) {
} }
if (stopError) if (stopError)
serverconsole.climessage( serverconsole.climessage(
`Some ${name} workers might not be stopped.`, `Some ${name} workers might not be stopped.`
); );
SVRJSInitialized = false; SVRJSInitialized = false;
closedMaster = true; closedMaster = true;
@ -2185,10 +2185,10 @@ function start(init) {
: process.serverConfig.sport, : process.serverConfig.sport,
headers: { headers: {
"X-SVR-JS-From-Main-Thread": "true", "X-SVR-JS-From-Main-Thread": "true",
"User-Agent": generateServerString(true), "User-Agent": generateServerString(true)
}, },
timeout: 1620, timeout: 1620,
rejectUnauthorized: false, rejectUnauthorized: false
}, },
(res) => { (res) => {
chksocket.removeAllListeners("timeout"); chksocket.removeAllListeners("timeout");
@ -2196,7 +2196,7 @@ function start(init) {
res.on("data", () => {}); res.on("data", () => {});
res.on("end", () => {}); res.on("end", () => {});
crashed = false; crashed = false;
}, }
) )
.on("error", () => { .on("error", () => {
if (!exiting) { if (!exiting) {
@ -2224,10 +2224,7 @@ function start(init) {
address = "[" + address + "]"; address = "[" + address + "]";
} }
const connection = http2.connect( const connection = http2.connect(
"http://" + "http://" + address + ":" + process.serverConfig.port.toString()
address +
":" +
process.serverConfig.port.toString(),
); );
connection.on("error", () => { connection.on("error", () => {
if (!exiting) { if (!exiting) {
@ -2242,7 +2239,7 @@ function start(init) {
chksocket = connection.request({ chksocket = connection.request({
":path": "/", ":path": "/",
"x-svr-js-from-main-thread": "true", "x-svr-js-from-main-thread": "true",
"user-agent": generateServerString(true), "user-agent": generateServerString(true)
}); });
chksocket.on("response", () => { chksocket.on("response", () => {
connection.close(); connection.close();
@ -2273,9 +2270,9 @@ function start(init) {
: process.serverConfig.port, : process.serverConfig.port,
headers: { headers: {
"X-SVR-JS-From-Main-Thread": "true", "X-SVR-JS-From-Main-Thread": "true",
"User-Agent": generateServerString(true), "User-Agent": generateServerString(true)
}, },
timeout: 1620, timeout: 1620
}, },
(res) => { (res) => {
chksocket.removeAllListeners("timeout"); chksocket.removeAllListeners("timeout");
@ -2283,7 +2280,7 @@ function start(init) {
res.on("data", () => {}); res.on("data", () => {});
res.on("end", () => {}); res.on("end", () => {});
crashed = false; crashed = false;
}, }
) )
.on("error", () => { .on("error", () => {
if (!exiting) { if (!exiting) {
@ -2327,7 +2324,7 @@ function start(init) {
isWorkerHungUpBuff = true; isWorkerHungUpBuff = true;
cluster.workers[allWorkers[_id]].on( cluster.workers[allWorkers[_id]].on(
"message", "message",
msgListener, msgListener
); );
cluster.workers[allWorkers[_id]].send("\x14KILLPING"); cluster.workers[allWorkers[_id]].send("\x14KILLPING");
setTimeout(() => { setTimeout(() => {
@ -2345,7 +2342,7 @@ function start(init) {
} catch (err) { } catch (err) {
if (cluster.workers[allWorkers[_id]]) { if (cluster.workers[allWorkers[_id]]) {
cluster.workers[allWorkers[_id]].removeAllListeners( cluster.workers[allWorkers[_id]].removeAllListeners(
"message", "message"
); );
addListenersToWorker(cluster.workers[allWorkers[_id]]); addListenersToWorker(cluster.workers[allWorkers[_id]]);
} }
@ -2361,19 +2358,19 @@ function start(init) {
isWorkerHungUpBuff = true; isWorkerHungUpBuff = true;
cluster.workers[goodWorkers[wN]].on( cluster.workers[goodWorkers[wN]].on(
"message", "message",
msgListener, msgListener
); );
cluster.workers[goodWorkers[wN]].send("\x14KILLREQ"); cluster.workers[goodWorkers[wN]].send("\x14KILLREQ");
} }
} catch (err) { } catch (err) {
if (cluster.workers[goodWorkers[wN]]) { if (cluster.workers[goodWorkers[wN]]) {
cluster.workers[goodWorkers[wN]].removeAllListeners( cluster.workers[goodWorkers[wN]].removeAllListeners(
"message", "message"
); );
addListenersToWorker(cluster.workers[goodWorkers[wN]]); addListenersToWorker(cluster.workers[goodWorkers[wN]]);
} }
serverconsole.locwarnmessage( 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(`${name} main process just crashed!!!`);
serverconsole.locerrmessage("Stack:"); serverconsole.locerrmessage("Stack:");
serverconsole.locerrmessage( serverconsole.locerrmessage(
err.stack ? generateErrorStack(err) : String(err), err.stack ? generateErrorStack(err) : String(err)
); );
process.exit(err.errno !== undefined ? err.errno : 1); process.exit(err.errno !== undefined ? err.errno : 1);
} }
@ -2409,7 +2406,7 @@ if (cluster.isPrimary || cluster.isPrimary === undefined) {
} }
} catch (err) { } catch (err) {
serverconsole.locwarnmessage( 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 { try {
@ -2432,7 +2429,7 @@ if (cluster.isPrimary || cluster.isPrimary === undefined) {
try { try {
fs.writeFileSync( fs.writeFileSync(
process.dirname + "/temp/serverSideScript.js", 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 // eslint-disable-next-line no-unused-vars
} catch (err) { } catch (err) {
@ -2472,7 +2469,7 @@ if (cluster.isPrimary || cluster.isPrimary === undefined) {
serverconsole.locerrmessage(`${name} worker just crashed!!!`); serverconsole.locerrmessage(`${name} worker just crashed!!!`);
serverconsole.locerrmessage("Stack:"); serverconsole.locerrmessage("Stack:");
serverconsole.locerrmessage( serverconsole.locerrmessage(
err.stack ? generateErrorStack(err) : String(err), err.stack ? generateErrorStack(err) : String(err)
); );
process.exit(err.errno !== undefined ? err.errno : 1); process.exit(err.errno !== undefined ? err.errno : 1);
} }

View file

@ -7,7 +7,7 @@ module.exports = (req, res, logFacilities, config, next) => {
blocklist.check( blocklist.check(
req.socket.realRemoteAddress req.socket.realRemoteAddress
? req.socket.realRemoteAddress ? req.socket.realRemoteAddress
: req.socket.remoteAddress, : req.socket.remoteAddress
) )
) { ) {
// Invoke 403 Forbidden error // Invoke 403 Forbidden error
@ -50,7 +50,7 @@ module.exports.commands = {
if (!cluster.isPrimary === false) log("IPs successfully unblocked."); if (!cluster.isPrimary === false) log("IPs successfully unblocked.");
passCommand(ip, log); passCommand(ip, log);
} }
}, }
}; };
module.exports.proxySafe = true; module.exports.proxySafe = true;

View file

@ -4,7 +4,7 @@ const {
getInitializePath, getInitializePath,
isForbiddenPath, isForbiddenPath,
isIndexOfForbiddenPath, isIndexOfForbiddenPath,
forbiddenPaths, forbiddenPaths
} = require("../utils/forbiddenPaths.js"); } = require("../utils/forbiddenPaths.js");
const svrjsInfo = require("../../svrjs.json"); const svrjsInfo = require("../../svrjs.json");
const { name } = svrjsInfo; const { name } = svrjsInfo;
@ -13,15 +13,15 @@ forbiddenPaths.config = getInitializePath("./config.json");
forbiddenPaths.certificates = []; forbiddenPaths.certificates = [];
if (process.serverConfig.secure) { if (process.serverConfig.secure) {
forbiddenPaths.certificates.push( forbiddenPaths.certificates.push(
getInitializePath(process.serverConfig.cert), getInitializePath(process.serverConfig.cert)
); );
forbiddenPaths.certificates.push(getInitializePath(process.serverConfig.key)); forbiddenPaths.certificates.push(getInitializePath(process.serverConfig.key));
Object.keys(process.serverConfig.sni).forEach((sniHostname) => { Object.keys(process.serverConfig.sni).forEach((sniHostname) => {
forbiddenPaths.certificates.push( forbiddenPaths.certificates.push(
getInitializePath(process.serverConfig.sni[sniHostname].cert), getInitializePath(process.serverConfig.sni[sniHostname].cert)
); );
forbiddenPaths.certificates.push( 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.dirname[process.dirname.length - 1] != "/"
? process.filename.replace(process.dirname + "/", "") ? process.filename.replace(process.dirname + "/", "")
: process.filename.replace(process.dirname, "")), : process.filename.replace(process.dirname, ""))
); );
forbiddenPaths.serverSideScripts = []; forbiddenPaths.serverSideScripts = [];
if (process.serverConfig.useWebRootServerSideScript) { if (process.serverConfig.useWebRootServerSideScript) {
forbiddenPaths.serverSideScripts.push("/serverSideScript.js"); forbiddenPaths.serverSideScripts.push("/serverSideScript.js");
} else { } else {
forbiddenPaths.serverSideScripts.push( forbiddenPaths.serverSideScripts.push(
getInitializePath("./serverSideScript.js"), getInitializePath("./serverSideScript.js")
); );
} }
forbiddenPaths.serverSideScriptDirectories = []; forbiddenPaths.serverSideScriptDirectories = [];
forbiddenPaths.serverSideScriptDirectories.push( forbiddenPaths.serverSideScriptDirectories.push(
getInitializePath("./node_modules"), getInitializePath("./node_modules")
); );
forbiddenPaths.serverSideScriptDirectories.push(getInitializePath("./mods")); forbiddenPaths.serverSideScriptDirectories.push(getInitializePath("./mods"));
forbiddenPaths.temp = getInitializePath("./temp"); forbiddenPaths.temp = getInitializePath("./temp");
@ -51,7 +51,7 @@ module.exports = (req, res, logFacilities, config, next) => {
let decodedHrefWithoutDuplicateSlashes = ""; let decodedHrefWithoutDuplicateSlashes = "";
try { try {
decodedHrefWithoutDuplicateSlashes = decodeURIComponent( decodedHrefWithoutDuplicateSlashes = decodeURIComponent(
req.parsedURL.pathname, req.parsedURL.pathname
).replace(/\/+/g, "/"); ).replace(/\/+/g, "/");
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
} catch (err) { } catch (err) {
@ -66,7 +66,7 @@ module.exports = (req, res, logFacilities, config, next) => {
) { ) {
res.error(403); res.error(403);
logFacilities.errmessage( logFacilities.errmessage(
"Access to configuration file/certificates is denied.", "Access to configuration file/certificates is denied."
); );
return; return;
} else if ( } else if (
@ -97,11 +97,11 @@ module.exports = (req, res, logFacilities, config, next) => {
(isForbiddenPath(decodedHrefWithoutDuplicateSlashes, "svrjs") || (isForbiddenPath(decodedHrefWithoutDuplicateSlashes, "svrjs") ||
isForbiddenPath( isForbiddenPath(
decodedHrefWithoutDuplicateSlashes, decodedHrefWithoutDuplicateSlashes,
"serverSideScripts", "serverSideScripts"
) || ) ||
isIndexOfForbiddenPath( isIndexOfForbiddenPath(
decodedHrefWithoutDuplicateSlashes, decodedHrefWithoutDuplicateSlashes,
"serverSideScriptDirectories", "serverSideScriptDirectories"
)) && )) &&
!req.isProxy && !req.isProxy &&
(config.disableServerSideScriptExpose || (config.disableServerSideScriptExpose ||

View file

@ -14,7 +14,7 @@ module.exports = (req, res, logFacilities, config, next) => {
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace( .replace(
/>/g, />/g,
"&gt;", "&gt;"
)} doesn't support proxy without proxy mod. If you're administator of this server, then install this mod in order to use ${name )} doesn't support proxy without proxy mod. If you're administator of this server, then install this mod in order to use ${name
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
@ -22,11 +22,11 @@ module.exports = (req, res, logFacilities, config, next) => {
.generateServerString() .generateServerString()
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;")}</i></p></body></html>`, .replace(/>/g, "&gt;")}</i></p></body></html>`
); );
res.end(); res.end();
logFacilities.errmessage( logFacilities.errmessage(
`${name} doesn't support proxy without proxy mod.`, `${name} doesn't support proxy without proxy mod.`
); );
return; return;
} }

View file

@ -9,7 +9,7 @@ const svrjsInfo = require("../../svrjs.json");
const { name } = svrjsInfo; const { name } = svrjsInfo;
let crypto = { let crypto = {
__disabled__: null, __disabled__: null
}; };
try { try {
crypto = require("crypto"); crypto = require("crypto");
@ -43,10 +43,10 @@ process.serverConfig.nonStandardCodes.forEach((nonStandardCodeRaw) => {
if (!cluster.isPrimary) { if (!cluster.isPrimary) {
passwordHashCacheIntervalId = setInterval(() => { passwordHashCacheIntervalId = setInterval(() => {
pbkdf2Cache = pbkdf2Cache.filter( pbkdf2Cache = pbkdf2Cache.filter(
(entry) => entry.addDate > new Date() - 3600000, (entry) => entry.addDate > new Date() - 3600000
); );
scryptCache = scryptCache.filter( scryptCache = scryptCache.filter(
(entry) => entry.addDate > new Date() - 3600000, (entry) => entry.addDate > new Date() - 3600000
); );
}, 1800000); }, 1800000);
} }
@ -67,13 +67,13 @@ module.exports = (req, res, logFacilities, config, next) => {
matchHostname(nonStandardCodes[i].host, req.headers.host) && matchHostname(nonStandardCodes[i].host, req.headers.host) &&
ipMatch( ipMatch(
nonStandardCodes[i].ip, nonStandardCodes[i].ip,
req.socket ? req.socket.localAddress : undefined, req.socket ? req.socket.localAddress : undefined
) )
) { ) {
let isMatch = false; let isMatch = false;
hrefWithoutDuplicateSlashes = req.parsedURL.pathname.replace( hrefWithoutDuplicateSlashes = req.parsedURL.pathname.replace(
/\/+/g, /\/+/g,
"/", "/"
); );
if (nonStandardCodes[i].regex) { if (nonStandardCodes[i].regex) {
// Regex match // Regex match
@ -130,7 +130,7 @@ module.exports = (req, res, logFacilities, config, next) => {
// Fallback replacement // Fallback replacement
location = hrefWithoutDuplicateSlashes.replace( location = hrefWithoutDuplicateSlashes.replace(
regexI[nonscodeIndex], regexI[nonscodeIndex],
nonscode.location, nonscode.location
); );
} }
} else if ( } else if (
@ -146,7 +146,7 @@ module.exports = (req, res, logFacilities, config, next) => {
res.redirect( res.redirect(
location, location,
nonscode.scode == 302 || nonscode.scode == 307, nonscode.scode == 302 || nonscode.scode == 307,
nonscode.scode == 307 || nonscode.scode == 308, nonscode.scode == 307 || nonscode.scode == 308
); );
return; return;
} else { } else {
@ -187,14 +187,14 @@ module.exports = (req, res, logFacilities, config, next) => {
res.error( res.error(
500, 500,
new Error( 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; return;
} else { } else {
cacheEntry = scryptCache.find( cacheEntry = scryptCache.find(
(entry) => (entry) =>
entry.password == hashedPassword && entry.salt == list[_i].salt, entry.password == hashedPassword && entry.salt == list[_i].salt
); );
if (cacheEntry) { if (cacheEntry) {
cb(cacheEntry.hash); cb(cacheEntry.hash);
@ -208,7 +208,7 @@ module.exports = (req, res, logFacilities, config, next) => {
hash: key, hash: key,
password: hashedPassword, password: hashedPassword,
salt: list[_i].salt, salt: list[_i].salt,
addDate: new Date(), addDate: new Date()
}); });
cb(key); cb(key);
} }
@ -220,14 +220,14 @@ module.exports = (req, res, logFacilities, config, next) => {
res.error( res.error(
500, 500,
new Error( 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; return;
} else { } else {
cacheEntry = pbkdf2Cache.find( cacheEntry = pbkdf2Cache.find(
(entry) => (entry) =>
entry.password == hashedPassword && entry.salt == list[_i].salt, entry.password == hashedPassword && entry.salt == list[_i].salt
); );
if (cacheEntry) { if (cacheEntry) {
cb(cacheEntry.hash); cb(cacheEntry.hash);
@ -247,11 +247,11 @@ module.exports = (req, res, logFacilities, config, next) => {
hash: key, hash: key,
password: hashedPassword, password: hashedPassword,
salt: list[_i].salt, salt: list[_i].salt,
addDate: new Date(), addDate: new Date()
}); });
cb(key); cb(key);
} }
}, }
); );
} }
} }
@ -282,7 +282,7 @@ module.exports = (req, res, logFacilities, config, next) => {
} }
const decodedCredentials = Buffer.from( const decodedCredentials = Buffer.from(
credentialsMatch[1], credentialsMatch[1],
"base64", "base64"
).toString("utf8"); ).toString("utf8");
const decodedCredentialsMatch = const decodedCredentialsMatch =
decodedCredentials.match(/^([^:]*):(.*)$/); decodedCredentials.match(/^([^:]*):(.*)$/);
@ -314,7 +314,7 @@ module.exports = (req, res, logFacilities, config, next) => {
let fakeCredentials = { let fakeCredentials = {
name: username, name: username,
pass: "SVRJSAWebServerRunningOnNodeJS", pass: "SVRJSAWebServerRunningOnNodeJS",
salt: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0", salt: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0"
}; };
if (!process.isBun) { if (!process.isBun) {
if (scryptCount > sha256Count && scryptCount > pbkdf2Count) { if (scryptCount > sha256Count && scryptCount > pbkdf2Count) {
@ -334,7 +334,7 @@ module.exports = (req, res, logFacilities, config, next) => {
} else { } else {
if (!bruteForceDb[reqip]) if (!bruteForceDb[reqip])
bruteForceDb[reqip] = { bruteForceDb[reqip] = {
invalidAttempts: 0, invalidAttempts: 0
}; };
bruteForceDb[reqip].invalidAttempts++; bruteForceDb[reqip].invalidAttempts++;
if (bruteForceDb[reqip].invalidAttempts >= 10) { if (bruteForceDb[reqip].invalidAttempts >= 10) {
@ -344,7 +344,7 @@ module.exports = (req, res, logFacilities, config, next) => {
} }
res.error(401, ha); res.error(401, ha);
logFacilities.errmessage( 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 { } else {
if (bruteProtection) { if (bruteProtection) {
@ -353,12 +353,12 @@ module.exports = (req, res, logFacilities, config, next) => {
} else { } else {
if (bruteForceDb[reqip]) if (bruteForceDb[reqip])
bruteForceDb[reqip] = { bruteForceDb[reqip] = {
invalidAttempts: 0, invalidAttempts: 0
}; };
} }
} }
logFacilities.reqmessage( 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; req.authUser = username;
next(); next();
@ -385,7 +385,7 @@ module.exports = (req, res, logFacilities, config, next) => {
) { ) {
if (bruteForceDb[reqip] && bruteForceDb[reqip].invalidAttempts >= 10) if (bruteForceDb[reqip] && bruteForceDb[reqip].invalidAttempts >= 10)
bruteForceDb[reqip] = { bruteForceDb[reqip] = {
invalidAttempts: 5, invalidAttempts: 5
}; };
authorizedCallback(true); authorizedCallback(true);
} else { } else {
@ -428,7 +428,7 @@ process.messageEventListeners.push((worker, serverconsole) => {
) { ) {
if (bruteForceDb[ip] && bruteForceDb[ip].invalidAttempts >= 10) if (bruteForceDb[ip] && bruteForceDb[ip].invalidAttempts >= 10)
bruteForceDb[ip] = { bruteForceDb[ip] = {
invalidAttempts: 5, invalidAttempts: 5
}; };
worker.send("\x14AUTHA" + ip); worker.send("\x14AUTHA" + ip);
} else { } else {
@ -438,13 +438,13 @@ process.messageEventListeners.push((worker, serverconsole) => {
ip = message.substring(6); ip = message.substring(6);
if (bruteForceDb[ip]) if (bruteForceDb[ip])
bruteForceDb[ip] = { bruteForceDb[ip] = {
invalidAttempts: 0, invalidAttempts: 0
}; };
} else if (message.substring(0, 6) == "\x12AUTHW") { } else if (message.substring(0, 6) == "\x12AUTHW") {
ip = message.substring(6); ip = message.substring(6);
if (!bruteForceDb[ip]) if (!bruteForceDb[ip])
bruteForceDb[ip] = { bruteForceDb[ip] = {
invalidAttempts: 0, invalidAttempts: 0
}; };
bruteForceDb[ip].invalidAttempts++; bruteForceDb[ip].invalidAttempts++;
if (bruteForceDb[ip].invalidAttempts >= 10) { if (bruteForceDb[ip].invalidAttempts >= 10) {
@ -458,7 +458,7 @@ module.exports.commands = {
stop: (args, log, passCommand) => { stop: (args, log, passCommand) => {
clearInterval(passwordHashCacheIntervalId); clearInterval(passwordHashCacheIntervalId);
passCommand(args, log); passCommand(args, log);
}, }
}; };
module.exports.proxySafe = true; module.exports.proxySafe = true;

View file

@ -21,7 +21,7 @@ module.exports = (req, res, logFacilities, config, next) => {
req.originalParsedURL.pathname + req.originalParsedURL.pathname +
"/" + "/" +
(req.parsedURL.search ? req.parsedURL.search : "") + (req.parsedURL.search ? req.parsedURL.search : "") +
(req.parsedURL.hash ? req.parsedURL.hash : ""), (req.parsedURL.hash ? req.parsedURL.hash : "")
); );
} }
}); });

View file

@ -27,7 +27,7 @@ module.exports = (req, res, logFacilities, config, next) => {
? req.socket.realRemoteAddress ? req.socket.realRemoteAddress
: req.socket.remoteAddress : req.socket.remoteAddress
).match( ).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; let destinationPort = 0;
@ -50,7 +50,7 @@ module.exports = (req, res, logFacilities, config, next) => {
"https://" + "https://" +
hostname + hostname +
(destinationPort == 443 ? "" : ":" + destinationPort) + (destinationPort == 443 ? "" : ":" + destinationPort) +
req.url, req.url
); );
return; return;
} }
@ -67,7 +67,7 @@ module.exports = (req, res, logFacilities, config, next) => {
hostname = hostname.join(":"); hostname = hostname.join(":");
if (hostname == config.domain && hostname.indexOf("www.") != 0) { if (hostname == config.domain && hostname.indexOf("www.") != 0) {
res.redirect( res.redirect(
`${req.socket.encrypted ? "https" : "http"}://www.${hostname}${hostport ? ":" + hostport : ""}${req.url.replace(/\/+/g, "/")}`, `${req.socket.encrypted ? "https" : "http"}://www.${hostname}${hostport ? ":" + hostport : ""}${req.url.replace(/\/+/g, "/")}`
); );
return; return;
} }

View file

@ -41,7 +41,7 @@ module.exports = (req, res, logFacilities, config, next) => {
_fileState = 3; _fileState = 3;
} }
rewriteURL(address, map, callback, _fileState, i); rewriteURL(address, map, callback, _fileState, i);
}, }
); );
doCallback = false; doCallback = false;
break; break;
@ -56,7 +56,7 @@ module.exports = (req, res, logFacilities, config, next) => {
matchHostname(mapEntry.host, req.headers.host) && matchHostname(mapEntry.host, req.headers.host) &&
ipMatch( ipMatch(
mapEntry.ip, mapEntry.ip,
req.socket ? req.socket.localAddress : undefined, req.socket ? req.socket.localAddress : undefined
) && ) &&
address.match(createRegex(mapEntry.definingRegex)) && address.match(createRegex(mapEntry.definingRegex)) &&
!(mapEntry.isNotDirectory && _fileState == 2) && !(mapEntry.isNotDirectory && _fileState == 2) &&
@ -66,7 +66,7 @@ module.exports = (req, res, logFacilities, config, next) => {
mapEntry.replacements.forEach((replacement) => { mapEntry.replacements.forEach((replacement) => {
rewrittenURL = rewrittenURL.replace( rewrittenURL = rewrittenURL.replace(
createRegex(replacement.regex), createRegex(replacement.regex),
replacement.replacement, replacement.replacement
); );
}); });
if (mapEntry.append) rewrittenURL += mapEntry.append; if (mapEntry.append) rewrittenURL += mapEntry.append;
@ -100,7 +100,7 @@ module.exports = (req, res, logFacilities, config, next) => {
: config.domain : config.domain
? config.domain ? config.domain
: "unknown.invalid" : "unknown.invalid"
}`, }`
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);
@ -109,7 +109,7 @@ module.exports = (req, res, logFacilities, config, next) => {
const sHref = sanitizeURL( const sHref = sanitizeURL(
req.parsedURL.pathname, req.parsedURL.pathname,
config.allowDoubleSlashes, config.allowDoubleSlashes
); );
const preparedReqUrl2 = const preparedReqUrl2 =
req.parsedURL.pathname + req.parsedURL.pathname +
@ -132,7 +132,7 @@ module.exports = (req, res, logFacilities, config, next) => {
(req.parsedURL.search ? req.parsedURL.search : "") + (req.parsedURL.search ? req.parsedURL.search : "") +
(req.parsedURL.hash ? req.parsedURL.hash : ""); (req.parsedURL.hash ? req.parsedURL.hash : "");
logFacilities.resmessage( logFacilities.resmessage(
`URL sanitized: ${req.url} => ${rewrittenAgainURL}`, `URL sanitized: ${req.url} => ${rewrittenAgainURL}`
); );
req.url = rewrittenAgainURL; req.url = rewrittenAgainURL;
try { try {
@ -144,7 +144,7 @@ module.exports = (req, res, logFacilities, config, next) => {
: config.domain : config.domain
? config.domain ? config.domain
: "unknown.invalid" : "unknown.invalid"
}`, }`
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);

View file

@ -18,7 +18,7 @@ let ETagDB = {};
const generateETag = (filePath, stat) => { const generateETag = (filePath, stat) => {
if (!ETagDB[filePath + "-" + stat.size + "-" + stat.mtime]) if (!ETagDB[filePath + "-" + stat.size + "-" + stat.mtime])
ETagDB[filePath + "-" + stat.size + "-" + stat.mtime] = sha256( ETagDB[filePath + "-" + stat.size + "-" + stat.mtime] = sha256(
filePath + "-" + stat.size + "-" + stat.mtime, filePath + "-" + stat.size + "-" + stat.mtime
); );
return ETagDB[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"]; const clientETag = req.headers["if-none-match"];
if (clientETag === fileETag) { if (clientETag === fileETag) {
res.writeHead(304, http.STATUS_CODES[304], { res.writeHead(304, http.STATUS_CODES[304], {
ETag: clientETag, ETag: clientETag
}); });
res.end(); res.end();
return; return;
@ -151,7 +151,7 @@ module.exports = (req, res, logFacilities, config, next) => {
const ifMatchETag = req.headers["if-match"]; const ifMatchETag = req.headers["if-match"];
if (ifMatchETag && ifMatchETag !== "*" && ifMatchETag !== fileETag) { if (ifMatchETag && ifMatchETag !== "*" && ifMatchETag !== fileETag) {
res.error(412, { res.error(412, {
ETag: clientETag, ETag: clientETag
}); });
return; return;
} }
@ -164,7 +164,7 @@ module.exports = (req, res, logFacilities, config, next) => {
rhd["Accept-Ranges"] = "bytes"; rhd["Accept-Ranges"] = "bytes";
rhd["Content-Range"] = `bytes */${filelen}`; rhd["Content-Range"] = `bytes */${filelen}`;
const regexmatch = req.headers["range"].match( const regexmatch = req.headers["range"].match(
/bytes=([0-9]*)-([0-9]*)/, /bytes=([0-9]*)-([0-9]*)/
); );
if (!regexmatch) { if (!regexmatch) {
res.error(416, rhd); res.error(416, rhd);
@ -217,8 +217,8 @@ module.exports = (req, res, logFacilities, config, next) => {
res.end( res.end(
res.foot.substring( res.foot.substring(
begin - res.head.length - filelen, begin - res.head.length - filelen,
end - res.head.length - filelen + 1, end - res.head.length - filelen + 1
), )
); );
return; return;
} }
@ -230,7 +230,7 @@ module.exports = (req, res, logFacilities, config, next) => {
end: end:
ext == "html" ext == "html"
? Math.min(filelen, end - res.head.length) ? Math.min(filelen, end - res.head.length)
: end, : end
}); });
readStream readStream
.on("error", (err) => { .on("error", (err) => {
@ -266,8 +266,8 @@ module.exports = (req, res, logFacilities, config, next) => {
res.end( res.end(
res.foot.substring( res.foot.substring(
0, 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: !( end: !(
res.foot.length > 0 && res.foot.length > 0 &&
end > res.head.length + filelen end > res.head.length + filelen
), )
}); });
}; };
res.writeHead(206, http.STATUS_CODES[206], rhd); res.writeHead(206, http.STATUS_CODES[206], rhd);
@ -283,7 +283,7 @@ module.exports = (req, res, logFacilities, config, next) => {
afterWriteCallback(); afterWriteCallback();
} else if ( } else if (
!res.write( !res.write(
res.head.substring(begin, res.head.length - begin), res.head.substring(begin, res.head.length - begin)
) )
) { ) {
res.on("drain", afterWriteCallback); res.on("drain", afterWriteCallback);
@ -295,7 +295,7 @@ module.exports = (req, res, logFacilities, config, next) => {
readStream.pipe(res); readStream.pipe(res);
} }
logFacilities.resmessage( logFacilities.resmessage(
"Client successfully received content.", "Client successfully received content."
); );
} catch (err) { } catch (err) {
res.error(500, err); res.error(500, err);
@ -352,10 +352,10 @@ module.exports = (req, res, logFacilities, config, next) => {
) { ) {
if ( if (
/^Mozilla\/4\.[0-9]+(( *\[[^)]*\] *| *)\([^)\]]*\))? *$/.test( /^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( !/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. 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 { } else {
if ( if (
/^Mozilla\/4\.0[6-8](( *\[[^)]*\] *| *)\([^)\]]*\))? *$/.test( /^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( !/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. 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, { readStream.pipe(resStream, {
end: res.foot.length == 0, end: res.foot.length == 0
}); });
}; };
res.writeHead(200, http.STATUS_CODES[200], hdhds); res.writeHead(200, http.STATUS_CODES[200], hdhds);
@ -474,7 +474,7 @@ module.exports = (req, res, logFacilities, config, next) => {
readStream.pipe(resStream); readStream.pipe(resStream);
} }
logFacilities.resmessage( logFacilities.resmessage(
"Client successfully received content.", "Client successfully received content."
); );
} catch (err) { } catch (err) {
res.error(500, err); res.error(500, err);
@ -494,7 +494,7 @@ module.exports = (req, res, logFacilities, config, next) => {
if ( if (
checkForEnabledDirectoryListing( checkForEnabledDirectoryListing(
req.headers.host, req.headers.host,
req.socket ? req.socket.localAddress : undefined, req.socket ? req.socket.localAddress : undefined
) )
) { ) {
let customDirListingHeader = ""; let customDirListingHeader = "";
@ -520,7 +520,7 @@ module.exports = (req, res, logFacilities, config, next) => {
customDirListingHeader = data.toString(); customDirListingHeader = data.toString();
callback(); callback();
} }
}, }
); );
} else { } else {
callback(); callback();
@ -532,7 +532,7 @@ module.exports = (req, res, logFacilities, config, next) => {
customDirListingHeader = data.toString(); customDirListingHeader = data.toString();
callback(); callback();
} }
}, }
); );
}; };
@ -556,7 +556,7 @@ module.exports = (req, res, logFacilities, config, next) => {
customDirListingFooter = data.toString(); customDirListingFooter = data.toString();
callback(); callback();
} }
}, }
); );
} else { } else {
callback(); callback();
@ -568,7 +568,7 @@ module.exports = (req, res, logFacilities, config, next) => {
customDirListingFooter = data.toString(); customDirListingFooter = data.toString();
callback(); callback();
} }
}, }
); );
}; };
@ -579,7 +579,7 @@ module.exports = (req, res, logFacilities, config, next) => {
const headerHasHTMLTag = customDirListingHeader const headerHasHTMLTag = customDirListingHeader
.replace(/<!--(?:(?:(?!-->)[\s\S])*|)(?:-->|$)/g, "") .replace(/<!--(?:(?:(?!-->)[\s\S])*|)(?:-->|$)/g, "")
.match( .match(
/<html(?![a-zA-Z0-9])(?:"(?:\\(?:[\s\S]|$)|[^\\"])*(?:"|$)|'(?:\\(?:[\s\S]|$)|[^\\'])*(?:'|$)|[^'">])*(?:>|$)/i, /<html(?![a-zA-Z0-9])(?:"(?:\\(?:[\s\S]|$)|[^\\"])*(?:"|$)|'(?:\\(?:[\s\S]|$)|[^\\'])*(?:'|$)|[^'">])*(?:>|$)/i
); );
// Generate HTML head and footer based on configuration and custom content // Generate HTML head and footer based on configuration and custom content
@ -601,7 +601,7 @@ module.exports = (req, res, logFacilities, config, next) => {
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") + .replace(/>/g, "&gt;") +
"</title>", "</title>"
) )
: res.head.replace( : res.head.replace(
/<head>/i, /<head>/i,
@ -610,14 +610,14 @@ module.exports = (req, res, logFacilities, config, next) => {
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") + .replace(/>/g, "&gt;") +
"</title>", "</title>"
)) + (!headerHasHTMLTag ? customDirListingHeader : "") )) + (!headerHasHTMLTag ? customDirListingHeader : "")
}<h1>Directory: ${decodeURIComponent(origHref) }<h1>Directory: ${decodeURIComponent(origHref)
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace( .replace(
/>/g, />/g,
"&gt;", "&gt;"
)}</h1><table id="directoryListing"> <tr> <th></th> <th>Filename</th> <th>Size</th> <th>Date</th> </tr>${ )}</h1><table id="directoryListing"> <tr> <th></th> <th>Filename</th> <th>Size</th> <th>Date</th> </tr>${
checkPathLevel(decodeURIComponent(origHref)) < 1 checkPathLevel(decodeURIComponent(origHref)) < 1
? "" ? ""
@ -648,7 +648,7 @@ module.exports = (req, res, logFacilities, config, next) => {
fs.existsSync( fs.existsSync(
"." + "." +
decodeURIComponent(href) + decodeURIComponent(href) +
"/.maindesc".replace(/\/+/g, "/"), "/.maindesc".replace(/\/+/g, "/")
) )
) { ) {
htmlFoot = htmlFoot =
@ -656,7 +656,7 @@ module.exports = (req, res, logFacilities, config, next) => {
fs.readFileSync( fs.readFileSync(
"." + "." +
decodeURIComponent(href) + decodeURIComponent(href) +
"/.maindesc".replace(/\/+/g, "/"), "/.maindesc".replace(/\/+/g, "/")
) + ) +
htmlFoot; htmlFoot;
} }
@ -672,7 +672,7 @@ module.exports = (req, res, logFacilities, config, next) => {
callback, callback,
prefix, prefix,
pushArray, pushArray,
index, index
) => { ) => {
if (fileList.length == 0) { if (fileList.length == 0) {
callback(pushArray); callback(pushArray);
@ -686,13 +686,13 @@ module.exports = (req, res, logFacilities, config, next) => {
fs.lstat( fs.lstat(
(prefix + "/" + fileList[index]).replace( (prefix + "/" + fileList[index]).replace(
/\/+/g, /\/+/g,
"/", "/"
), ),
(err, stats) => { (err, stats) => {
pushArray.push({ pushArray.push({
name: fileList[index], name: fileList[index],
stats: err ? null : stats, stats: err ? null : stats,
errored: true, errored: true
}); });
if (index < fileList.length - 1) { if (index < fileList.length - 1) {
getStatsForAllFilesI( getStatsForAllFilesI(
@ -700,18 +700,18 @@ module.exports = (req, res, logFacilities, config, next) => {
callback, callback,
prefix, prefix,
pushArray, pushArray,
index + 1, index + 1
); );
} else { } else {
callback(pushArray); callback(pushArray);
} }
}, }
); );
} else { } else {
pushArray.push({ pushArray.push({
name: fileList[index], name: fileList[index],
stats: stats, stats: stats,
errored: false, errored: false
}); });
if (index < fileList.length - 1) { if (index < fileList.length - 1) {
getStatsForAllFilesI( getStatsForAllFilesI(
@ -719,13 +719,13 @@ module.exports = (req, res, logFacilities, config, next) => {
callback, callback,
prefix, prefix,
pushArray, pushArray,
index + 1, index + 1
); );
} else { } else {
callback(pushArray); callback(pushArray);
} }
} }
}, }
); );
}; };
@ -756,8 +756,8 @@ module.exports = (req, res, logFacilities, config, next) => {
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace( .replace(
/>/g, />/g,
"&gt;", "&gt;"
)}</a></td><td>-</td><td>${estats ? estats.mtime.toDateString() : "-"}</td></tr>\r\n`, )}</a></td><td>-</td><td>${estats ? estats.mtime.toDateString() : "-"}</td></tr>\r\n`
); );
} else { } else {
let entry = `<tr><td style="width: 24px;"><img src="[img]" alt="[alt]" width="24px" height="24px" /></td><td style="word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;"><a href="${( let entry = `<tr><td style="width: 24px;"><img src="[img]" alt="[alt]" width="24px" height="24px" /></td><td style="word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;"><a href="${(
@ -766,7 +766,7 @@ module.exports = (req, res, logFacilities, config, next) => {
encodeURIComponent(ename) encodeURIComponent(ename)
).replace( ).replace(
/\/+/g, /\/+/g,
"/", "/"
)}${estats.isDirectory() ? "/" : ""}">${ename )}${estats.isDirectory() ? "/" : ""}">${ename
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
@ -789,7 +789,7 @@ module.exports = (req, res, logFacilities, config, next) => {
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace( .replace(
/>/g, />/g,
"&gt;", "&gt;"
)}</a></td><td>-</td><td>${estats.mtime.toDateString()}</td></tr>\r\n`; )}</a></td><td>-</td><td>${estats.mtime.toDateString()}</td></tr>\r\n`;
// Determine the special file types (block device, character device, etc.) // Determine the special file types (block device, character device, etc.)
@ -819,7 +819,7 @@ module.exports = (req, res, logFacilities, config, next) => {
.replace("[img]", "/.dirimages/html.png") .replace("[img]", "/.dirimages/html.png")
.replace( .replace(
"[alt]", "[alt]",
eext == "xml" ? "[XML]" : "[HTM]", eext == "xml" ? "[XML]" : "[HTM]"
); );
} else if (eext == "js") { } else if (eext == "js") {
entry = entry entry = entry
@ -838,7 +838,7 @@ module.exports = (req, res, logFacilities, config, next) => {
.replace("[img]", "/.dirimages/image.png") .replace("[img]", "/.dirimages/image.png")
.replace( .replace(
"[alt]", "[alt]",
eext == "ico" ? "[ICO]" : "[IMG]", eext == "ico" ? "[ICO]" : "[IMG]"
); );
} else if (emime && emime.split("/")[0] == "font") { } else if (emime && emime.split("/")[0] == "font") {
entry = entry entry = entry
@ -856,7 +856,7 @@ module.exports = (req, res, logFacilities, config, next) => {
.replace("[img]", "/.dirimages/text.png") .replace("[img]", "/.dirimages/text.png")
.replace( .replace(
"[alt]", "[alt]",
eext == "json" ? "[JSO]" : "[TXT]", eext == "json" ? "[JSO]" : "[TXT]"
); );
} else if (emime && emime.split("/")[0] == "video") { } else if (emime && emime.split("/")[0] == "video") {
entry = entry entry = entry
@ -885,19 +885,19 @@ module.exports = (req, res, logFacilities, config, next) => {
// Push the information about empty directory // Push the information about empty directory
if (directoryListingRows.length == 0) { if (directoryListingRows.length == 0) {
directoryListingRows.push( directoryListingRows.push(
"<tr><td></td><td>No files found</td><td></td><td></td></tr>", "<tr><td></td><td>No files found</td><td></td><td></td></tr>"
); );
} }
// Send the directory listing response // Send the directory listing response
res.writeHead(200, http.STATUS_CODES[200], { res.writeHead(200, http.STATUS_CODES[200], {
"Content-Type": "text/html; charset=utf-8", "Content-Type": "text/html; charset=utf-8"
}); });
res.end( res.end(
htmlHead + directoryListingRows.join("") + htmlFoot, htmlHead + directoryListingRows.join("") + htmlFoot
); );
logFacilities.resmessage( logFacilities.resmessage(
"Client successfully received content.", "Client successfully received content."
); );
}); });
} catch (err) { } catch (err) {
@ -932,7 +932,7 @@ module.exports = (req, res, logFacilities, config, next) => {
} else { } else {
res.error(501); res.error(501);
logFacilities.errmessage( 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; return;
} }
@ -955,7 +955,7 @@ module.exports = (req, res, logFacilities, config, next) => {
readFrom = (readFrom + "/index.xhtml").replace(/\/+/g, "/"); readFrom = (readFrom + "/index.xhtml").replace(/\/+/g, "/");
properDirectoryListingAndStaticFileServe(); properDirectoryListingAndStaticFileServe();
} }
}, }
); );
} else { } else {
stats = s; stats = s;

View file

@ -40,7 +40,7 @@ module.exports = (req, res, logFacilities, config, next) => {
statusBody += `Average error rate: ${ statusBody += `Average error rate: ${
Math.round( Math.round(
((process.err4xxcounter + process.err5xxcounter) / process.reqcounter) * ((process.err4xxcounter + process.err5xxcounter) / process.reqcounter) *
10000, 10000
) / 100 ) / 100
}%<br/>`; }%<br/>`;
statusBody += `Malformed HTTP requests: ${process.malformedcounter}`; statusBody += `Malformed HTTP requests: ${process.malformedcounter}`;
@ -52,13 +52,13 @@ module.exports = (req, res, logFacilities, config, next) => {
((process.cpuUsage().user + process.cpuUsage().system) / ((process.cpuUsage().user + process.cpuUsage().system) /
1000000 / 1000000 /
process.uptime()) * process.uptime()) *
1000, 1000
) / 1000 ) / 1000
}%`; }%`;
statusBody += `<br/>Thread PID: ${process.pid}<br/>`; statusBody += `<br/>Thread PID: ${process.pid}<br/>`;
res.writeHead(200, http.STATUS_CODES[200], { res.writeHead(200, http.STATUS_CODES[200], {
"Content-Type": "text/html; charset=utf-8", "Content-Type": "text/html; charset=utf-8"
}); });
res.end( res.end(
`${ `${
@ -94,7 +94,7 @@ module.exports = (req, res, logFacilities, config, next) => {
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;")) + .replace(/>/g, "&gt;")) +
"</title>", "</title>"
) )
}<h1>${name }<h1>${name
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
@ -107,7 +107,7 @@ module.exports = (req, res, logFacilities, config, next) => {
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") .replace(/>/g, "&gt;")
}</h1>${statusBody}${res.foot == "" ? "</body></html>" : res.foot}`, }</h1>${statusBody}${res.foot == "" ? "</body></html>" : res.foot}`
); );
return; return;
} }

View file

@ -5,7 +5,7 @@ module.exports = (req, res, logFacilities, config, next) => {
// Sanitize URL // Sanitize URL
let sanitizedHref = sanitizeURL( let sanitizedHref = sanitizeURL(
req.parsedURL.pathname, req.parsedURL.pathname,
config.allowDoubleSlashes, config.allowDoubleSlashes
); );
let preparedReqUrl = let preparedReqUrl =
req.parsedURL.pathname + req.parsedURL.pathname +
@ -30,7 +30,7 @@ module.exports = (req, res, logFacilities, config, next) => {
: config.domain : config.domain
? config.domain ? config.domain
: "unknown.invalid" : "unknown.invalid"
}`, }`
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);

View file

@ -59,7 +59,7 @@ module.exports = (req, res, logFacilities, config, next) => {
matchHostname(postfixEntry.host) && matchHostname(postfixEntry.host) &&
ipMatch( ipMatch(
postfixEntry.ip, postfixEntry.ip,
req.socket ? req.socket.localAddress : undefined, req.socket ? req.socket.localAddress : undefined
) && ) &&
!( !(
postfixEntry.skipRegex && postfixEntry.skipRegex &&
@ -75,7 +75,7 @@ module.exports = (req, res, logFacilities, config, next) => {
}); });
if (urlWithPostfix != preparedReqUrl3) { if (urlWithPostfix != preparedReqUrl3) {
logFacilities.resmessage( logFacilities.resmessage(
"Added web root postfix: " + req.url + " => " + urlWithPostfix, "Added web root postfix: " + req.url + " => " + urlWithPostfix
); );
req.url = urlWithPostfix; req.url = urlWithPostfix;
try { try {
@ -87,7 +87,7 @@ module.exports = (req, res, logFacilities, config, next) => {
: config.domain : config.domain
? config.domain ? config.domain
: "unknown.invalid" : "unknown.invalid"
}`, }`
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);
@ -96,7 +96,7 @@ module.exports = (req, res, logFacilities, config, next) => {
const sHref = sanitizeURL( const sHref = sanitizeURL(
req.parsedURL.pathname, req.parsedURL.pathname,
config.allowDoubleSlashes, config.allowDoubleSlashes
); );
const preparedReqUrl2 = const preparedReqUrl2 =
req.parsedURL.pathname + req.parsedURL.pathname +
@ -119,7 +119,7 @@ module.exports = (req, res, logFacilities, config, next) => {
(req.parsedURL.search ? req.parsedURL.search : "") + (req.parsedURL.search ? req.parsedURL.search : "") +
(req.parsedURL.hash ? req.parsedURL.hash : ""); (req.parsedURL.hash ? req.parsedURL.hash : "");
logFacilities.resmessage( logFacilities.resmessage(
`URL sanitized: ${req.url} => ${rewrittenAgainURL}`, `URL sanitized: ${req.url} => ${rewrittenAgainURL}`
); );
req.url = rewrittenAgainURL; req.url = rewrittenAgainURL;
try { try {
@ -131,7 +131,7 @@ module.exports = (req, res, logFacilities, config, next) => {
: config.domain : config.domain
? config.domain ? config.domain
: "unknown.invalid" : "unknown.invalid"
}`, }`
); );
} catch (err) { } catch (err) {
res.error(400, err); res.error(400, err);

View file

@ -46,7 +46,7 @@ const serverHTTPErrorDescs = {
510: "The server requires an extended HTTP request. The request you made isn't an extended HTTP request.", 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.", 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.", 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; module.exports = serverHTTPErrorDescs;

View file

@ -39,7 +39,7 @@ const logo = [
"\x1b[0m ,///////,", "\x1b[0m ,///////,",
"", "",
"", "",
"\x1b[0m", "\x1b[0m"
]; ];
module.exports = logo; module.exports = logo;

View file

@ -30,7 +30,7 @@ const serverErrorDescs = {
"Protocol not supported. The requested network protocol is not supported.", "Protocol not supported. The requested network protocol is not supported.",
ETIMEDOUT: ETIMEDOUT:
"Connection timed out. The server did not respond within the specified timeout period.", "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; module.exports = serverErrorDescs;

View file

@ -29,7 +29,7 @@ if (!process.singleThreaded) {
isDead: () => false, isDead: () => false,
send: (message, ...params) => { send: (message, ...params) => {
process.send(message, ...params); process.send(message, ...params);
}, }
}; };
if (!process.send) { if (!process.send) {
@ -52,9 +52,9 @@ if (!process.singleThreaded) {
? path.join( ? path.join(
"\\\\?\\pipe", "\\\\?\\pipe",
process.dirname, 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) => { process.send = (message) => {
@ -64,12 +64,12 @@ if (!process.singleThreaded) {
? path.join( ? path.join(
"\\\\?\\pipe", "\\\\?\\pipe",
process.dirname, process.dirname,
"temp/.P" + process.pid + ".ipc", "temp/.P" + process.pid + ".ipc"
) )
: process.dirname + "/temp/.P" + process.pid + ".ipc", : process.dirname + "/temp/.P" + process.pid + ".ipc",
() => { () => {
fakeIPCConnection.end(message); fakeIPCConnection.end(message);
}, }
); );
}; };
@ -92,7 +92,7 @@ if (!process.singleThreaded) {
let command = newArguments.shift(); let command = newArguments.shift();
let newWorker = child_process.spawn(command, newArguments, { let newWorker = child_process.spawn(command, newArguments, {
env: newEnvironment, env: newEnvironment,
stdio: ["inherit", "inherit", "inherit", "ipc"], stdio: ["inherit", "inherit", "inherit", "ipc"]
}); });
newWorker.process = newWorker; newWorker.process = newWorker;
@ -158,9 +158,9 @@ if (!process.singleThreaded) {
? path.join( ? path.join(
"\\\\?\\pipe", "\\\\?\\pipe",
process.dirname, 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 // Cleanup when worker process exits
@ -174,7 +174,7 @@ if (!process.singleThreaded) {
fakeParam2, fakeParam2,
fakeParam3, fakeParam3,
fakeParam4, fakeParam4,
tries, tries
) { ) {
if (!tries) tries = 0; if (!tries) tries = 0;
@ -185,12 +185,12 @@ if (!process.singleThreaded) {
? path.join( ? path.join(
"\\\\?\\pipe", "\\\\?\\pipe",
process.dirname, process.dirname,
"temp/.W" + newWorker.process.pid + ".ipc", "temp/.W" + newWorker.process.pid + ".ipc"
) )
: process.dirname + "/temp/.W" + newWorker.process.pid + ".ipc", : process.dirname + "/temp/.W" + newWorker.process.pid + ".ipc",
() => { () => {
fakeWorkerIPCConnection.end(message); fakeWorkerIPCConnection.end(message);
}, }
); );
} catch (err) { } catch (err) {
if (tries > 50) throw err; if (tries > 50) throw err;
@ -199,7 +199,7 @@ if (!process.singleThreaded) {
fakeParam2, fakeParam2,
fakeParam3, fakeParam3,
fakeParam4, fakeParam4,
tries + 1, tries + 1
); );
} }
}; };

View file

@ -4,7 +4,7 @@ function createRegex(regex, isPath) {
// The new regular expression supports single unescaped "/" within [], but not two unescaped "/". // 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. // 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( const regexStrMatch = regex.match(
/^\/((?:\\.|\/+(?:(?:\\.|[^\]\\/])*\])|[^/\\])*)\/([a-zA-Z0-9]*)$/, /^\/((?:\\.|\/+(?:(?:\\.|[^\]\\/])*\])|[^/\\])*)\/([a-zA-Z0-9]*)$/
); );
if (!regexStrMatch) throw new Error("Invalid regular expression: " + regex); if (!regexStrMatch) throw new Error("Invalid regular expression: " + regex);
const searchString = regexStrMatch[1]; const searchString = regexStrMatch[1];

View file

@ -65,11 +65,10 @@ function isIndexOfForbiddenPath(decodedHref, match) {
? forbiddenPath.some( ? forbiddenPath.some(
(path) => (path) =>
decodedHrefLower === path.toLowerCase() || decodedHrefLower === path.toLowerCase() ||
decodedHrefLower.indexOf(path.toLowerCase() + "/") == 0, decodedHrefLower.indexOf(path.toLowerCase() + "/") == 0
) )
: forbiddenPath.some( : forbiddenPath.some(
(path) => (path) => decodedHref === path || decodedHref.indexOf(path + "/") == 0
decodedHref === path || decodedHref.indexOf(path + "/") == 0,
); );
} }
@ -83,5 +82,5 @@ module.exports = {
getInitializePath: getInitializePath, getInitializePath: getInitializePath,
isForbiddenPath: isForbiddenPath, isForbiddenPath: isForbiddenPath,
isIndexOfForbiddenPath: isIndexOfForbiddenPath, isIndexOfForbiddenPath: isIndexOfForbiddenPath,
forbiddenPaths: forbiddenPaths, forbiddenPaths: forbiddenPaths
}; };

View file

@ -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 the error stack starts with the error name, return the original stack (it is V8-style then).
if ( if (
errorStack.some( errorStack.some(
(errorStackLine) => errorStackLine.indexOf(errorObject.name) == 0, (errorStackLine) => errorStackLine.indexOf(errorObject.name) == 0
) )
) { ) {
return errorObject.stack; return errorObject.stack;
@ -16,7 +16,7 @@ function generateErrorStack(errorObject) {
let newErrorStack = [ let newErrorStack = [
errorObject.name + errorObject.name +
(errorObject.code ? ": " + errorObject.code : "") + (errorObject.code ? ": " + errorObject.code : "") +
(errorObject.message == "" ? "" : ": " + errorObject.message), (errorObject.message == "" ? "" : ": " + errorObject.message)
]; ];
// Process each line of the original error stack. // Process each line of the original error stack.
@ -37,8 +37,7 @@ function generateErrorStack(errorObject) {
? !location || location == "" ? !location || location == ""
? "<anonymous>" ? "<anonymous>"
: location : location
: func + : func + (!location || location == "" ? "" : " (" + location + ")"))
(!location || location == "" ? "" : " (" + location + ")")),
); );
} }
}); });

View file

@ -6,7 +6,7 @@ function ipBlockList(rawBlockList) {
raw: [], raw: [],
rawtoPreparedMap: [], rawtoPreparedMap: [],
prepared: [], prepared: [],
cidrs: [], cidrs: []
}; };
// Function to normalize IPv4 address (remove leading zeros) // Function to normalize IPv4 address (remove leading zeros)
@ -79,7 +79,7 @@ function ipBlockList(rawBlockList) {
const ipMax = ipMin + exp - 1; const ipMax = ipMin + exp - 1;
return { return {
min: ipMin, min: ipMin,
max: ipMax, max: ipMax
}; };
}; };
@ -106,7 +106,7 @@ function ipBlockList(rawBlockList) {
? i < 7 - fieldsToDelete ? i < 7 - fieldsToDelete
? ipBlocks[i] ? ipBlocks[i]
: (ipBlocks[i] >> fieldMaskModify) << fieldMaskModify : (ipBlocks[i] >> fieldMaskModify) << fieldMaskModify
: 0, : 0
); );
} }
for (let i = 0; i < 8; i++) { for (let i = 0; i < 8; i++) {
@ -117,12 +117,12 @@ function ipBlockList(rawBlockList) {
: ((ipBlocks[i] >> fieldMaskModify) << fieldMaskModify) + : ((ipBlocks[i] >> fieldMaskModify) << fieldMaskModify) +
Math.pow(2, fieldMaskModify) - Math.pow(2, fieldMaskModify) -
1 1
: 65535, : 65535
); );
} }
return { return {
min: ipBlockMin, min: ipBlockMin,
max: ipBlockMax, max: ipBlockMax
}; };
}; };
@ -183,13 +183,13 @@ function ipBlockList(rawBlockList) {
instance.cidrs.push(cidrLimits); instance.cidrs.push(cidrLimits);
instance.rawtoPreparedMap.push({ instance.rawtoPreparedMap.push({
cidr: true, cidr: true,
index: cidrIndex, index: cidrIndex
}); });
} else { } else {
instance.prepared.push(rawValue); instance.prepared.push(rawValue);
instance.rawtoPreparedMap.push({ instance.rawtoPreparedMap.push({
cidr: false, cidr: false,
index: beginIndex, index: beginIndex
}); });
} }
}; };

View file

@ -2,7 +2,7 @@ function calculateBroadcastIPv4FromCidr(ipWithCidr) {
// Check if CIDR notation is valid, if it's not, return null // Check if CIDR notation is valid, if it's not, return null
if (!ipWithCidr) return null; if (!ipWithCidr) return null;
const ipCA = ipWithCidr.match( 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; if (!ipCA) return null;
@ -27,7 +27,7 @@ function calculateNetworkIPv4FromCidr(ipWithCidr) {
// Check if CIDR notation is valid, if it's not, return null // Check if CIDR notation is valid, if it's not, return null
if (!ipWithCidr) return null; if (!ipWithCidr) return null;
const ipCA = ipWithCidr.match( 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; if (!ipCA) return null;
@ -50,5 +50,5 @@ function calculateNetworkIPv4FromCidr(ipWithCidr) {
module.exports = { module.exports = {
calculateBroadcastIPv4FromCidr: calculateBroadcastIPv4FromCidr, calculateBroadcastIPv4FromCidr: calculateBroadcastIPv4FromCidr,
calculateNetworkIPv4FromCidr: calculateNetworkIPv4FromCidr, calculateNetworkIPv4FromCidr: calculateNetworkIPv4FromCidr
}; };

View file

@ -3,7 +3,7 @@ try {
formidable = require("formidable"); formidable = require("formidable");
} catch (err) { } catch (err) {
formidable = { formidable = {
_errored: err, _errored: err
}; };
} }
@ -78,7 +78,7 @@ module.exports = (legacyMod) => {
req.originalParsedURL.pathname, // origHref req.originalParsedURL.pathname, // origHref
res.redirect, // redirect res.redirect, // redirect
parsePostData, // parsePostData parsePostData, // parsePostData
req.authUser, // authUser req.authUser // authUser
)(); )();
}; };
@ -90,7 +90,7 @@ module.exports = (legacyMod) => {
head, // head head, // head
config, // configJSON config, // configJSON
logFacilities, // serverconsole logFacilities, // serverconsole
next, // elseCallback next // elseCallback
)(); )();
}; };
} }

View file

@ -3,7 +3,7 @@ const svrjsInfo = require("../../svrjs.json");
const { version, statisticsServerCollectEndpoint } = svrjsInfo; const { version, statisticsServerCollectEndpoint } = svrjsInfo;
let crypto = { let crypto = {
__disabled__: null, __disabled__: null
}; };
let https = { let https = {
createServer: () => { createServer: () => {
@ -14,7 +14,7 @@ let https = {
}, },
get: () => { get: () => {
throw new Error("Crypto support is not present"); throw new Error("Crypto support is not present");
}, }
}; };
try { try {
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
@ -30,7 +30,7 @@ function sendStatistics(modInfos, callback) {
version: version, version: version,
runtime: process.isBun ? "Bun" : "Node.js", runtime: process.isBun ? "Bun" : "Node.js",
runtimeVersion: process.isBun ? process.versions.bun : process.version, runtimeVersion: process.isBun ? process.versions.bun : process.version,
mods: modInfos, mods: modInfos
}); });
const statisticsRequest = https.request( const statisticsRequest = https.request(
statisticsServerCollectEndpoint, statisticsServerCollectEndpoint,
@ -39,8 +39,8 @@ function sendStatistics(modInfos, callback) {
headers: { headers: {
"User-Agent": generateServerString(true), "User-Agent": generateServerString(true),
"Content-Type": "application/json", "Content-Type": "application/json",
"Content-Length": Buffer.byteLength(statisticsToSend), "Content-Length": Buffer.byteLength(statisticsToSend)
}, }
}, },
(res) => { (res) => {
const statusCode = res.statusCode; const statusCode = res.statusCode;
@ -65,7 +65,7 @@ function sendStatistics(modInfos, callback) {
callback(err); callback(err);
} }
}); });
}, }
); );
statisticsRequest.on("error", (err) => { statisticsRequest.on("error", (err) => {
callback(err); callback(err);

View file

@ -23,7 +23,7 @@ function LOG(s) {
"-" + "-" +
timestamp + timestamp +
".log", ".log",
"[" + new Date().toISOString() + "] " + s + "\r\n", "[" + new Date().toISOString() + "] " + s + "\r\n"
); );
} else { } else {
if (!logFile) { if (!logFile) {
@ -40,19 +40,19 @@ function LOG(s) {
".log", ".log",
{ {
flags: "a", flags: "a",
autoClose: false, autoClose: false
}, }
); );
logFile.on("error", (err) => { logFile.on("error", (err) => {
if ( if (
!s.match( !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 !reallyExiting
) )
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
"There was a problem while saving logs! Logs will not be kept in log file. Reason: " + "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) { } catch (err) {
if ( if (
!s.match( !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 !reallyExiting
) )
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
"There was a problem while saving logs! Logs will not be kept in log file. Reason: " + "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" + "\x1b[1mSERVER CLI MESSAGE\x1b[22m" +
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg, msg
); );
LOG( LOG(
"SERVER CLI MESSAGE" + "SERVER CLI MESSAGE" +
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg, msg
); );
return; return;
}, },
@ -112,13 +112,13 @@ const serverconsole = {
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg + msg +
"\x1b[37m\x1b[0m", "\x1b[37m\x1b[0m"
); );
LOG( LOG(
"SERVER REQUEST MESSAGE" + "SERVER REQUEST MESSAGE" +
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg, msg
); );
return; return;
}, },
@ -134,13 +134,13 @@ const serverconsole = {
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg + msg +
"\x1b[37m\x1b[0m", "\x1b[37m\x1b[0m"
); );
LOG( LOG(
"SERVER RESPONSE MESSAGE" + "SERVER RESPONSE MESSAGE" +
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg, msg
); );
return; return;
}, },
@ -156,13 +156,13 @@ const serverconsole = {
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg + msg +
"\x1b[37m\x1b[0m", "\x1b[37m\x1b[0m"
); );
LOG( LOG(
"SERVER RESPONSE ERROR MESSAGE" + "SERVER RESPONSE ERROR MESSAGE" +
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg, msg
); );
return; return;
}, },
@ -178,13 +178,13 @@ const serverconsole = {
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg + msg +
"\x1b[40m\x1b[0m", "\x1b[40m\x1b[0m"
); );
LOG( LOG(
"SERVER ERROR MESSAGE" + "SERVER ERROR MESSAGE" +
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg, msg
); );
return; return;
}, },
@ -200,13 +200,13 @@ const serverconsole = {
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg + msg +
"\x1b[40m\x1b[0m", "\x1b[40m\x1b[0m"
); );
LOG( LOG(
"SERVER WARNING MESSAGE" + "SERVER WARNING MESSAGE" +
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg, msg
); );
return; return;
}, },
@ -221,19 +221,19 @@ const serverconsole = {
"\x1b[1mSERVER MESSAGE\x1b[22m" + "\x1b[1mSERVER MESSAGE\x1b[22m" +
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg, msg
); );
LOG( LOG(
"SERVER MESSAGE" + "SERVER MESSAGE" +
(reqId ? " [Request Id: " + reqId + "]" : "") + (reqId ? " [Request Id: " + reqId + "]" : "") +
": " + ": " +
msg, msg
); );
return; return;
}, },
setProcessExiting: (state) => { setProcessExiting: (state) => {
reallyExiting = state; reallyExiting = state;
}, }
}; };
// Wrap around process.exit, so that log contents can be flushed. // Wrap around process.exit, so that log contents can be flushed.

View file

@ -96,7 +96,7 @@ function sha256(s) {
0x90befffa, 0x90befffa,
0xa4506ceb, 0xa4506ceb,
0xbef9a3f7, 0xbef9a3f7,
0xc67178f2, 0xc67178f2
); );
let HASH = new Array( let HASH = new Array(
0x6a09e667, 0x6a09e667,
@ -106,7 +106,7 @@ function sha256(s) {
0x510e527f, 0x510e527f,
0x9b05688c, 0x9b05688c,
0x1f83d9ab, 0x1f83d9ab,
0x5be0cd19, 0x5be0cd19
); );
let W = new Array(64); let W = new Array(64);
let a, b, c, d, e, f, g, h; let a, b, c, d, e, f, g, h;
@ -131,14 +131,14 @@ function sha256(s) {
W[j] = safeAdd( W[j] = safeAdd(
safeAdd( safeAdd(
safeAdd(Gamma1256(W[j - 2]), W[j - 7]), safeAdd(Gamma1256(W[j - 2]), W[j - 7]),
Gamma0256(W[j - 15]), Gamma0256(W[j - 15])
), ),
W[j - 16], W[j - 16]
); );
T1 = safeAdd( T1 = safeAdd(
safeAdd(safeAdd(safeAdd(h, Sigma1256(e)), Ch(e, f, g)), K[j]), safeAdd(safeAdd(safeAdd(h, Sigma1256(e)), Ch(e, f, g)), K[j]),
W[j], W[j]
); );
T2 = safeAdd(Sigma0256(a), Maj(a, b, c)); T2 = safeAdd(Sigma0256(a), Maj(a, b, c));

View file

@ -5,12 +5,12 @@ function sizify(bytes, addI) {
const prefixes = ["", "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"]; const prefixes = ["", "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"];
const prefixIndex = Math.min( const prefixIndex = Math.min(
Math.floor(Math.log2(bytes) / 10), Math.floor(Math.log2(bytes) / 10),
prefixes.length - 1, prefixes.length - 1
); );
const prefixIndexTranslated = Math.pow(2, 10 * prefixIndex); const prefixIndexTranslated = Math.pow(2, 10 * prefixIndex);
const decimalPoints = Math.max( const decimalPoints = Math.max(
2 - Math.floor(Math.log10(bytes / prefixIndexTranslated)), 2 - Math.floor(Math.log10(bytes / prefixIndexTranslated)),
0, 0
); );
const size = const size =

View file

@ -13,7 +13,7 @@ function parseURL(uri, prepend) {
// Parse the URL using regular expression // Parse the URL using regular expression
let parsedURI = uri.match( let parsedURI = uri.match(
/^(?:([^:]+:)(\/\/)?)?(?:([^@/?#*]+)@)?([^:/?#*]+|\[[^*\]/]\])?(?::([0-9]+))?(\*|\/[^?#]*)?(\?[^#]*)?(#[\S\s]*)?/, /^(?:([^:]+:)(\/\/)?)?(?:([^@/?#*]+)@)?([^:/?#*]+|\[[^*\]/]\])?(?::([0-9]+))?(\*|\/[^?#]*)?(\?[^#]*)?(#[\S\s]*)?/
); );
// Match 1: protocol // Match 1: protocol
// Match 2: slashes after protocol // Match 2: slashes after protocol

View file

@ -13,12 +13,12 @@ middleware.mockImplementation(() => {
check: ipBlockListCheck, check: ipBlockListCheck,
add: ipBlockListAdd, add: ipBlockListAdd,
remove: ipBlockListRemove, remove: ipBlockListRemove,
raw: [], raw: []
}; };
}); });
process.serverConfig = { process.serverConfig = {
blacklist: [], blacklist: []
}; };
const blocklistMiddleware = require("../../src/middleware/blocklist.js"); const blocklistMiddleware = require("../../src/middleware/blocklist.js");
@ -30,14 +30,14 @@ describe("Blocklist middleware", () => {
req = { req = {
socket: { socket: {
realRemoteAddress: "127.0.0.1", realRemoteAddress: "127.0.0.1",
remoteAddress: "127.0.0.1", remoteAddress: "127.0.0.1"
}, }
}; };
res = { res = {
error: jest.fn(), error: jest.fn()
}; };
logFacilities = { logFacilities = {
errmessage: jest.fn(), errmessage: jest.fn()
}; };
config = {}; config = {};
next = jest.fn(); next = jest.fn();
@ -63,7 +63,7 @@ describe("Blocklist middleware", () => {
expect(next).not.toHaveBeenCalled(); expect(next).not.toHaveBeenCalled();
expect(res.error).toHaveBeenCalledWith(403); expect(res.error).toHaveBeenCalledWith(403);
expect(logFacilities.errmessage).toHaveBeenCalledWith( expect(logFacilities.errmessage).toHaveBeenCalledWith(
"Client is in the block list.", "Client is in the block list."
); );
}); });

View file

@ -11,13 +11,13 @@ jest.mock("../../src/utils/forbiddenPaths.js", () => ({
serverSideScripts: ["/forbidden"], serverSideScripts: ["/forbidden"],
serverSideScriptDirectories: ["/forbidden"], serverSideScriptDirectories: ["/forbidden"],
temp: "/forbidden", temp: "/forbidden",
log: "/forbidden", log: "/forbidden"
}, }
})); }));
process.serverConfig = { process.serverConfig = {
secure: true, secure: true,
sni: [], sni: []
}; };
process.dirname = "/usr/lib/mocksvrjs"; process.dirname = "/usr/lib/mocksvrjs";
@ -31,19 +31,19 @@ describe("Forbidden path checking middleware", () => {
beforeEach(() => { beforeEach(() => {
req = { req = {
parsedURL: { pathname: "/forbidden" }, parsedURL: { pathname: "/forbidden" },
isProxy: false, isProxy: false
}; };
res = { res = {
error: jest.fn(), error: jest.fn()
}; };
logFacilities = { logFacilities = {
errmessage: jest.fn(), errmessage: jest.fn()
}; };
config = { config = {
enableLogging: true, enableLogging: true,
enableRemoteLogBrowsing: false, enableRemoteLogBrowsing: false,
exposeServerVersion: false, exposeServerVersion: false,
disableServerSideScriptExpose: true, disableServerSideScriptExpose: true
}; };
next = jest.fn(); next = jest.fn();
}); });

View file

@ -8,11 +8,11 @@ describe("Default handler checks middleware", () => {
req = httpMocks.createRequest(); req = httpMocks.createRequest();
res = httpMocks.createResponse(); res = httpMocks.createResponse();
logFacilities = { logFacilities = {
errmessage: jest.fn(), errmessage: jest.fn()
}; };
config = { config = {
getCustomHeaders: jest.fn(() => ({})), getCustomHeaders: jest.fn(() => ({})),
generateServerString: jest.fn(() => "Server String"), generateServerString: jest.fn(() => "Server String")
}; };
next = jest.fn(); next = jest.fn();
}); });
@ -22,7 +22,7 @@ describe("Default handler checks middleware", () => {
middleware(req, res, logFacilities, config, next); middleware(req, res, logFacilities, config, next);
expect(res._getStatusCode()).toBe(501); expect(res._getStatusCode()).toBe(501);
expect(logFacilities.errmessage).toHaveBeenCalledWith( 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._getStatusCode()).toBe(204);
expect(res._getHeaders()).toHaveProperty( expect(res._getHeaders()).toHaveProperty(
"allow", "allow",
"GET, POST, HEAD, OPTIONS", "GET, POST, HEAD, OPTIONS"
); );
}); });
@ -42,7 +42,7 @@ describe("Default handler checks middleware", () => {
middleware(req, res, logFacilities, config, next); middleware(req, res, logFacilities, config, next);
expect(res.error).toHaveBeenCalledWith(405); expect(res.error).toHaveBeenCalledWith(405);
expect(logFacilities.errmessage).toHaveBeenCalledWith( expect(logFacilities.errmessage).toHaveBeenCalledWith(
expect.stringContaining("Invaild method: PUT"), expect.stringContaining("Invaild method: PUT")
); );
}); });

View file

@ -22,7 +22,7 @@ jest.mock("crypto", () => {
pbkdf2: jest.fn((password, salt, iterations, keylen, digest, callback) => { pbkdf2: jest.fn((password, salt, iterations, keylen, digest, callback) => {
// Mock implementation for crypto.pbkdf2 // Mock implementation for crypto.pbkdf2
callback(null, Buffer.from(mockPbkdf2Hash)); callback(null, Buffer.from(mockPbkdf2Hash));
}), })
// Add other properties or methods of crypto module if needed // Add other properties or methods of crypto module if needed
}; };
}); });
@ -34,15 +34,15 @@ process.serverConfig = {
ip: "192.168.1.1", ip: "192.168.1.1",
url: "/test/path", url: "/test/path",
scode: 403, scode: 403,
users: ["127.0.0.1"], users: ["127.0.0.1"]
}, },
{ {
host: "example.com", host: "example.com",
ip: "192.168.1.1", ip: "192.168.1.1",
url: "/test/path2", url: "/test/path2",
scode: 401, scode: 401
}, }
], ]
}; };
process.messageEventListeners = []; process.messageEventListeners = [];
@ -58,32 +58,32 @@ describe("Non-standard codes and HTTP authentication middleware", () => {
req = { req = {
socket: { socket: {
realRemoteAddress: "127.0.0.1", realRemoteAddress: "127.0.0.1",
localAddress: "192.168.1.1", localAddress: "192.168.1.1"
}, },
parsedURL: { parsedURL: {
pathname: "/test/path", pathname: "/test/path"
}, },
url: "/test/path", url: "/test/path",
headers: { headers: {
host: "example.com", host: "example.com"
}, },
isProxy: false, isProxy: false
}; };
res = { res = {
error: jest.fn(), error: jest.fn(),
redirect: jest.fn(), redirect: jest.fn()
}; };
logFacilities = { logFacilities = {
errmessage: jest.fn(), errmessage: jest.fn(),
reqmessage: jest.fn(), reqmessage: jest.fn()
}; };
config = { config = {
getCustomHeaders: jest.fn(), getCustomHeaders: jest.fn(),
users: [], users: []
}; };
next = jest.fn(); next = jest.fn();
process.serverConfig = { process.serverConfig = {
nonStandardCodes: [], nonStandardCodes: []
}; };
cluster.isPrimary = true; cluster.isPrimary = true;
@ -92,7 +92,7 @@ describe("Non-standard codes and HTTP authentication middleware", () => {
test("should handle non-standard codes", () => { test("should handle non-standard codes", () => {
ipBlockList.mockReturnValue({ ipBlockList.mockReturnValue({
check: jest.fn().mockReturnValue(true), check: jest.fn().mockReturnValue(true)
}); });
matchHostname.mockReturnValue(true); matchHostname.mockReturnValue(true);
ipMatch.mockReturnValue(true); ipMatch.mockReturnValue(true);
@ -112,8 +112,8 @@ describe("Non-standard codes and HTTP authentication middleware", () => {
{ {
name: "test", name: "test",
pass: "test", pass: "test",
salt: "test", salt: "test"
}, }
]; ];
sha256.mockReturnValue("test"); sha256.mockReturnValue("test");
req.headers.authorization = "Basic dGVzdDp0ZXN0"; req.headers.authorization = "Basic dGVzdDp0ZXN0";
@ -122,7 +122,7 @@ describe("Non-standard codes and HTTP authentication middleware", () => {
expect(next).toHaveBeenCalled(); expect(next).toHaveBeenCalled();
expect(logFacilities.reqmessage).toHaveBeenCalledWith( 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", name: "test",
pass: "test2", pass: "test2",
salt: "test", salt: "test"
}, }
]; ];
sha256.mockReturnValue("test"); sha256.mockReturnValue("test");
req.headers.authorization = "Basic dGVzdDp0ZXN0"; req.headers.authorization = "Basic dGVzdDp0ZXN0";
@ -150,7 +150,7 @@ describe("Non-standard codes and HTTP authentication middleware", () => {
expect(next).not.toHaveBeenCalled(); expect(next).not.toHaveBeenCalled();
expect(logFacilities.errmessage).toHaveBeenCalledWith( 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", name: "test",
pass: "74657374", // "test" converted to hex pass: "74657374", // "test" converted to hex
salt: "test", salt: "test",
scrypt: true, scrypt: true
}, }
]; ];
mockScryptHash = "test"; mockScryptHash = "test";
req.headers.authorization = "Basic dGVzdDp0ZXN0"; req.headers.authorization = "Basic dGVzdDp0ZXN0";
@ -174,7 +174,7 @@ describe("Non-standard codes and HTTP authentication middleware", () => {
expect(next).toHaveBeenCalled(); expect(next).toHaveBeenCalled();
expect(logFacilities.reqmessage).toHaveBeenCalledWith( 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", name: "test",
pass: "74657374", // "test" converted to hex pass: "74657374", // "test" converted to hex
salt: "test", salt: "test",
pbkdf2: true, pbkdf2: true
}, }
]; ];
mockPbkdf2Hash = "test"; mockPbkdf2Hash = "test";
req.headers.authorization = "Basic dGVzdDp0ZXN0"; req.headers.authorization = "Basic dGVzdDp0ZXN0";
@ -198,7 +198,7 @@ describe("Non-standard codes and HTTP authentication middleware", () => {
expect(next).toHaveBeenCalled(); expect(next).toHaveBeenCalled();
expect(logFacilities.reqmessage).toHaveBeenCalledWith( 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", name: "test",
pass: "test", pass: "test",
salt: "test", salt: "test"
}, }
]; ];
sha256.mockReturnValue("test"); sha256.mockReturnValue("test");
req.headers.authorization = "Basic dGVzdDp0ZXN0"; req.headers.authorization = "Basic dGVzdDp0ZXN0";
@ -255,7 +255,7 @@ describe("Non-standard codes and HTTP authentication middleware", () => {
const mockWorker = { const mockWorker = {
send: (msg) => { send: (msg) => {
mockHandlers.forEach((handler) => handler(msg)); mockHandlers.forEach((handler) => handler(msg));
}, }
}; };
const mockServerConsole = { const mockServerConsole = {
climessage: () => {}, climessage: () => {},
@ -264,10 +264,10 @@ describe("Non-standard codes and HTTP authentication middleware", () => {
errmessage: () => {}, errmessage: () => {},
locerrmessage: () => {}, locerrmessage: () => {},
locwarnmessage: () => {}, locwarnmessage: () => {},
locmessage: () => {}, locmessage: () => {}
}; };
process.messageEventListeners.forEach((listenerWrapper) => 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(next).toHaveBeenCalled();
expect(logFacilities.reqmessage).toHaveBeenCalledWith( expect(logFacilities.reqmessage).toHaveBeenCalledWith(
'Client is logged in as "test".', 'Client is logged in as "test".'
); );
}); });
}); });

View file

@ -10,11 +10,11 @@ describe("Trailing slash redirection middleware", () => {
req = { req = {
isProxy: false, isProxy: false,
parsedURL: { pathname: "/test", search: "?query=1", hash: "#hash" }, parsedURL: { pathname: "/test", search: "?query=1", hash: "#hash" },
originalParsedURL: { pathname: "/test" }, originalParsedURL: { pathname: "/test" }
}; };
res = { res = {
redirect: jest.fn(), redirect: jest.fn(),
error: jest.fn(), error: jest.fn()
}; };
logFacilities = {}; logFacilities = {};
config = { disableTrailingSlashRedirects: false }; config = { disableTrailingSlashRedirects: false };

View file

@ -8,14 +8,14 @@ describe("Redirects middleware", () => {
headers: {}, headers: {},
socket: { encrypted: false, remoteAddress: "8.8.8.8" }, socket: { encrypted: false, remoteAddress: "8.8.8.8" },
isProxy: false, isProxy: false,
url: "/test", url: "/test"
}; };
res = { res = {
redirect: jest.fn(), redirect: jest.fn(),
error: jest.fn(), error: jest.fn()
}; };
logFacilities = { logFacilities = {
errmessage: jest.fn(), errmessage: jest.fn()
}; };
config = { config = {
secure: true, secure: true,
@ -25,7 +25,7 @@ describe("Redirects middleware", () => {
sport: 443, sport: 443,
spubport: 8443, spubport: 8443,
wwwredirect: true, wwwredirect: true,
domain: "example.com", domain: "example.com"
}; };
next = jest.fn(); next = jest.fn();
}); });

View file

@ -8,7 +8,7 @@ describe("Response header setting middleware", () => {
res = { setHeader: jest.fn() }; res = { setHeader: jest.fn() };
next = jest.fn(); next = jest.fn();
config = { config = {
getCustomHeaders: jest.fn(() => ({ "X-Custom-Header": "custom-value" })), getCustomHeaders: jest.fn(() => ({ "X-Custom-Header": "custom-value" }))
}; };
logFacilities = {}; logFacilities = {};
}); });
@ -18,7 +18,7 @@ describe("Response header setting middleware", () => {
expect(res.setHeader).toHaveBeenCalledWith( expect(res.setHeader).toHaveBeenCalledWith(
"X-Custom-Header", "X-Custom-Header",
"custom-value", "custom-value"
); );
expect(next).toHaveBeenCalled(); expect(next).toHaveBeenCalled();
}); });

View file

@ -17,40 +17,40 @@ describe("rewriteURL middleware", () => {
parsedURL: { parsedURL: {
pathname: "/test", pathname: "/test",
search: "", search: "",
hash: "", hash: ""
}, },
url: "/test", url: "/test",
headers: { headers: {
host: "test.com", host: "test.com"
}, },
socket: { socket: {
encrypted: false, encrypted: false,
localAddress: "127.0.0.1", localAddress: "127.0.0.1"
}, }
}; };
res = { res = {
error: jest.fn(), error: jest.fn()
}; };
logFacilities = { logFacilities = {
resmessage: jest.fn(), resmessage: jest.fn(),
errmessage: jest.fn(), errmessage: jest.fn()
}; };
config = { config = {
rewriteMap: [], rewriteMap: [],
domain: "test.com", domain: "test.com",
allowDoubleSlashes: false, allowDoubleSlashes: false
}; };
next = jest.fn(); next = jest.fn();
// Make mocks call actual functions // Make mocks call actual functions
createRegex.mockImplementation((...params) => createRegex.mockImplementation((...params) =>
jest.requireActual("../../src/utils/createRegex.js")(...params), jest.requireActual("../../src/utils/createRegex.js")(...params)
); );
parseURL.mockImplementation((...params) => parseURL.mockImplementation((...params) =>
jest.requireActual("../../src/utils/urlParser.js")(...params), jest.requireActual("../../src/utils/urlParser.js")(...params)
); );
sanitizeURL.mockImplementation((...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: [ replacements: [
{ {
regex: "/.*/", regex: "/.*/",
replacement: "error", replacement: "error"
}, }
], ]
}, }
]; ];
createRegex.mockImplementation(() => { createRegex.mockImplementation(() => {
throw new Error("Test error"); throw new Error("Test error");
@ -93,10 +93,10 @@ describe("rewriteURL middleware", () => {
replacements: [ replacements: [
{ {
regex: "/.*/", regex: "/.*/",
replacement: "/new", replacement: "/new"
}, }
], ]
}, }
]; ];
parseURL.mockImplementation(() => { parseURL.mockImplementation(() => {
throw new Error("Test error"); throw new Error("Test error");
@ -113,10 +113,10 @@ describe("rewriteURL middleware", () => {
replacements: [ replacements: [
{ {
regex: "/.*/", regex: "/.*/",
replacement: "/new", replacement: "/new"
}, }
], ]
}, }
]; ];
sanitizeURL.mockReturnValue("/sanitized"); sanitizeURL.mockReturnValue("/sanitized");
middleware(req, res, logFacilities, config, next); middleware(req, res, logFacilities, config, next);
@ -132,10 +132,10 @@ describe("rewriteURL middleware", () => {
replacements: [ replacements: [
{ {
regex: "/.*/", regex: "/.*/",
replacement: "/new", replacement: "/new"
}, }
], ]
}, }
]; ];
middleware(req, res, logFacilities, config, next); middleware(req, res, logFacilities, config, next);
expect(next).toHaveBeenCalled(); expect(next).toHaveBeenCalled();

View file

@ -15,20 +15,20 @@ describe("Static file serving and directory listings middleware", () => {
headers: { headers: {
host: "example.com", host: "example.com",
"accept-encoding": "gzip, deflate, br", "accept-encoding": "gzip, deflate, br",
"user-agent": "Mozilla/5.0", "user-agent": "Mozilla/5.0"
}, },
socket: { socket: {
localAddress: "127.0.0.1", localAddress: "127.0.0.1"
}, }
}); });
req.parsedURL = { req.parsedURL = {
pathname: "/", pathname: "/"
}; };
req.originalParsedURL = { req.originalParsedURL = {
pathname: "/", pathname: "/"
}; };
res = httpMocks.createResponse({ res = httpMocks.createResponse({
eventEmitter: require("events").EventEmitter, eventEmitter: require("events").EventEmitter
}); });
res.error = (statusCode) => { res.error = (statusCode) => {
// Very simple replacement of res.error // Very simple replacement of res.error
@ -39,14 +39,14 @@ describe("Static file serving and directory listings middleware", () => {
res.foot = ""; res.foot = "";
logFacilities = { logFacilities = {
errmessage: jest.fn(), errmessage: jest.fn(),
resmessage: jest.fn(), resmessage: jest.fn()
}; };
config = { config = {
enableDirectoryListing: true, enableDirectoryListing: true,
enableDirectoryListingVHost: [], enableDirectoryListingVHost: [],
enableCompression: true, enableCompression: true,
dontCompress: [], dontCompress: [],
generateServerString: jest.fn().mockReturnValue("Server"), generateServerString: jest.fn().mockReturnValue("Server")
}; };
next = jest.fn(); next = jest.fn();
}); });
@ -64,7 +64,7 @@ describe("Static file serving and directory listings middleware", () => {
expect(res.statusCode).toBe(404); expect(res.statusCode).toBe(404);
expect(logFacilities.errmessage).toHaveBeenCalledWith( 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(res.statusCode).toBe(403);
expect(logFacilities.errmessage).toHaveBeenCalledWith( 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(res.statusCode).toBe(508);
expect(logFacilities.errmessage).toHaveBeenCalledWith( 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, { cb(null, {
isDirectory: () => false, isDirectory: () => false,
isFile: () => 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(res.statusCode).toBe(501);
expect(logFacilities.errmessage).toHaveBeenCalledWith( 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, isDirectory: () => false,
isFile: () => true, isFile: () => true,
size: 1024, size: 1024,
mtime: new Date(), mtime: new Date()
}); });
} }
}); });
@ -198,7 +198,7 @@ describe("Static file serving and directory listings middleware", () => {
cb(null, { cb(null, {
isDirectory: () => false, isDirectory: () => false,
isFile: () => true, isFile: () => true,
size: 9, size: 9
}); });
} }
}); });
@ -229,7 +229,7 @@ describe("Static file serving and directory listings middleware", () => {
destStream.end("mock data"); destStream.end("mock data");
} }
return destStream; return destStream;
}, }
}; };
fs.createReadStream.mockImplementation(() => { fs.createReadStream.mockImplementation(() => {

View file

@ -8,18 +8,18 @@ describe("Status middleware", () => {
beforeEach(() => { beforeEach(() => {
req = { req = {
parsedURL: { pathname: "/svrjsstatus.svr" }, parsedURL: { pathname: "/svrjsstatus.svr" },
headers: { host: "localhost" }, headers: { host: "localhost" }
}; };
res = { res = {
writeHead: jest.fn(), writeHead: jest.fn(),
end: jest.fn(), end: jest.fn(),
head: "", head: "",
foot: "", foot: ""
}; };
logFacilities = {}; logFacilities = {};
config = { config = {
allowStatus: true, allowStatus: true,
generateServerString: () => "Test Server", generateServerString: () => "Test Server"
}; };
next = jest.fn(); next = jest.fn();
process.reqcounter = 100; process.reqcounter = 100;
@ -35,7 +35,7 @@ describe("Status middleware", () => {
test("should set response headers and body when conditions are met", () => { test("should set response headers and body when conditions are met", () => {
middleware(req, res, logFacilities, config, next); middleware(req, res, logFacilities, config, next);
expect(res.writeHead).toHaveBeenCalledWith(200, http.STATUS_CODES[200], { 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(); expect(res.end).toHaveBeenCalled();
}); });
@ -51,7 +51,7 @@ describe("Status middleware", () => {
jest.spyOn(os, "platform").mockReturnValue("win32"); jest.spyOn(os, "platform").mockReturnValue("win32");
middleware(req, res, logFacilities, config, next); middleware(req, res, logFacilities, config, next);
expect(res.writeHead).toHaveBeenCalledWith(200, http.STATUS_CODES[200], { 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(); expect(res.end).toHaveBeenCalled();
os.platform.mockRestore(); os.platform.mockRestore();
@ -61,7 +61,7 @@ describe("Status middleware", () => {
req.headers.host = undefined; req.headers.host = undefined;
middleware(req, res, logFacilities, config, next); middleware(req, res, logFacilities, config, next);
expect(res.writeHead).toHaveBeenCalledWith(200, http.STATUS_CODES[200], { 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(); expect(res.end).toHaveBeenCalled();
}); });

View file

@ -13,28 +13,28 @@ describe("Path sanitizer middleware", () => {
parsedURL: { parsedURL: {
pathname: "/test", pathname: "/test",
search: "?query=test", search: "?query=test",
hash: "#hash", hash: "#hash"
}, },
url: "/test?query=test#hash", url: "/test?query=test#hash",
isProxy: false, isProxy: false,
headers: { headers: {
host: "test.com", host: "test.com"
}, },
socket: { socket: {
encrypted: false, encrypted: false
}, }
}; };
res = { res = {
redirect: jest.fn(), redirect: jest.fn(),
error: jest.fn(), error: jest.fn()
}; };
logFacilities = { logFacilities = {
resmessage: jest.fn(), resmessage: jest.fn()
}; };
config = { config = {
allowDoubleSlashes: false, allowDoubleSlashes: false,
rewriteDirtyURLs: false, rewriteDirtyURLs: false,
domain: "test.com", domain: "test.com"
}; };
next = jest.fn(); next = jest.fn();
@ -52,7 +52,7 @@ describe("Path sanitizer middleware", () => {
middleware(req, res, logFacilities, config, next); middleware(req, res, logFacilities, config, next);
expect(res.redirect).toHaveBeenCalledWith( expect(res.redirect).toHaveBeenCalledWith(
"/dirty%20url?query=test#hash", "/dirty%20url?query=test#hash",
false, false
); );
expect(next).not.toHaveBeenCalled(); expect(next).not.toHaveBeenCalled();
}); });
@ -71,7 +71,7 @@ describe("Path sanitizer middleware", () => {
middleware(req, res, logFacilities, config, next); middleware(req, res, logFacilities, config, next);
expect(res.redirect).toHaveBeenCalledWith( expect(res.redirect).toHaveBeenCalledWith(
"/clean%20url?query=test#hash", "/clean%20url?query=test#hash",
false, false
); );
expect(next).not.toHaveBeenCalled(); expect(next).not.toHaveBeenCalled();
}); });

View file

@ -14,7 +14,7 @@ describe("Web root prefixes middleware", () => {
url: "/test", url: "/test",
parsedURL: { pathname: "/test" }, parsedURL: { pathname: "/test" },
headers: { host: "test.com" }, headers: { host: "test.com" },
socket: { localAddress: "127.0.0.1" }, socket: { localAddress: "127.0.0.1" }
}; };
res = { error: jest.fn() }; res = { error: jest.fn() };
logFacilities = { resmessage: jest.fn(), errmessage: jest.fn() }; logFacilities = { resmessage: jest.fn(), errmessage: jest.fn() };
@ -22,8 +22,8 @@ describe("Web root prefixes middleware", () => {
allowPostfixDoubleSlashes: true, allowPostfixDoubleSlashes: true,
wwwrootPostfixPrefixesVHost: [], wwwrootPostfixPrefixesVHost: [],
wwwrootPostfixesVHost: [ wwwrootPostfixesVHost: [
{ host: "test.com", ip: "127.0.0.1", postfix: "postfix" }, { host: "test.com", ip: "127.0.0.1", postfix: "postfix" }
], ]
}; };
next = jest.fn(); next = jest.fn();
@ -35,7 +35,7 @@ describe("Web root prefixes middleware", () => {
middleware(req, res, logFacilities, config, next); middleware(req, res, logFacilities, config, next);
expect(req.url).toBe("/postfix/test"); expect(req.url).toBe("/postfix/test");
expect(logFacilities.resmessage).toHaveBeenCalledWith( 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", () => { test("should not add web root postfix if no matching config is found", () => {
config.wwwrootPostfixesVHost = [ 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); middleware(req, res, logFacilities, config, next);
expect(req.url).toBe("/test"); expect(req.url).toBe("/test");

View file

@ -2,7 +2,7 @@ const createRegex = require("../../src/utils/createRegex.js");
const os = require("os"); const os = require("os");
jest.mock("os", () => ({ jest.mock("os", () => ({
platform: jest.fn(), platform: jest.fn()
})); }));
describe("Regular expression creation function", () => { describe("Regular expression creation function", () => {
@ -12,7 +12,7 @@ describe("Regular expression creation function", () => {
test("should throw an error for invalid regular expression", () => { test("should throw an error for invalid regular expression", () => {
expect(() => createRegex("invalid/regex", false)).toThrow( expect(() => createRegex("invalid/regex", false)).toThrow(
"Invalid regular expression: invalid/regex", "Invalid regular expression: invalid/regex"
); );
}); });

View file

@ -63,7 +63,7 @@ describe("Deep cloning function", () => {
const original = { const original = {
a: 1, a: 1,
b: [2, 3, { c: 4 }], b: [2, 3, { c: 4 }],
d: { e: 5, f: [6, { g: 7 }] }, d: { e: 5, f: [6, { g: 7 }] }
}; };
const cloned = deepClone(original); const cloned = deepClone(original);
expect(cloned).toEqual(original); expect(cloned).toEqual(original);

View file

@ -2,12 +2,12 @@ const {
getInitializePath, getInitializePath,
isForbiddenPath, isForbiddenPath,
isIndexOfForbiddenPath, isIndexOfForbiddenPath,
forbiddenPaths, forbiddenPaths
} = require("../../src/utils/forbiddenPaths.js"); } = require("../../src/utils/forbiddenPaths.js");
const os = require("os"); const os = require("os");
jest.mock("os", () => ({ jest.mock("os", () => ({
platform: jest.fn(), platform: jest.fn()
})); }));
describe("Forbidden paths handling", () => { describe("Forbidden paths handling", () => {
@ -16,10 +16,10 @@ describe("Forbidden paths handling", () => {
forbiddenPaths.config = getInitializePath("./config.json"); forbiddenPaths.config = getInitializePath("./config.json");
forbiddenPaths.serverSideScriptDirectories = []; forbiddenPaths.serverSideScriptDirectories = [];
forbiddenPaths.serverSideScriptDirectories.push( forbiddenPaths.serverSideScriptDirectories.push(
getInitializePath("./node_modules"), getInitializePath("./node_modules")
); );
forbiddenPaths.serverSideScriptDirectories.push( forbiddenPaths.serverSideScriptDirectories.push(
getInitializePath("./mods"), getInitializePath("./mods")
); );
process.cwd = () => "/usr/lib/mocksvrjs"; process.cwd = () => "/usr/lib/mocksvrjs";
process.dirname = "/usr/lib/mocksvrjs"; process.dirname = "/usr/lib/mocksvrjs";
@ -43,7 +43,7 @@ describe("Forbidden paths handling", () => {
test("should handle absolute paths on Unix", () => { test("should handle absolute paths on Unix", () => {
os.platform.mockReturnValue("linux"); os.platform.mockReturnValue("linux");
expect(getInitializePath("/absolute/path")).toBe( expect(getInitializePath("/absolute/path")).toBe(
"/../../../absolute/path", "/../../../absolute/path"
); );
}); });
@ -91,13 +91,13 @@ describe("Forbidden paths handling", () => {
test("should handle array of forbidden paths", () => { test("should handle array of forbidden paths", () => {
os.platform.mockReturnValue("linux"); os.platform.mockReturnValue("linux");
expect( expect(
isForbiddenPath("/node_modules", "serverSideScriptDirectories"), isForbiddenPath("/node_modules", "serverSideScriptDirectories")
).toBe(true); ).toBe(true);
expect(isForbiddenPath("/mods", "serverSideScriptDirectories")).toBe( expect(isForbiddenPath("/mods", "serverSideScriptDirectories")).toBe(
true, true
); );
expect( expect(
isForbiddenPath("/notforbidden", "serverSideScriptDirectories"), isForbiddenPath("/notforbidden", "serverSideScriptDirectories")
).toBe(false); ).toBe(false);
}); });
}); });
@ -107,7 +107,7 @@ describe("Forbidden paths handling", () => {
os.platform.mockReturnValue("linux"); os.platform.mockReturnValue("linux");
expect(isIndexOfForbiddenPath("/config.json", "config")).toBe(true); expect(isIndexOfForbiddenPath("/config.json", "config")).toBe(true);
expect( expect(
isIndexOfForbiddenPath("/node_modules/", "serverSideScriptDirectories"), isIndexOfForbiddenPath("/node_modules/", "serverSideScriptDirectories")
).toBe(true); ).toBe(true);
}); });
@ -115,14 +115,14 @@ describe("Forbidden paths handling", () => {
os.platform.mockReturnValue("linux"); os.platform.mockReturnValue("linux");
expect(isIndexOfForbiddenPath("/notconfig.json", "config")).toBe(false); expect(isIndexOfForbiddenPath("/notconfig.json", "config")).toBe(false);
expect( expect(
isIndexOfForbiddenPath("/notforbidden/", "serverSideScriptDirectories"), isIndexOfForbiddenPath("/notforbidden/", "serverSideScriptDirectories")
).toBe(false); ).toBe(false);
expect(isIndexOfForbiddenPath("/config.json.fake", "config")).toBe(false); expect(isIndexOfForbiddenPath("/config.json.fake", "config")).toBe(false);
expect( expect(
isIndexOfForbiddenPath( isIndexOfForbiddenPath(
"/node_modules_fake/", "/node_modules_fake/",
"serverSideScriptDirectories", "serverSideScriptDirectories"
), )
).toBe(false); ).toBe(false);
}); });
@ -133,20 +133,20 @@ describe("Forbidden paths handling", () => {
os.platform.mockReturnValue("win32"); os.platform.mockReturnValue("win32");
expect(isIndexOfForbiddenPath("/CONFIG.JSON", "config")).toBe(true); expect(isIndexOfForbiddenPath("/CONFIG.JSON", "config")).toBe(true);
expect( expect(
isIndexOfForbiddenPath("/NODE_MODULES/", "serverSideScriptDirectories"), isIndexOfForbiddenPath("/NODE_MODULES/", "serverSideScriptDirectories")
).toBe(true); ).toBe(true);
}); });
test("should handle array of forbidden paths", () => { test("should handle array of forbidden paths", () => {
os.platform.mockReturnValue("linux"); os.platform.mockReturnValue("linux");
expect( expect(
isIndexOfForbiddenPath("/node_modules/", "serverSideScriptDirectories"), isIndexOfForbiddenPath("/node_modules/", "serverSideScriptDirectories")
).toBe(true); ).toBe(true);
expect( expect(
isIndexOfForbiddenPath("/mods/", "serverSideScriptDirectories"), isIndexOfForbiddenPath("/mods/", "serverSideScriptDirectories")
).toBe(true); ).toBe(true);
expect( expect(
isIndexOfForbiddenPath("/notforbidden/", "serverSideScriptDirectories"), isIndexOfForbiddenPath("/notforbidden/", "serverSideScriptDirectories")
).toBe(false); ).toBe(false);
}); });
}); });

View file

@ -16,10 +16,10 @@ describe("IP block list functionality", () => {
test("should add and check IPv6 address", () => { test("should add and check IPv6 address", () => {
blockList.add("2001:0db8:85a3:0000:0000:8a2e:0370:7334"); blockList.add("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe( 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( 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", () => { test("should add and check IPv6 CIDR block", () => {
blockList.add("2001:0db8:85a3::/64"); blockList.add("2001:0db8:85a3::/64");
expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe( 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( 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( 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", () => { test("should remove IPv6 address", () => {
blockList.add("2001:0db8:85a3:0000:0000:8a2e:0370:7334"); blockList.add("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe( expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe(
true, true
); );
blockList.remove("2001:0db8:85a3:0000:0000:8a2e:0370:7334"); blockList.remove("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe( 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", () => { test("should remove IPv6 CIDR block", () => {
blockList.add("2001:0db8:85a3::/64"); blockList.add("2001:0db8:85a3::/64");
expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe( expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe(
true, true
); );
blockList.remove("2001:0db8:85a3::/64"); blockList.remove("2001:0db8:85a3::/64");
expect(blockList.check("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe( 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", () => { test("should handle edge cases for IPv6 addresses", () => {
blockList.add("2001:0db8:85a3::/64"); blockList.add("2001:0db8:85a3::/64");
expect(blockList.check("2001:0db8:85a2:ffff:ffff:ffff:ffff:ffff")).toBe( 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( 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( 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( expect(blockList.check("2001:0db8:85a3:0001:0000:0000:0000:0000")).toBe(
false, false
); );
}); });
}); });

View file

@ -29,8 +29,8 @@ describe("IP address matching function", () => {
expect( expect(
ipMatch( ipMatch(
"2001:0db8:85a3:0000:0000:8a2e:0370:7334", "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
"2001:db8:85a3::8a2e:370:7334", "2001:db8:85a3::8a2e:370:7334"
), )
).toBe(true); ).toBe(true);
}); });
@ -38,8 +38,8 @@ describe("IP address matching function", () => {
expect( expect(
ipMatch( ipMatch(
"2001:0db8:85a3:0000:0000:8a2e:0370:7334", "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
"2001:db8:85a3::8a2e:370:7335", "2001:db8:85a3::8a2e:370:7335"
), )
).toBe(false); ).toBe(false);
}); });
@ -58,7 +58,7 @@ describe("IP address matching function", () => {
test("should handle mixed case IP addresses", () => { test("should handle mixed case IP addresses", () => {
expect(ipMatch("192.168.1.1", "192.168.1.1")).toBe(true); expect(ipMatch("192.168.1.1", "192.168.1.1")).toBe(true);
expect( 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); ).toBe(true);
}); });
@ -66,8 +66,8 @@ describe("IP address matching function", () => {
expect( expect(
ipMatch( ipMatch(
"2001:0db8:85a3:0000:0000:8a2e:0370:7334", "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
"2001:db8:85a3::8a2e:370:7334", "2001:db8:85a3::8a2e:370:7334"
), )
).toBe(true); ).toBe(true);
}); });
@ -75,8 +75,8 @@ describe("IP address matching function", () => {
expect( expect(
ipMatch( ipMatch(
"2001:0DB8:85A3:0000:0000:8A2E:0370:7334", "2001:0DB8:85A3:0000:0000:8A2E:0370:7334",
"2001:db8:85a3::8a2e:370:7334", "2001:db8:85a3::8a2e:370:7334"
), )
).toBe(true); ).toBe(true);
}); });
}); });

View file

@ -1,37 +1,37 @@
const { const {
calculateBroadcastIPv4FromCidr, calculateBroadcastIPv4FromCidr,
calculateNetworkIPv4FromCidr, calculateNetworkIPv4FromCidr
} = require("../../src/utils/ipSubnetUtils.js"); } = require("../../src/utils/ipSubnetUtils.js");
describe("IPv4 subnet utilties", () => { describe("IPv4 subnet utilties", () => {
describe("calculateBroadcastIPv4FromCidr", () => { describe("calculateBroadcastIPv4FromCidr", () => {
test("should return the broadcast address for a given CIDR", () => { test("should return the broadcast address for a given CIDR", () => {
expect(calculateBroadcastIPv4FromCidr("192.168.1.0/24")).toBe( expect(calculateBroadcastIPv4FromCidr("192.168.1.0/24")).toBe(
"192.168.1.255", "192.168.1.255"
); );
expect(calculateBroadcastIPv4FromCidr("192.168.1.0/25")).toBe( expect(calculateBroadcastIPv4FromCidr("192.168.1.0/25")).toBe(
"192.168.1.127", "192.168.1.127"
); );
expect(calculateBroadcastIPv4FromCidr("192.168.1.0/26")).toBe( expect(calculateBroadcastIPv4FromCidr("192.168.1.0/26")).toBe(
"192.168.1.63", "192.168.1.63"
); );
expect(calculateBroadcastIPv4FromCidr("192.168.1.0/27")).toBe( expect(calculateBroadcastIPv4FromCidr("192.168.1.0/27")).toBe(
"192.168.1.31", "192.168.1.31"
); );
expect(calculateBroadcastIPv4FromCidr("192.168.1.0/28")).toBe( expect(calculateBroadcastIPv4FromCidr("192.168.1.0/28")).toBe(
"192.168.1.15", "192.168.1.15"
); );
expect(calculateBroadcastIPv4FromCidr("192.168.1.0/29")).toBe( expect(calculateBroadcastIPv4FromCidr("192.168.1.0/29")).toBe(
"192.168.1.7", "192.168.1.7"
); );
expect(calculateBroadcastIPv4FromCidr("192.168.1.0/30")).toBe( expect(calculateBroadcastIPv4FromCidr("192.168.1.0/30")).toBe(
"192.168.1.3", "192.168.1.3"
); );
expect(calculateBroadcastIPv4FromCidr("192.168.1.0/31")).toBe( expect(calculateBroadcastIPv4FromCidr("192.168.1.0/31")).toBe(
"192.168.1.1", "192.168.1.1"
); );
expect(calculateBroadcastIPv4FromCidr("192.168.1.0/32")).toBe( 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", () => { describe("calculateNetworkIPv4FromCidr", () => {
test("should return the network address for a given CIDR", () => { test("should return the network address for a given CIDR", () => {
expect(calculateNetworkIPv4FromCidr("192.168.1.0/24")).toBe( expect(calculateNetworkIPv4FromCidr("192.168.1.0/24")).toBe(
"192.168.1.0", "192.168.1.0"
); );
expect(calculateNetworkIPv4FromCidr("192.168.1.0/25")).toBe( expect(calculateNetworkIPv4FromCidr("192.168.1.0/25")).toBe(
"192.168.1.0", "192.168.1.0"
); );
expect(calculateNetworkIPv4FromCidr("192.168.1.0/26")).toBe( expect(calculateNetworkIPv4FromCidr("192.168.1.0/26")).toBe(
"192.168.1.0", "192.168.1.0"
); );
expect(calculateNetworkIPv4FromCidr("192.168.1.0/27")).toBe( expect(calculateNetworkIPv4FromCidr("192.168.1.0/27")).toBe(
"192.168.1.0", "192.168.1.0"
); );
expect(calculateNetworkIPv4FromCidr("192.168.1.0/28")).toBe( expect(calculateNetworkIPv4FromCidr("192.168.1.0/28")).toBe(
"192.168.1.0", "192.168.1.0"
); );
expect(calculateNetworkIPv4FromCidr("192.168.1.0/29")).toBe( expect(calculateNetworkIPv4FromCidr("192.168.1.0/29")).toBe(
"192.168.1.0", "192.168.1.0"
); );
expect(calculateNetworkIPv4FromCidr("192.168.1.0/30")).toBe( expect(calculateNetworkIPv4FromCidr("192.168.1.0/30")).toBe(
"192.168.1.0", "192.168.1.0"
); );
expect(calculateNetworkIPv4FromCidr("192.168.1.0/31")).toBe( expect(calculateNetworkIPv4FromCidr("192.168.1.0/31")).toBe(
"192.168.1.0", "192.168.1.0"
); );
expect(calculateNetworkIPv4FromCidr("192.168.1.0/32")).toBe( expect(calculateNetworkIPv4FromCidr("192.168.1.0/32")).toBe(
"192.168.1.0", "192.168.1.0"
); );
}); });

View file

@ -5,8 +5,8 @@ const crypto = require("crypto");
jest.mock("crypto", () => ({ jest.mock("crypto", () => ({
createHash: jest.fn(() => ({ createHash: jest.fn(() => ({
update: jest.fn(), update: jest.fn(),
digest: jest.fn(() => "mockedHash"), digest: jest.fn(() => "mockedHash")
})), }))
})); }));
describe("SHA256 hash", () => { describe("SHA256 hash", () => {
@ -20,7 +20,7 @@ describe("SHA256 hash", () => {
crypto.__disabled__ = null; crypto.__disabled__ = null;
const result = sha256("test"); const result = sha256("test");
expect(result).toBe( expect(result).toBe(
"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
); );
}); });
@ -28,7 +28,7 @@ describe("SHA256 hash", () => {
crypto.__disabled__ = null; crypto.__disabled__ = null;
const result = sha256(""); const result = sha256("");
expect(result).toBe( expect(result).toBe(
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
); );
}); });
@ -36,7 +36,7 @@ describe("SHA256 hash", () => {
crypto.__disabled__ = null; crypto.__disabled__ = null;
const result = sha256("!@#$%^&*()"); const result = sha256("!@#$%^&*()");
expect(result).toBe( expect(result).toBe(
"95ce789c5c9d18490972709838ca3a9719094bca3ac16332cfec0652b0236141", "95ce789c5c9d18490972709838ca3a9719094bca3ac16332cfec0652b0236141"
); );
}); });
@ -45,7 +45,7 @@ describe("SHA256 hash", () => {
const longString = "a".repeat(1000); const longString = "a".repeat(1000);
const result = sha256(longString); const result = sha256(longString);
expect(result).toBe( expect(result).toBe(
"41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3", "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3"
); );
}); });
@ -53,7 +53,7 @@ describe("SHA256 hash", () => {
crypto.__disabled__ = null; crypto.__disabled__ = null;
const result = sha256("éñ"); const result = sha256("éñ");
expect(result).toBe( expect(result).toBe(
"c53435f74d8215688e74112f1c6527ad31fd3b72939769a75d09a14cd8a80cfe", "c53435f74d8215688e74112f1c6527ad31fd3b72939769a75d09a14cd8a80cfe"
); );
}); });
}); });

View file

@ -36,7 +36,7 @@ describe("URL mojibake fixer", () => {
test("should handle strings with mixed characters", () => { test("should handle strings with mixed characters", () => {
expect(fixNodeMojibakeURL("hello123 é world ñ!@#$%^&*()")).toBe( expect(fixNodeMojibakeURL("hello123 é world ñ!@#$%^&*()")).toBe(
"hello123 %E9 world %F1!@#$%^&*()", "hello123 %E9 world %F1!@#$%^&*()"
); );
}); });
}); });

View file

@ -62,7 +62,7 @@ describe("URL parser", () => {
test("should parse a URL with all components", () => { test("should parse a URL with all components", () => {
const parsedUrl = parseURL( 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.protocol).toBe("http:");
expect(parsedUrl.auth).toBe("user:pass"); expect(parsedUrl.auth).toBe("user:pass");
@ -74,7 +74,7 @@ describe("URL parser", () => {
expect(parsedUrl.hash).toBe("#fragment"); expect(parsedUrl.hash).toBe("#fragment");
expect(parsedUrl.path).toBe("/path/to/resource?query=string"); expect(parsedUrl.path).toBe("/path/to/resource?query=string");
expect(parsedUrl.href).toBe( 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"
); );
}); });
}); });

View file

@ -20,7 +20,7 @@ for (
) { ) {
console.log("SVR.JS log highlighter usage:"); console.log("SVR.JS log highlighter usage:");
console.log( console.log(
"<some process> | node loghighlight.js [-h] [--help] [-?] [/h] [/?]", "<some process> | node loghighlight.js [-h] [--help] [-?] [/h] [/?]"
); );
console.log("-h -? /h /? --help -- Displays help"); console.log("-h -? /h /? --help -- Displays help");
process.exit(0); process.exit(0);
@ -28,7 +28,7 @@ for (
console.log("Unrecognized argument: " + args[i]); console.log("Unrecognized argument: " + args[i]);
console.log("SVR.JS log highlighter usage:"); console.log("SVR.JS log highlighter usage:");
console.log( console.log(
"<some process> | node loghighlight.js [-h] [--help] [-?] [/h] [/?]", "<some process> | node loghighlight.js [-h] [--help] [-?] [/h] [/?]"
); );
console.log("-h -? /h /? --help -- Displays help"); console.log("-h -? /h /? --help -- Displays help");
process.exit(1); process.exit(1);
@ -39,7 +39,7 @@ const rl = readline.createInterface({
input: process.stdin, input: process.stdin,
output: process.stdout, output: process.stdout,
terminal: false, terminal: false,
prompt: "", prompt: ""
}); });
rl.prompt(); rl.prompt();
rl.on("line", (line) => { rl.on("line", (line) => {
@ -54,36 +54,36 @@ function viewLog(log) {
log[i] = log[i] =
log[i].replace( log[i].replace(
"SERVER REQUEST MESSAGE", "SERVER REQUEST MESSAGE",
"\x1b[34m\x1b[1mSERVER REQUEST MESSAGE\x1b[22m", "\x1b[34m\x1b[1mSERVER REQUEST MESSAGE\x1b[22m"
) + "\x1b[37m\x1b[0m"; ) + "\x1b[37m\x1b[0m";
} else if (log[i].indexOf("SERVER RESPONSE MESSAGE") != -1) { } else if (log[i].indexOf("SERVER RESPONSE MESSAGE") != -1) {
log[i] = log[i] =
log[i].replace( log[i].replace(
"SERVER RESPONSE MESSAGE", "SERVER RESPONSE MESSAGE",
"\x1b[32m\x1b[1mSERVER RESPONSE MESSAGE\x1b[22m", "\x1b[32m\x1b[1mSERVER RESPONSE MESSAGE\x1b[22m"
) + "\x1b[37m\x1b[0m"; ) + "\x1b[37m\x1b[0m";
} else if (log[i].indexOf("SERVER RESPONSE ERROR MESSAGE") != -1) { } else if (log[i].indexOf("SERVER RESPONSE ERROR MESSAGE") != -1) {
log[i] = log[i] =
log[i].replace( log[i].replace(
"SERVER RESPONSE ERROR MESSAGE", "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"; ) + "\x1b[37m\x1b[0m";
} else if (log[i].indexOf("SERVER ERROR MESSAGE") != -1) { } else if (log[i].indexOf("SERVER ERROR MESSAGE") != -1) {
log[i] = log[i] =
log[i].replace( log[i].replace(
"SERVER ERROR MESSAGE", "SERVER ERROR MESSAGE",
"\x1b[41m\x1b[1mSERVER ERROR MESSAGE\x1b[22m", "\x1b[41m\x1b[1mSERVER ERROR MESSAGE\x1b[22m"
) + "\x1b[40m\x1b[0m"; ) + "\x1b[40m\x1b[0m";
} else if (log[i].indexOf("SERVER WARNING MESSAGE") != -1) { } else if (log[i].indexOf("SERVER WARNING MESSAGE") != -1) {
log[i] = log[i] =
log[i].replace( log[i].replace(
"SERVER WARNING MESSAGE", "SERVER WARNING MESSAGE",
"\x1b[43m\x1b[1mSERVER WARNING MESSAGE\x1b[22m", "\x1b[43m\x1b[1mSERVER WARNING MESSAGE\x1b[22m"
) + "\x1b[40m\x1b[0m"; ) + "\x1b[40m\x1b[0m";
} else if (log[i].indexOf("SERVER MESSAGE") != -1) { } else if (log[i].indexOf("SERVER MESSAGE") != -1) {
log[i] = log[i].replace( log[i] = log[i].replace(
"SERVER MESSAGE", "SERVER MESSAGE",
"\x1b[1mSERVER MESSAGE\x1b[22m", "\x1b[1mSERVER MESSAGE\x1b[22m"
); );
} }
console.log(log[i]); console.log(log[i]);

View file

@ -72,7 +72,7 @@ const logo = [
"\x1b[0m ,///////,", "\x1b[0m ,///////,",
"", "",
"", "",
"\x1b[0m", "\x1b[0m"
]; ];
for (let i = 0; i < logo.length; i++) { for (let i = 0; i < logo.length; i++) {
@ -89,7 +89,7 @@ function prompt(options) {
const rl = readline.createInterface({ const rl = readline.createInterface({
input: process.stdin, input: process.stdin,
output: process.stdout, output: process.stdout,
prompt: "logviewer> ", prompt: "logviewer> "
}); });
console.log("Options:"); console.log("Options:");
for (let i = 0; i < options.length; i++) { for (let i = 0; i < options.length; i++) {
@ -120,36 +120,36 @@ function viewLog(log) {
log[i] = log[i] =
log[i].replace( log[i].replace(
"SERVER REQUEST MESSAGE", "SERVER REQUEST MESSAGE",
"\x1b[34m\x1b[1mSERVER REQUEST MESSAGE\x1b[22m", "\x1b[34m\x1b[1mSERVER REQUEST MESSAGE\x1b[22m"
) + "\x1b[37m\x1b[0m"; ) + "\x1b[37m\x1b[0m";
} else if (log[i].indexOf("SERVER RESPONSE MESSAGE") != -1) { } else if (log[i].indexOf("SERVER RESPONSE MESSAGE") != -1) {
log[i] = log[i] =
log[i].replace( log[i].replace(
"SERVER RESPONSE MESSAGE", "SERVER RESPONSE MESSAGE",
"\x1b[32m\x1b[1mSERVER RESPONSE MESSAGE\x1b[22m", "\x1b[32m\x1b[1mSERVER RESPONSE MESSAGE\x1b[22m"
) + "\x1b[37m\x1b[0m"; ) + "\x1b[37m\x1b[0m";
} else if (log[i].indexOf("SERVER RESPONSE ERROR MESSAGE") != -1) { } else if (log[i].indexOf("SERVER RESPONSE ERROR MESSAGE") != -1) {
log[i] = log[i] =
log[i].replace( log[i].replace(
"SERVER RESPONSE ERROR MESSAGE", "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"; ) + "\x1b[37m\x1b[0m";
} else if (log[i].indexOf("SERVER ERROR MESSAGE") != -1) { } else if (log[i].indexOf("SERVER ERROR MESSAGE") != -1) {
log[i] = log[i] =
log[i].replace( log[i].replace(
"SERVER ERROR MESSAGE", "SERVER ERROR MESSAGE",
"\x1b[41m\x1b[1mSERVER ERROR MESSAGE\x1b[22m", "\x1b[41m\x1b[1mSERVER ERROR MESSAGE\x1b[22m"
) + "\x1b[40m\x1b[0m"; ) + "\x1b[40m\x1b[0m";
} else if (log[i].indexOf("SERVER WARNING MESSAGE") != -1) { } else if (log[i].indexOf("SERVER WARNING MESSAGE") != -1) {
log[i] = log[i] =
log[i].replace( log[i].replace(
"SERVER WARNING MESSAGE", "SERVER WARNING MESSAGE",
"\x1b[43m\x1b[1mSERVER WARNING MESSAGE\x1b[22m", "\x1b[43m\x1b[1mSERVER WARNING MESSAGE\x1b[22m"
) + "\x1b[40m\x1b[0m"; ) + "\x1b[40m\x1b[0m";
} else if (log[i].indexOf("SERVER MESSAGE") != -1) { } else if (log[i].indexOf("SERVER MESSAGE") != -1) {
log[i] = log[i].replace( log[i] = log[i].replace(
"SERVER MESSAGE", "SERVER MESSAGE",
"\x1b[1mSERVER MESSAGE\x1b[22m", "\x1b[1mSERVER MESSAGE\x1b[22m"
); );
} }
console.log(log[i]); console.log(log[i]);
@ -173,7 +173,7 @@ function viewMasterLogs() {
fs fs
.readFileSync(__dirname + "/log/" + latestLogFileName) .readFileSync(__dirname + "/log/" + latestLogFileName)
.toString() .toString()
.split("\n"), .split("\n")
); );
prompt(mainOptions); prompt(mainOptions);
} }
@ -242,7 +242,7 @@ function viewFilteredWorkerLogsPrompt() {
var rl2 = readline.createInterface({ var rl2 = readline.createInterface({
input: process.stdin, input: process.stdin,
output: process.stdout, output: process.stdout,
prompt: "filter> ", prompt: "filter> "
}); });
console.log("Input filter:"); console.log("Input filter:");
rl2.prompt(); rl2.prompt();
@ -257,15 +257,15 @@ var mainOptions = [
{ name: "View 5 latest worker logs", callback: viewWorkerLogs }, { name: "View 5 latest worker logs", callback: viewWorkerLogs },
{ {
name: "View filtered worker logs (latest 20 logs)", name: "View filtered worker logs (latest 20 logs)",
callback: viewFilteredWorkerLogsPrompt, callback: viewFilteredWorkerLogsPrompt
}, },
{ {
name: "Exit log viewer", name: "Exit log viewer",
callback: () => { callback: () => {
console.log("Bye!"); console.log("Bye!");
process.exit(0); process.exit(0);
}, }
}, }
]; ];
prompt(mainOptions); prompt(mainOptions);

View file

@ -123,7 +123,7 @@ try {
0x90befffa, 0x90befffa,
0xa4506ceb, 0xa4506ceb,
0xbef9a3f7, 0xbef9a3f7,
0xc67178f2, 0xc67178f2
); );
let HASH = new Array( let HASH = new Array(
0x6a09e667, 0x6a09e667,
@ -133,7 +133,7 @@ try {
0x510e527f, 0x510e527f,
0x9b05688c, 0x9b05688c,
0x1f83d9ab, 0x1f83d9ab,
0x5be0cd19, 0x5be0cd19
); );
let W = new Array(64); let W = new Array(64);
let a, b, c, d, e, f, g, h; let a, b, c, d, e, f, g, h;
@ -158,14 +158,14 @@ try {
W[j] = safeAdd( W[j] = safeAdd(
safeAdd( safeAdd(
safeAdd(Gamma1256(W[j - 2]), W[j - 7]), safeAdd(Gamma1256(W[j - 2]), W[j - 7]),
Gamma0256(W[j - 15]), Gamma0256(W[j - 15])
), ),
W[j - 16], W[j - 16]
); );
T1 = safeAdd( T1 = safeAdd(
safeAdd(safeAdd(safeAdd(h, Sigma1256(e)), Ch(e, f, g)), K[j]), safeAdd(safeAdd(safeAdd(h, Sigma1256(e)), Ch(e, f, g)), K[j]),
W[j], W[j]
); );
T2 = safeAdd(Sigma0256(a), Maj(a, b, c)); T2 = safeAdd(Sigma0256(a), Maj(a, b, c));
@ -229,7 +229,7 @@ try {
for (let i = 0; i < binarray.length * 4; i++) { for (let i = 0; i < binarray.length * 4; i++) {
str += str +=
hexTab.charAt( 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); hexTab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8)) & 0xf);
} }
@ -244,7 +244,7 @@ try {
hx.push(parseInt(str[i] + str[i + 1], 16)); hx.push(parseInt(str[i] + str[i + 1], 16));
} }
return Buffer.from(hx); return Buffer.from(hx);
}, }
}; };
}; };
} }
@ -279,7 +279,7 @@ function saveConfig() {
let configJSONobj = {}; let configJSONobj = {};
if (fs.existsSync(__dirname + "/config.json")) if (fs.existsSync(__dirname + "/config.json"))
configJSONobj = JSON.parse( configJSONobj = JSON.parse(
fs.readFileSync(__dirname + "/config.json").toString(), fs.readFileSync(__dirname + "/config.json").toString()
); );
configJSONobj.users = users; configJSONobj.users = users;
const configString = JSON.stringify(configJSONobj, null, 2); const configString = JSON.stringify(configJSONobj, null, 2);
@ -314,7 +314,7 @@ for (
) { ) {
console.log("SVR.JS user tool usage:"); console.log("SVR.JS user tool usage:");
console.log( console.log(
"node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] <username>", "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] <username>"
); );
console.log("-h -? /h /? --help -- Displays help"); console.log("-h -? /h /? --help -- Displays help");
console.log("-a --add -- Add an user"); console.log("-a --add -- Add an user");
@ -325,7 +325,7 @@ for (
if (action != "change") { if (action != "change") {
console.log("Multiple actions specified."); console.log("Multiple actions specified.");
console.log( console.log(
"node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] <username>", "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] <username>"
); );
console.log("-h -? /h /? --help -- Displays help"); console.log("-h -? /h /? --help -- Displays help");
console.log("-a --add -- Add an user"); console.log("-a --add -- Add an user");
@ -338,7 +338,7 @@ for (
if (action != "change") { if (action != "change") {
console.log("Multiple actions specified."); console.log("Multiple actions specified.");
console.log( console.log(
"node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] <username>", "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] <username>"
); );
console.log("-h -? /h /? --help -- Displays help"); console.log("-h -? /h /? --help -- Displays help");
console.log("-a --add -- Add an user"); console.log("-a --add -- Add an user");
@ -351,7 +351,7 @@ for (
if (forcechange) { if (forcechange) {
console.log("Multiple -x options specified."); console.log("Multiple -x options specified.");
console.log( console.log(
"node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] <username>", "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] <username>"
); );
console.log("-h -? /h /? --help -- Displays help"); console.log("-h -? /h /? --help -- Displays help");
console.log("-a --add -- Add an user"); console.log("-a --add -- Add an user");
@ -364,7 +364,7 @@ for (
if (user != "") { if (user != "") {
console.log("Multiple users specified."); console.log("Multiple users specified.");
console.log( console.log(
"node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] <username>", "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] <username>"
); );
console.log("-h -? /h /? --help -- Displays help"); console.log("-h -? /h /? --help -- Displays help");
console.log("-a --add -- Add an user"); console.log("-a --add -- Add an user");
@ -379,7 +379,7 @@ for (
if (user == "") { if (user == "") {
console.log("No user specified."); console.log("No user specified.");
console.log( console.log(
"node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] <username>", "node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-x] [-a|--add|-d|--delete] <username>"
); );
console.log("-h -? /h /? --help -- Displays help"); console.log("-h -? /h /? --help -- Displays help");
console.log("-a --add -- Add an user"); console.log("-a --add -- Add an user");
@ -419,7 +419,7 @@ function password(callback) {
const rl = readline.createInterface({ const rl = readline.createInterface({
input: process.stdin, input: process.stdin,
output: process.stdout, output: process.stdout,
prompt: "Password: ", prompt: "Password: "
}); });
rl.prompt(); rl.prompt();
process.stdout.writeold = process.stdout.write; process.stdout.writeold = process.stdout.write;
@ -431,7 +431,7 @@ function password(callback) {
var rl = readline.createInterface({ var rl = readline.createInterface({
input: process.stdin, input: process.stdin,
output: process.stdout, output: process.stdout,
prompt: "Confirm password: ", prompt: "Confirm password: "
}); });
rl.prompt(); rl.prompt();
process.stdout.writeold = process.stdout.write; process.stdout.writeold = process.stdout.write;
@ -464,7 +464,7 @@ function promptAlgorithms(callback, bypass, pbkdf2, scrypt) {
pbkdf2: pbkdf2:
"PBKDF2 (PBKDF2-HMAC-SHA512, 36250 iterations) - more secure and uses less memory, but slower", "PBKDF2 (PBKDF2-HMAC-SHA512, 36250 iterations) - more secure and uses less memory, but slower",
scrypt: 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 ( if (
!crypto.pbkdf2 || !crypto.pbkdf2 ||
@ -472,7 +472,7 @@ function promptAlgorithms(callback, bypass, pbkdf2, scrypt) {
!( !(
process.versions.bun && process.versions.bun &&
!process.versions.bun.match( !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({ const rl = readline.createInterface({
input: process.stdin, input: process.stdin,
output: process.stdout, output: process.stdout,
prompt: "Algorithm: ", prompt: "Algorithm: "
}); });
rl.prompt(); rl.prompt();
rl.on("line", (line) => { rl.on("line", (line) => {
@ -537,7 +537,7 @@ if (action == "delete") {
salt: salt, salt: salt,
pbkdf2: algorithm == "pbkdf2" ? true : undefined, pbkdf2: algorithm == "pbkdf2" ? true : undefined,
scrypt: algorithm == "scrypt" ? true : undefined, scrypt: algorithm == "scrypt" ? true : undefined,
__svrpasswd_l2: true, __svrpasswd_l2: true
}); });
saveConfig(); saveConfig();
console.log("User added successfully"); console.log("User added successfully");
@ -574,7 +574,7 @@ if (action == "delete") {
salt: salt, salt: salt,
pbkdf2: algorithm == "pbkdf2" ? true : undefined, pbkdf2: algorithm == "pbkdf2" ? true : undefined,
scrypt: algorithm == "scrypt" ? true : undefined, scrypt: algorithm == "scrypt" ? true : undefined,
__svrpasswd_l2: true, __svrpasswd_l2: true
}; };
saveConfig(); saveConfig();
console.log("Password changed successfully"); console.log("Password changed successfully");
@ -584,6 +584,6 @@ if (action == "delete") {
}, },
users[userindex].__svrpasswd_l2 && !forcechange, users[userindex].__svrpasswd_l2 && !forcechange,
users[userindex].pbkdf2, users[userindex].pbkdf2,
users[userindex].scrypt, users[userindex].scrypt
); );
} }