This commit is contained in:
Benjamin Toby
2024-12-09 12:45:39 +01:00
parent 7bd4b2fe65
commit 586e3cfa85
43 changed files with 216 additions and 506 deletions
-163
View File
@@ -1,163 +0,0 @@
// @ts-check
const fs = require("fs");
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Add Database Entry
* ==============================================================================
* @param {object} params - foundUser if any
* @param {string} params.tableName - Table Name
* @param {any} params.data - Data to be added
* @param {string} [params.duplicateColumnName] - Duplicate Column Name
* @param {string | number} [params.duplicateColumnValue] - Duplicate Column Value
*/
module.exports = async function addDbEntry({
tableName,
data,
duplicateColumnName,
duplicateColumnValue,
}) {
/**
* Check Duplicate if specified
*
* @description Check Duplicate if specified
*/
if (duplicateColumnName) {
let duplicateEntry = await DB_HANDLER(
`SELECT ${duplicateColumnName} FROM ${tableName} WHERE ${duplicateColumnName}='${duplicateColumnValue}'`
);
if (duplicateEntry && duplicateEntry[0]) return null;
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
const dataKeys = Object.keys(data);
let insertKeysArray = [];
let insertValuesArray = [];
for (let i = 0; i < dataKeys.length; i++) {
const dataKey = dataKeys[i];
let dataValue = data[dataKey];
// const correspondingColumnObject = dbColumns.filter((col) => col.Field === dataKey);
// const { Field, Type, Null, Key, Default, Extra } = correspondingColumnObject;
if (!dataValue) continue;
insertKeysArray.push("`" + dataKey + "`");
if (typeof dataValue === "object") {
dataValue = JSON.stringify(data[dataKey]);
}
// let parsedDataValue = dataValue.toString().replace(/\'/g, "\\'");
insertValuesArray.push(dataValue);
}
////////////////////////////////////////
// @ts-ignore
let existingDateCreatedColumn = await DB_HANDLER(
`SHOW COLUMNS FROM \`${tableName}\` WHERE Field = 'date_created'`
);
if (!existingDateCreatedColumn || !existingDateCreatedColumn[0]) {
// @ts-ignore
await DB_HANDLER(
`ALTER TABLE ${tableName} ADD COLUMN date_created VARCHAR(255) NOT NULL`
);
}
insertKeysArray.push("date_created");
insertValuesArray.push(Date());
////////////////////////////////////////
// @ts-ignore
let existingDateCreatedCodeColumn = await DB_HANDLER(
`SHOW COLUMNS FROM ${tableName} WHERE Field = 'date_created_code'`
);
if (!existingDateCreatedCodeColumn || !existingDateCreatedCodeColumn[0]) {
// @ts-ignore
await DB_HANDLER(
`ALTER TABLE ${tableName} ADD COLUMN date_created_code BIGINT NOT NULL`
);
}
insertKeysArray.push("date_created_code");
insertValuesArray.push(Date.now());
////////////////////////////////////////
// @ts-ignore
let existingDateCodeColumn = await DB_HANDLER(
`SHOW COLUMNS FROM ${tableName} WHERE Field = 'date_code'`
);
if (existingDateCodeColumn && existingDateCodeColumn[0]) {
insertKeysArray.push("date_code");
insertValuesArray.push(Date.now());
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
// @ts-ignore
let existingDateUpdatedColumn = await DB_HANDLER(
`SHOW COLUMNS FROM ${tableName} WHERE Field = 'date_updated'`
);
if (!existingDateUpdatedColumn || !existingDateUpdatedColumn[0]) {
// @ts-ignore
await DB_HANDLER(
`ALTER TABLE ${tableName} ADD COLUMN date_updated VARCHAR(255) NOT NULL`
);
}
insertKeysArray.push("date_updated");
insertValuesArray.push(Date());
////////////////////////////////////////
// @ts-ignore
let existingDateUpdatedCodeColumn = await DB_HANDLER(
`SHOW COLUMNS FROM ${tableName} WHERE Field = 'date_updated_code'`
);
if (!existingDateUpdatedCodeColumn || !existingDateUpdatedCodeColumn[0]) {
// @ts-ignore
await DB_HANDLER(
`ALTER TABLE ${tableName} ADD COLUMN date_updated_code BIGINT NOT NULL`
);
}
insertKeysArray.push("date_updated_code");
insertValuesArray.push(Date.now());
////////////////////////////////////////
const query = `INSERT INTO ${tableName} (${insertKeysArray.join(
","
)}) VALUES (${insertValuesArray.map((val) => "?").join(",")})`;
const queryValuesArray = insertValuesArray;
// @ts-ignore
const newInsert = await DB_HANDLER(query, queryValuesArray);
////////////////////////////////////////
return newInsert;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
};
@@ -51,7 +51,9 @@ async function addDbEntry({
/**
* Initialize variables
*/
const isMaster = dbContext?.match(/dsql.user/i)
const isMaster = useLocal
? true
: dbContext?.match(/dsql.user/i)
? false
: dbFullName && !dbFullName.match(/^datasquirel$/)
? false
@@ -41,7 +41,9 @@ async function deleteDbEntry({
/**
* Check if data is valid
*/
const isMaster = dbContext?.match(/dsql.user/i)
const isMaster = useLocal
? true
: dbContext?.match(/dsql.user/i)
? false
: dbFullName && !dbFullName.match(/^datasquirel$/)
? false
@@ -1,41 +1,14 @@
// @ts-check
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/**
* Sanitize SQL function
* ==============================================================================
* @description this function takes in a text(or number) and returns a sanitized
* text, usually without spaces
* # Path Traversal Check
*
* @param {string|number} text - Text or number or object
*
* @returns {string}
*/
function pathTraversalCheck(text) {
/**
* Initial Checks
*
* @description Initial Checks
*/
return text.toString().replace(/\//g, "");
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
module.exports = pathTraversalCheck;
-6
View File
@@ -1,10 +1,4 @@
export = runQuery;
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Run DSQL users queries
* ==============================================================================
@@ -1,12 +1,3 @@
/** # MODULE TRACE
======================================================================
* Detected 3 files that call this module. The files are listed below:
======================================================================
* `import` Statement Found in [get.js] => file:///d:\GitHub\datasquirel\pages\api\query\get.js
* `import` Statement Found in [post.js] => file:///d:\GitHub\datasquirel\pages\api\query\post.js
* `import` Statement Found in [add-user.js] => file:///d:\GitHub\datasquirel\pages\api\user\add-user.js
==== MODULE TRACE END ==== */
// @ts-check
const fs = require("fs");
@@ -15,20 +6,12 @@ const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HAND
const fullAccessDbHandler = require("../fullAccessDbHandler");
const varReadOnlyDatabaseDbHandler = require("../varReadOnlyDatabaseDbHandler");
const serverError = require("../serverError");
const addDbEntry = require("./addDbEntry");
const updateDbEntry = require("./updateDbEntry");
const deleteDbEntry = require("./deleteDbEntry");
const parseDbResults = require("../parseDbResults");
const trimSql = require("../../../utils/trim-sql");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Run DSQL users queries
* ==============================================================================
@@ -100,31 +83,19 @@ async function runQuery({
if (
readOnly &&
formattedQuery.match(
/^alter|^delete|information_schema|databases|^create/i
/^alter|^delete|information_schema|^create/i
)
) {
throw new Error("Wrong Input!");
}
if (local) {
console.log("Using Local ...");
const rawResults = await LOCAL_DB_HANDLER(
formattedQuery,
queryValuesArray
);
result = tableSchema
? parseDbResults({
unparsedResults: rawResults,
tableSchema,
})
: rawResults;
} else if (readOnly) {
if (readOnly) {
result = await varReadOnlyDatabaseDbHandler({
queryString: formattedQuery,
queryValuesArray: queryValuesArray?.map((vl) => String(vl)),
database: dbFullName,
tableSchema,
useLocal: local,
});
} else {
result = await fullAccessDbHandler({
@@ -132,6 +103,7 @@ async function runQuery({
queryValuesArray: queryValuesArray?.map((vl) => String(vl)),
database: dbFullName,
tableSchema,
local,
});
}
} else if (typeof query === "object") {
@@ -163,6 +135,7 @@ async function runQuery({
duplicateColumnName,
duplicateColumnValue,
tableSchema,
useLocal: local,
});
if (!result?.insertId) {
@@ -181,6 +154,7 @@ async function runQuery({
identifierColumnName,
identifierValue,
tableSchema,
useLocal: local,
});
break;
@@ -194,6 +168,7 @@ async function runQuery({
identifierColumnName,
identifierValue,
tableSchema,
useLocal: local,
});
break;
@@ -2,13 +2,6 @@
const _ = require("lodash");
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/**
* Sanitize SQL function
* ==============================================================================
@@ -22,53 +15,18 @@ const _ = require("lodash");
* @returns {any}
*/
function sanitizeSql(text, spaces, regex) {
/**
* Initial Checks
*
* @description Initial Checks
*/
if (!text) return "";
if (typeof text == "number" || typeof text == "boolean") return text;
if (typeof text == "string" && !text?.toString()?.match(/./)) return "";
if (typeof text == "object" && !Array.isArray(text)) {
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const newObject = sanitizeObjects(text, spaces);
return newObject;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} else if (typeof text == "object" && Array.isArray(text)) {
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const newArray = sanitizeArrays(text, spaces);
return newArray;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
// if (text?.toString()?.match(/\'|\"/)) {
// console.log("TEXT containing commas =>", text);
// return "";
// }
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Declare variables
*
* @description Declare "results" variable
*/
let finalText = text;
if (regex) {
@@ -83,45 +41,18 @@ function sanitizeSql(text, spaces, regex) {
.replace(/ /g, "");
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const escapeRegex =
/select |insert |drop |delete |alter |create |exec | union | or | like | concat|LOAD_FILE|ASCII| COLLATE | HAVING | information_schema|DECLARE |\#|WAITFOR |delay |BENCHMARK |\/\*.*\*\//gi;
finalText = finalText
.replace(/(?<!\\)\'/g, "\\'")
.replace(/(?<!\\)\`/g, "\\`")
// .replace(/(?<!\\)\"/g, '\\"')
.replace(/\/\*\*\//g, "")
.replace(escapeRegex, "\\$&");
// const injectionRegexp = /select .* from|\*|delete from|drop database|drop table|update .* set/i;
// if (text?.toString()?.match(injectionRegexp)) {
// console.log("ATTEMPTED INJECTION =>", text);
// return "";
// }
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return finalText;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/**
* Sanitize Objects Function
* ==============================================================================
@@ -157,13 +88,6 @@ function sanitizeObjects(object, spaces) {
return objectUpdated;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/**
* Sanitize Objects Function
* ==============================================================================
@@ -197,11 +121,4 @@ function sanitizeArrays(array, spaces) {
return arrayUpdated;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
module.exports = sanitizeSql;
@@ -51,7 +51,9 @@ async function updateDbEntry({
*/
if (!data || !Object.keys(data).length) return null;
const isMaster = dbContext?.match(/dsql.user/i)
const isMaster = useLocal
? true
: dbContext?.match(/dsql.user/i)
? false
: dbFullName && !dbFullName.match(/^datasquirel$/)
? false