overall: formatting check, jsdoc type hints, express res/return stuff

utils - changes in logger, dateformatter and removed unneeded ones

.env file changes

license check, readme update

package.json update - version, deps, URLs

server cleanup

sequelize config check
This commit is contained in:
2024-08-14 21:08:58 +05:30
parent 7318e8e325
commit 32735ad7ff
36 changed files with 343 additions and 5731 deletions

View File

@@ -2,8 +2,8 @@ const fs = require("fs");
const archiver = require('archiver');
/**
* @param {String} sourceDir: /some/folder/to/compress
* @param {String} outPath: /path/to/created.zip
* @param {string} sourceDir /some/folder/to/compress
* @param {string} outPath /path/to/created.zip
* @returns {Promise}
*/
function zipDirectory(sourceDir, outPath) {
@@ -24,4 +24,4 @@ function zipDirectory(sourceDir, outPath) {
module.exports = {
zipDirectory,
}
};

View File

@@ -1,12 +1,14 @@
/**
* Returns a timestamp string to use for timestamped files
* @returns {string} String of current datetime in YYYY.MM.DD-HH:MM:SS format
* @returns {string} String of current datetime in YYYYMMDDHHMMSS format
*/
const dateForFilename = () => {
const dt = new Date();
return `${dt.getFullYear()}-${dt.getMonth() + 1}-${dt.getDate()}-${dt.getHours()}-${dt.getMinutes()}-${dt.getSeconds()}`;
return new Date().
toISOString().slice(-24).
replace(/\D/g, '').
slice(0, 14);
}
module.exports = {
dateForFilename,
}
};

View File

