This commit is contained in:
Benjamin Toby
2025-01-10 20:35:05 +01:00
parent 9192dae0b5
commit a3561da53d
286 changed files with 13862 additions and 42590 deletions
+10
View File
@@ -0,0 +1,10 @@
type Param = {
encryptedString: string;
encryptionKey?: string;
encryptionSalt?: string;
};
/**
* # Decrypt Function
*/
export default function decrypt({ encryptedString, encryptionKey, encryptionSalt, }: Param): string;
export {};
+41
View File
@@ -0,0 +1,41 @@
"use strict";
// @ts-check
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = decrypt;
const crypto_1 = require("crypto");
const buffer_1 = require("buffer");
/**
* # Decrypt Function
*/
function decrypt({ encryptedString, encryptionKey, encryptionSalt, }) {
if (!(encryptedString === null || encryptedString === void 0 ? void 0 : encryptedString.match(/./))) {
console.log("Encrypted string is invalid");
return encryptedString;
}
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
const finalKeyLen = process.env.DSQL_ENCRYPTION_KEY_LENGTH
? Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH)
: 24;
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
console.log("Decrption key is invalid");
return encryptedString;
}
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
console.log("Decrption salt is invalid");
return encryptedString;
}
const algorithm = "aes-192-cbc";
let key = (0, crypto_1.scryptSync)(finalEncryptionKey, finalEncryptionSalt, finalKeyLen);
let iv = buffer_1.Buffer.alloc(16, 0);
const decipher = (0, crypto_1.createDecipheriv)(algorithm, key, iv);
try {
let decrypted = decipher.update(encryptedString, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
}
catch (error) {
console.log("Error in decrypting =>", error.message);
return encryptedString;
}
}
+10
View File
@@ -0,0 +1,10 @@
type Param = {
data: string;
encryptionKey?: string;
encryptionSalt?: string;
};
/**
* # Encrypt String
*/
export default function encrypt({ data, encryptionKey, encryptionSalt, }: Param): string | null;
export {};
+44
View File
@@ -0,0 +1,44 @@
"use strict";
// @ts-check
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = encrypt;
const crypto_1 = require("crypto");
const buffer_1 = require("buffer");
/**
* # Encrypt String
*/
function encrypt({ data, encryptionKey, encryptionSalt, }) {
if (!(data === null || data === void 0 ? void 0 : data.match(/./))) {
console.log("Encryption string is invalid");
return data;
}
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
const finalKeyLen = process.env.DSQL_ENCRYPTION_KEY_LENGTH
? Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH)
: 24;
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
console.log("Encryption key is invalid");
return data;
}
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
console.log("Encryption salt is invalid");
return data;
}
const algorithm = "aes-192-cbc";
const password = finalEncryptionKey;
let key = (0, crypto_1.scryptSync)(password, finalEncryptionSalt, finalKeyLen);
let iv = buffer_1.Buffer.alloc(16, 0);
// @ts-ignore
const cipher = (0, crypto_1.createCipheriv)(algorithm, key, iv);
try {
let encrypted = cipher.update(data, "utf8", "hex");
encrypted += cipher.final("hex");
return encrypted;
}
catch ( /** @type {*} */error) {
console.log("Error in encrypting =>", error.message);
return data;
}
}
module.exports = encrypt;
+9
View File
@@ -0,0 +1,9 @@
type Param = {
password: string;
encryptionKey?: string;
};
/**
* # Hash password Function
*/
export default function hashPassword({ password, encryptionKey, }: Param): string;
export {};
+17
View File
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = hashPassword;
const crypto_1 = require("crypto");
/**
* # Hash password Function
*/
function hashPassword({ password, encryptionKey, }) {
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
throw new Error("Encryption key is invalid");
}
const hmac = (0, crypto_1.createHmac)("sha512", finalEncryptionKey);
hmac.update(password);
let hashed = hmac.digest("base64");
return hashed;
}
@@ -0,0 +1,12 @@
interface SQLDeleteGenReturn {
query: string;
values: string[];
}
/**
* # SQL Delete Generator
*/
export default function sqlDeleteGenerator({ tableName, data, }: {
data: any;
tableName: string;
}): SQLDeleteGenReturn | undefined;
export {};
@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = sqlDeleteGenerator;
/**
* # SQL Delete Generator
*/
function sqlDeleteGenerator({ tableName, data, }) {
try {
let queryStr = `DELETE FROM ${tableName}`;
let deleteBatch = [];
let queryArr = [];
Object.keys(data).forEach((ky) => {
deleteBatch.push(`${ky}=?`);
queryArr.push(data[ky]);
});
queryStr += ` WHERE ${deleteBatch.join(" AND ")}`;
return {
query: queryStr,
values: queryArr,
};
}
catch ( /** @type {any} */error) {
console.log(`SQL delete gen ERROR: ${error.message}`);
return undefined;
}
}
@@ -0,0 +1,15 @@
import { ServerQueryParam } from "../../../types";
type Param = {
genObject?: ServerQueryParam;
tableName: string;
};
type Return = {
string: string;
values: string[];
} | undefined;
/**
* # SQL Query Generator
* @description Generates an SQL Query for node module `mysql` or `serverless-mysql`
*/
export default function sqlGenerator({ tableName, genObject }: Param): Return;
export {};
+211
View File
@@ -0,0 +1,211 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = sqlGenerator;
/**
* # SQL Query Generator
* @description Generates an SQL Query for node module `mysql` or `serverless-mysql`
*/
function sqlGenerator({ tableName, genObject }) {
if (!genObject)
return undefined;
const finalQuery = genObject.query ? genObject.query : undefined;
const queryKeys = finalQuery ? Object.keys(finalQuery) : undefined;
const sqlSearhValues = [];
/**
* # Generate Query
*/
function genSqlSrchStr({ queryObj, join, field, }) {
const finalFieldName = (() => {
if (queryObj === null || queryObj === void 0 ? void 0 : queryObj.tableName) {
return `${queryObj.tableName}.${field}`;
}
if (join) {
return `${tableName}.${field}`;
}
return field;
})();
let str = `${finalFieldName}=?`;
if (typeof queryObj.value == "string" ||
typeof queryObj.value == "number") {
const valueParsed = String(queryObj.value);
if (queryObj.equality == "LIKE") {
str = `LOWER(${finalFieldName}) LIKE LOWER('%${valueParsed}%')`;
}
else if (queryObj.equality == "NOT EQUAL") {
str = `${finalFieldName} != ?`;
sqlSearhValues.push(valueParsed);
}
else {
sqlSearhValues.push(valueParsed);
}
}
else if (Array.isArray(queryObj.value)) {
/** @type {string[]} */
const strArray = [];
queryObj.value.forEach((val) => {
const valueParsed = val;
if (queryObj.equality == "LIKE") {
strArray.push(`LOWER(${finalFieldName}) LIKE LOWER('%${valueParsed}%')`);
}
else if (queryObj.equality == "NOT EQUAL") {
strArray.push(`${finalFieldName} != ?`);
sqlSearhValues.push(valueParsed);
}
else {
strArray.push(`${finalFieldName} = ?`);
sqlSearhValues.push(valueParsed);
}
});
str = "(" + strArray.join(` ${queryObj.operator || "AND"} `) + ")";
}
return str;
}
const sqlSearhString = queryKeys === null || queryKeys === void 0 ? void 0 : queryKeys.map((field) => {
const queryObj =
/** @type {import("../../../types").ServerQueryQueryObject} */ finalQuery === null || finalQuery === void 0 ? void 0 : finalQuery[field];
if (!queryObj)
return;
if (queryObj.__query) {
const subQueryGroup =
/** @type {import("../../../types").ServerQueryQueryObject}} */ queryObj.__query;
const subSearchKeys = Object.keys(subQueryGroup);
const subSearchString = subSearchKeys.map((_field) => {
const newSubQueryObj = subQueryGroup === null || subQueryGroup === void 0 ? void 0 : subQueryGroup[_field];
return genSqlSrchStr({
queryObj: newSubQueryObj,
field: _field,
join: genObject.join,
});
});
console.log("queryObj.operator", queryObj.operator);
return ("(" +
subSearchString.join(` ${queryObj.operator || "AND"} `) +
")");
}
return genSqlSrchStr({ queryObj, field, join: genObject.join });
});
function generateJoinStr(
/** @type {import("../../../types").ServerQueryParamsJoinMatchObject} */ mtch,
/** @type {import("../../../types").ServerQueryParamsJoin} */ join) {
return `${typeof mtch.source == "object" ? mtch.source.tableName : tableName}.${typeof mtch.source == "object" ? mtch.source.fieldName : mtch.source}=${(() => {
if (mtch.targetLiteral) {
return `'${mtch.targetLiteral}'`;
}
if (join.alias) {
return `${typeof mtch.target == "object"
? mtch.target.tableName
: join.alias}.${typeof mtch.target == "object"
? mtch.target.fieldName
: mtch.target}`;
}
return `${typeof mtch.target == "object"
? mtch.target.tableName
: join.tableName}.${typeof mtch.target == "object"
? mtch.target.fieldName
: mtch.target}`;
})()}`;
}
let queryString = (() => {
var _a, _b, _c;
let str = "SELECT";
if ((_a = genObject.selectFields) === null || _a === void 0 ? void 0 : _a[0]) {
if (genObject.join) {
str += ` ${(_b = genObject.selectFields) === null || _b === void 0 ? void 0 : _b.map((fld) => `${tableName}.${fld}`).join(",")}`;
}
else {
str += ` ${(_c = genObject.selectFields) === null || _c === void 0 ? void 0 : _c.join(",")}`;
}
}
else {
if (genObject.join) {
str += ` ${tableName}.*`;
}
else {
str += " *";
}
}
if (genObject.join) {
/** @type {string[]} */
const existingJoinTableNames = [tableName];
str +=
"," +
genObject.join
.map((joinObj) => {
const joinTableName = joinObj.alias
? joinObj.alias
: joinObj.tableName;
if (existingJoinTableNames.includes(joinTableName))
return null;
existingJoinTableNames.push(joinTableName);
if (joinObj.selectFields) {
return joinObj.selectFields
.map((selectField) => {
if (typeof selectField == "string") {
return `${joinTableName}.${selectField}`;
}
else if (typeof selectField == "object") {
let aliasSelectField = selectField.count
? `COUNT(${joinTableName}.${selectField.field})`
: `${joinTableName}.${selectField.field}`;
if (selectField.alias)
aliasSelectField += ` AS ${selectField.alias}`;
return aliasSelectField;
}
})
.join(",");
}
else {
return `${joinTableName}.*`;
}
})
.filter((_) => Boolean(_))
.join(",");
}
str += ` FROM ${tableName}`;
if (genObject.join) {
str +=
" " +
genObject.join
.map((join) => {
return (join.joinType +
" " +
(join.alias
? join.tableName + " " + join.alias
: join.tableName) +
" ON " +
(() => {
if (Array.isArray(join.match)) {
return ("(" +
join.match
.map((mtch) => generateJoinStr(mtch, join))
.join(join.operator
? ` ${join.operator} `
: " AND ") +
")");
}
else if (typeof join.match == "object") {
return generateJoinStr(join.match, join);
}
})());
})
.join(" ");
}
return str;
})();
if ((sqlSearhString === null || sqlSearhString === void 0 ? void 0 : sqlSearhString[0]) && sqlSearhString.find((str) => str)) {
const stringOperator = (genObject === null || genObject === void 0 ? void 0 : genObject.searchOperator) || "AND";
queryString += ` WHERE ${sqlSearhString.join(` ${stringOperator} `)} `;
}
if (genObject.order)
queryString += ` ORDER BY ${genObject.join
? `${tableName}.${genObject.order.field}`
: genObject.order.field} ${genObject.order.strategy}`;
if (genObject.limit)
queryString += ` LIMIT ${genObject.limit}`;
if (genObject.offset)
queryString += ` OFFSET ${genObject.offset}`;
return {
string: queryString,
values: sqlSearhValues,
};
}
@@ -0,0 +1,12 @@
interface SQLInsertGenReturn {
query: string;
values: string[];
}
/**
* # SQL Insert Generator
*/
export default function sqlInsertGenerator({ tableName, data, }: {
data: any[];
tableName: string;
}): SQLInsertGenReturn | undefined;
export {};
@@ -0,0 +1,50 @@
"use strict";
// @ts-check
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = sqlInsertGenerator;
/**
* # SQL Insert Generator
*/
function sqlInsertGenerator({ tableName, data, }) {
try {
if (Array.isArray(data) && (data === null || data === void 0 ? void 0 : data[0])) {
/** @type {string[]} */
let insertKeys = [];
data.forEach((dt) => {
const kys = Object.keys(dt);
kys.forEach((ky) => {
if (!insertKeys.includes(ky)) {
insertKeys.push(ky);
}
});
});
/** @type {string[]} */
let queryBatches = [];
/** @type {string[]} */
let queryValues = [];
data.forEach((item) => {
queryBatches.push(`(${insertKeys
.map((ky) => {
var _a, _b;
queryValues.push(((_b = (_a = item[ky]) === null || _a === void 0 ? void 0 : _a.toString()) === null || _b === void 0 ? void 0 : _b.match(/./))
? item[ky]
: null);
return "?";
})
.join(",")})`);
});
let query = `INSERT INTO ${tableName} (${insertKeys.join(",")}) VALUES ${queryBatches.join(",")}`;
return {
query: query,
values: queryValues,
};
}
else {
return undefined;
}
}
catch ( /** @type {any} */error) {
console.log(`SQL insert gen ERROR: ${error.message}`);
return undefined;
}
}