@@ -1,3 +1,9 @@
/**
* Recursively build a FormData object from a JSON object
* @param {FormData} formData
* @param {any} data
* @param {string} parentKey
*/
function buildFormData(formData, data, parentKey) {
if (data && typeof data === 'object' && !(data instanceof Date)) {
Object.keys(data).forEach(key => {
@@ -10,6 +16,11 @@ function buildFormData(formData, data, parentKey) {
}
}
/**
* Converts a JSON object to a FormData object
* @param {any} data
* @returns {FormData}
*/
function jsonToFormData(data) {
const formData = new FormData();
@@ -21,4 +32,4 @@ function jsonToFormData(data) {
module.exports = {
jsonToFormData,
buildFormData,
}
};

View File

@@ -1,11 +1,11 @@
/**
* String joins all the values of a JSON object, including nested keys
* Stringifies only values of a JSON object, including nested ones
*
* @param {any} obj JSON object
* @param {string} delimiter Delimiter of final string
* @returns
* @returns {string}
*/
const getNestedValuesString = (obj, delimiter) => {
const getNestedValuesString = (obj, delimiter = ', ') => {
let values = [];
for (key in obj) {
if (typeof obj[key] !== "object") {
@@ -15,9 +15,9 @@ const getNestedValuesString = (obj, delimiter) => {
}
}
return delimiter ? values.join(delimiter) : values.join();
return values.join(delimiter);
}
module.exports = {
getNestedValuesString
}
};

View File

@@ -1,60 +1,67 @@
// Whole thing is winston logger stuff, if you want to learn read the docs
const path = require("path");
const { createLogger, transports, config, format } = require("winston");
const { combine, label, timestamp, printf } = format;
const { createLogger, transports, config, format } = require('winston');
const { combine, label, timestamp, printf, errors } = format;
const typedefs = require("../typedefs");
const getLabel = (callingModule) => {
const parts = callingModule.filename.split(path.sep);
return path.join(parts[parts.length - 2], parts.pop());
if (!callingModule.filename) return "repl";
const parts = callingModule.filename?.split(path.sep);
return path.join(parts[parts.length - 2], parts.pop());
};
const logMetaReplacer = (key, value) => {
if (key === "error") {
return value.name + ": " + value.message;
}
return value;
}
const allowedErrorKeys = ["name", "code", "message", "stack"];
const metaFormat = (meta) => {
if (Object.keys(meta).length > 0)
return "\n" + JSON.stringify(meta, logMetaReplacer) + "\n";
return "\n";
if (Object.keys(meta).length > 0)
return '\n' + JSON.stringify(meta, null, "\t");
return '';
}
const logFormat = printf(({ level, message, label, timestamp, ...meta }) => {
if (meta.error) {
for (const key in meta.error) {
if (typeof key !== "symbol" && key !== "message" && key !== "name") {
delete meta.error[key]
}
}
}
return `${timestamp} [${label}] ${level}: ${message}${metaFormat(meta)}`;
if (meta.error) { // if the error was passed
for (const key in meta.error) {
if (!allowedErrorKeys.includes(key)) {
delete meta.error[key];
}
}
const { stack, ...rest } = meta.error;
return `${timestamp} [${label}] ${level}: ${message}${metaFormat(rest)}\n` +
`${stack ?? ''}`;
}
return `${timestamp} [${label}] ${level}: ${message}${metaFormat(meta)}`;
});
/**
* Creates a curried function, and call it with the module in use to get logs with filename
* @param {typedefs.Module} callingModule The module from which the logger is called
* @returns {typedefs.Logger}
*/
const logger = (callingModule) => {
return createLogger({
levels: config.npm.levels,
format: combine(
label({ label: getLabel(callingModule) }),
timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
logFormat,
),
transports: [
new transports.Console(),
new transports.File({ filename: __dirname + "/../logs/common.log" }),
new transports.File({ filename: __dirname + "/../logs/error.log", level: "error" }),
]
});
const curriedLogger = (callingModule) => {
let winstonLogger = createLogger({
levels: config.npm.levels,
format: combine(
errors({ stack: true }),
label({ label: getLabel(callingModule) }),
timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
logFormat,
),
transports: [
new transports.Console({ level: 'info' }),
new transports.File({
filename: __dirname + '/../logs/debug.log',
level: 'debug',
maxsize: 10485760,
}),
new transports.File({
filename: __dirname + '/../logs/error.log',
level: 'error',
maxsize: 1048576,
}),
]
});
winstonLogger.on('error', (error) => winstonLogger.error("Error inside logger", { error }));
return winstonLogger;
}
module.exports = logger;
module.exports = curriedLogger;

View File

@@ -1,45 +0,0 @@
const mailer = require("nodemailer");
const logger = require("./logger")(module);
// Creates a mailer transporter object with authentication and base config
const transport = mailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
service: "gmail",
auth: {
user: process.env.AUTOMAILER_ID,
pass: process.env.AUTOMAILER_APP_PASSWD,
}
});
/**
* Sends a mail from web user to a mail inside organization
* @param {string} mailTarget Target mail - must be within organization
* @param {string} mailSubject Mail subject
* @param {{name: string, email: string, message: string}} userData User details: name, email, and message
*/
const inboundMailer = (mailTarget, mailSubject, userData) => {
if (!mailTarget.endsWith("cegtechforum.in")) {
throw new Error("Invalid target mail domain.");
}
const message = {
to: mailTarget,
subject: mailSubject,
html:
"<p>Name: " + userData.name + "</p><p>Email: " + userData.email + "</p><br/><p>Message:<br/>" + userData.message + "</p>"
};
transport.sendMail(message, (err, info) => {
if (err) {
logger.error("Failure: QUERY mail NOT sent", { err, userData });
} else {
logger.info("Success: QUERY mail sent", { info });
}
});
};
module.exports = {
inboundMailer
}

View File

@@ -1,58 +0,0 @@
const pathLib = require("path");
const qr = require("qrcode");
const logger = require("./logger")(module);
const { getSignedJWT } = require("./token");
/**
* Generates QR code from data and writes to file in tmp folder.
* To avoid race conditions, use email or other unique attributes for id.
* @param {string|any} data String or JSON object
*/
const qrPNGFile = (id, data) => {
qr.toFile(
path = pathLib.join(__dirname, "../tmp/tmpQR-" + id + ".png"),
text = (typeof data === "object" ? JSON.stringify(data) : data),
options = { type: 'png' },
(err) => {
if (err) {
logger.error("qrPNGFile", err);
throw err;
}
}
);
}
/**
* Generates QR code from data after signing and writes to file in tmp or k-qrs folder.
*
* To avoid race conditions, use email or other unique attributes for ID.
* @param {string|any} data String or JSON object
*/
const qrSignedPNGFile = (id, data, tmp = true) => {
const signedData = getSignedJWT(data);
const qrFilename = `${tmp ? 'tmpEncQR' : 'K-QR'}-${id}.png`;
const targetPath = pathLib.join(
__dirname, "..",
tmp ? "tmp" : pathLib.join("uploads", "2023", "k-qrs"),
qrFilename,
);
qr.toFile(
path = targetPath,
text = (typeof data === "object" ? JSON.stringify(signedData) : signedData),
options = { type: 'png' },
(err) => {
if (err) {
logger.error("qrSignedPNGFile", err);
throw err;
}
}
)
return qrFilename;
}
module.exports = {
qrPNGFile,
qrSignedPNGFile,
}

View File

@@ -1,23 +0,0 @@
/* Taken from quick-encrypt package, which is not maintained anymore */
const crypto = require('crypto')
const acceptableBitSizes = [1024, 2048];
exports.generate = (sizeInBits) => {
if (!acceptableBitSizes.includes(sizeInBits))
throw Error('Error generating public and private key. Key size can only be 1024 or 2048. Example usage: ` let keys = QuickEncrypt.generate(2048); `')
return keypair({ bits: sizeInBits })
}
exports.encrypt = (payloadString, publicKey) => {
if (typeof payloadString !== 'string' || typeof publicKey !== 'string')
throw Error("Error encrypting. Payload and Public Key should be in text format. Example usage: ` let encryptedText = QuickEncrypt.encrypt('Some secret text here!', 'the public RSA key in text format here'); ` ")
return crypto.publicEncrypt(publicKey, Buffer.from(payloadString, 'utf8')).toString('hex')
}
exports.decrypt = (encryptedString, privateKey) => {
if (typeof encryptedString !== 'string' || typeof privateKey !== 'string')
throw Error("Error decrypting. Decrypted Text and Private Key should be in text format. Example usage: ` let decryptedText = QuickEncrypt.decrypt('asddd213d19jenacanscasn', 'the private RSA key in text format here'); ` ")
return crypto.privateDecrypt({ key: privateKey }, Buffer.from(encryptedString, 'hex')).toString()
}

View File

@@ -1,8 +1,8 @@
const fs = require("fs");
const jwt = require("jsonwebtoken");
const privateKey = fs.readFileSync(process.env.PRIVKEY);
const publicKey = fs.readFileSync(process.env.PUBKEY);
const privateKey = fs.readFileSync(process.env.PRIVKEY_PATH);
const publicKey = fs.readFileSync(process.env.PUBKEY_PATH);
/**
* Sign data into JWT with JWT env secret
@@ -10,7 +10,7 @@ const publicKey = fs.readFileSync(process.env.PUBKEY);
* @returns {jwt.JwtPayload}
*/
const getJWT = (data) => {
return jwt.sign({ id: data }, process.env.JWTSECRET, { algorithm: "HS256" }); // symmetric encryption, so simple secret with SHA
return jwt.sign({ id: data }, process.env.JWTSECRET, { algorithm: "HS256" }); // symmetric encryption, so simple secret with SHA
};
/**
@@ -19,13 +19,7 @@ const getJWT = (data) => {
* @returns {jwt.JwtPayload}
*/
const getSignedJWT = (data) => {
return jwt.sign(
{ id: data },
privateKey,
{
algorithm: "RS256", // asymmetric signing, so private key with RSA
}
)
return jwt.sign({ id: data }, privateKey, { algorithm: "RS256" }); // asymmetric signing, so private key with RSA
}
/**
@@ -34,7 +28,7 @@ const getSignedJWT = (data) => {
* @returns {string|any}
*/
const verifyJWT = (data) => {
return jwt.verify(data, process.env.JWTSECRET, { algorithms: ["HS256"] });
return jwt.verify(data, process.env.JWTSECRET, { algorithms: ["HS256"] });
}
/**
@@ -43,18 +37,12 @@ const verifyJWT = (data) => {
* @returns {string|any}
*/
const verifySignedJWT = (signedString) => {
return jwt.verify(
signedString,
publicKey,
{
algorithms: ["RS256"]
}
);
return jwt.verify(signedString, publicKey, { algorithms: ["RS256"] });
}
module.exports = {
getJWT,
verifyJWT,
getSignedJWT,
verifySignedJWT,
getJWT,
verifyJWT,
getSignedJWT,
verifySignedJWT,
};