Fix SQL injection, query value handling, and other security issues
- Quote all identifiers and validate operators, order strategies, join types, raw comparisons, and limit/offset/page in the query generator - Treat 0 as a real query value; stop null from leaving unbound placeholders - Return the WHERE clause and its values separately from sqlGenerator so delete/update no longer regex-parse generated SQL - update(): target matched row ids, re-fetch reliably, and return success: false when no rows match - Fix duplicated aliases, [object Object] select fields, AVERAGE -> AVG, escape GROUP_CONCAT separators - Fix OFFSET without LIMIT and OFFSET on count queries - Store boolean false as 0 on insert; call function values once - Verify TLS certificates by default (new ssl_reject_unauthorized option) - Confirm before importing an executable schema from an archive (--yes) - Skip symlinks when reading extracted zip archives - Only trim files matching the backup/export naming pattern - Tighten default HTML sanitizer (no style/id attributes, no button) - Stop typedef generation from mutating parent table schemas - Pass config through DbSQL; handle BigInt values in results Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+107
-81
@@ -5,9 +5,18 @@ import type {
|
||||
} from "../types";
|
||||
import sqlGenGenSearchStr from "./sql-generator-gen-search-str";
|
||||
import sqlGenGenQueryStr from "./sql-generator-gen-query-str";
|
||||
import {
|
||||
columnRef,
|
||||
quoteIdentifier,
|
||||
quoteQualified,
|
||||
sqlLogicalOperator,
|
||||
sqlNonNegativeInt,
|
||||
sqlOrderStrategy,
|
||||
} from "./sql-identifier";
|
||||
|
||||
type Param<T extends { [key: string]: any } = { [key: string]: any }> = {
|
||||
genObject?: ServerQueryParam<T>;
|
||||
/** Raw (unquoted) table name */
|
||||
tableName: string;
|
||||
dbFullName?: string;
|
||||
count?: boolean;
|
||||
@@ -16,25 +25,37 @@ type Param<T extends { [key: string]: any } = { [key: string]: any }> = {
|
||||
type Return = {
|
||||
string: string;
|
||||
values: SQLInsertGenValueType[];
|
||||
/** `WHERE ...` clause alone (empty string if none) */
|
||||
where: string;
|
||||
/** Values for the `where` clause placeholders only */
|
||||
whereValues: SQLInsertGenValueType[];
|
||||
};
|
||||
|
||||
/** MariaDB requires LIMIT before OFFSET; this is the documented "no limit" value */
|
||||
const MAX_LIMIT = "18446744073709551615";
|
||||
|
||||
/**
|
||||
* # SQL Query Generator
|
||||
* @description Builds parameterized SELECT SQL for MariaDB
|
||||
*/
|
||||
export default function sqlGenerator<
|
||||
T extends { [key: string]: any } = { [key: string]: any },
|
||||
>({ tableName, genObject, dbFullName, count }: Param<T>): Return {
|
||||
>({ tableName: rawTableName, genObject, dbFullName, count }: Param<T>): Return {
|
||||
const tableName = quoteQualified(rawTableName);
|
||||
|
||||
const finalQuery = genObject?.query ? genObject.query : undefined;
|
||||
|
||||
const queryKeys = finalQuery ? Object.keys(finalQuery) : undefined;
|
||||
|
||||
const sqlSearhValues: SQLInsertGenValueType[] = [];
|
||||
const whereValues: SQLInsertGenValueType[] = [];
|
||||
|
||||
let fullTextMatchStr = genObject?.fullTextSearch
|
||||
? ` MATCH(${genObject.fullTextSearch.fields
|
||||
.map((f) =>
|
||||
genObject.join ? `${tableName}.${String(f)}` : `${String(f)}`,
|
||||
columnRef(
|
||||
String(f),
|
||||
genObject.join ? tableName : undefined,
|
||||
),
|
||||
)
|
||||
.join(",")}) AGAINST (? IN BOOLEAN MODE)`
|
||||
: undefined;
|
||||
@@ -46,7 +67,7 @@ export default function sqlGenerator<
|
||||
.join(" ")
|
||||
: undefined;
|
||||
|
||||
let { str: queryString, values } = sqlGenGenQueryStr<T>({
|
||||
let { str: queryString, values: selectValues } = sqlGenGenQueryStr<T>({
|
||||
table_name: tableName,
|
||||
append_table_names: true,
|
||||
full_text_match_str: fullTextMatchStr,
|
||||
@@ -54,8 +75,6 @@ export default function sqlGenerator<
|
||||
genObject,
|
||||
});
|
||||
|
||||
sqlSearhValues.push(...values);
|
||||
|
||||
const sqlSearhString = queryKeys?.map((field) => {
|
||||
const queryObj = finalQuery?.[field];
|
||||
if (!queryObj) return;
|
||||
@@ -64,26 +83,30 @@ export default function sqlGenerator<
|
||||
const subQueryGroup = queryObj.__query;
|
||||
|
||||
const subSearchKeys = Object.keys(subQueryGroup);
|
||||
const subSearchString = subSearchKeys.map((_field) => {
|
||||
const newSubQueryObj = subQueryGroup?.[_field];
|
||||
const subSearchString = subSearchKeys
|
||||
.map((_field) => {
|
||||
const newSubQueryObj = subQueryGroup?.[_field];
|
||||
|
||||
if (newSubQueryObj) {
|
||||
const { str, values } = sqlGenGenSearchStr({
|
||||
queryObj: newSubQueryObj,
|
||||
field: newSubQueryObj.fieldName || _field,
|
||||
join: genObject?.join,
|
||||
table_name: tableName,
|
||||
});
|
||||
if (newSubQueryObj) {
|
||||
const { str, values } = sqlGenGenSearchStr({
|
||||
queryObj: newSubQueryObj,
|
||||
field: newSubQueryObj.fieldName || _field,
|
||||
join: genObject?.join,
|
||||
table_name: tableName,
|
||||
});
|
||||
|
||||
sqlSearhValues.push(...values);
|
||||
whereValues.push(...values);
|
||||
|
||||
return str;
|
||||
}
|
||||
});
|
||||
return str;
|
||||
}
|
||||
})
|
||||
.filter((str) => typeof str == "string");
|
||||
|
||||
return (
|
||||
"(" +
|
||||
subSearchString.join(` ${queryObj.operator || "AND"} `) +
|
||||
subSearchString.join(
|
||||
` ${sqlLogicalOperator(queryObj.operator)} `,
|
||||
) +
|
||||
")"
|
||||
);
|
||||
}
|
||||
@@ -95,7 +118,7 @@ export default function sqlGenerator<
|
||||
table_name: tableName,
|
||||
});
|
||||
|
||||
sqlSearhValues.push(...values);
|
||||
whereValues.push(...values);
|
||||
|
||||
return str;
|
||||
});
|
||||
@@ -107,97 +130,100 @@ export default function sqlGenerator<
|
||||
const isSearchStr =
|
||||
cleanedUpSearchStr?.[0] && cleanedUpSearchStr.find((str) => str);
|
||||
|
||||
let where = ``;
|
||||
|
||||
if (isSearchStr) {
|
||||
const stringOperator = genObject?.searchOperator || "AND";
|
||||
queryString += ` WHERE ${cleanedUpSearchStr.join(
|
||||
` ${stringOperator} `,
|
||||
)}`;
|
||||
const stringOperator = sqlLogicalOperator(genObject?.searchOperator);
|
||||
where += `WHERE ${cleanedUpSearchStr.join(` ${stringOperator} `)}`;
|
||||
}
|
||||
|
||||
if (genObject?.fullTextSearch && fullTextSearchStr && fullTextMatchStr) {
|
||||
queryString += `${isSearchStr ? " AND" : " WHERE"} ${fullTextMatchStr}`;
|
||||
sqlSearhValues.push(fullTextSearchStr);
|
||||
where += `${isSearchStr ? " AND" : "WHERE"} ${fullTextMatchStr}`;
|
||||
whereValues.push(fullTextSearchStr);
|
||||
}
|
||||
|
||||
if (where) {
|
||||
queryString += ` ${where}`;
|
||||
}
|
||||
|
||||
if (genObject?.group) {
|
||||
const groupRef = (
|
||||
group: string | { field: unknown; table?: string },
|
||||
) =>
|
||||
typeof group == "object"
|
||||
? columnRef(String(group.field), group.table)
|
||||
: columnRef(String(group));
|
||||
|
||||
let group_by_txt = ``;
|
||||
|
||||
if (typeof genObject.group == "string") {
|
||||
group_by_txt = genObject.group;
|
||||
} else if (Array.isArray(genObject.group)) {
|
||||
for (let i = 0; i < genObject.group.length; i++) {
|
||||
const group = genObject.group[i];
|
||||
|
||||
if (typeof group == "string") {
|
||||
group_by_txt += `\`${group.toString()}\``;
|
||||
} else if (typeof group == "object" && group.table) {
|
||||
group_by_txt += `${group.table}.${String(group.field)}`;
|
||||
} else if (typeof group == "object") {
|
||||
group_by_txt += `${String(group.field)}`;
|
||||
}
|
||||
|
||||
if (i < genObject.group.length - 1) {
|
||||
group_by_txt += ",";
|
||||
}
|
||||
}
|
||||
} else if (typeof genObject.group == "object") {
|
||||
if (genObject.group.table) {
|
||||
group_by_txt = `${genObject.group.table}.${String(genObject.group.field)}`;
|
||||
} else {
|
||||
group_by_txt = `${String(genObject.group.field)}`;
|
||||
}
|
||||
if (Array.isArray(genObject.group)) {
|
||||
group_by_txt = genObject.group
|
||||
.map((group) => groupRef(group as any))
|
||||
.join(",");
|
||||
} else {
|
||||
group_by_txt = groupRef(genObject.group as any);
|
||||
}
|
||||
|
||||
queryString += ` GROUP BY ${group_by_txt}`;
|
||||
}
|
||||
|
||||
function grabOrderString(order: ServerQueryParamOrder<T>) {
|
||||
let orderFields = [];
|
||||
let orderSrt = ``;
|
||||
const scoreAlias = genObject?.fullTextSearch?.scoreAlias;
|
||||
let orderField = ``;
|
||||
|
||||
if (genObject?.fullTextSearch && genObject.fullTextSearch.scoreAlias) {
|
||||
orderFields.push(genObject.fullTextSearch.scoreAlias);
|
||||
} else if (genObject?.join) {
|
||||
orderFields.push(`${tableName}.${String(order.field)}`);
|
||||
if (scoreAlias && String(order.field) === scoreAlias) {
|
||||
orderField = quoteIdentifier(scoreAlias);
|
||||
} else {
|
||||
orderFields.push(order.field);
|
||||
orderField = columnRef(
|
||||
String(order.field),
|
||||
genObject?.join ? tableName : undefined,
|
||||
);
|
||||
}
|
||||
|
||||
orderSrt += ` ${orderFields.join(", ")} ${order.strategy}`;
|
||||
|
||||
return orderSrt;
|
||||
return ` ${orderField} ${sqlOrderStrategy(order.strategy)}`;
|
||||
}
|
||||
|
||||
if (genObject?.order) {
|
||||
let orderSrt = ` ORDER BY`;
|
||||
const orders = (
|
||||
Array.isArray(genObject.order) ? genObject.order : [genObject.order]
|
||||
).filter(Boolean);
|
||||
|
||||
if (Array.isArray(genObject.order)) {
|
||||
for (let i = 0; i < genObject.order.length; i++) {
|
||||
const order = genObject.order[i];
|
||||
if (order) {
|
||||
orderSrt +=
|
||||
grabOrderString(order) +
|
||||
(i < genObject.order.length - 1 ? `,` : "");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
orderSrt += grabOrderString(genObject.order);
|
||||
if (orders.length) {
|
||||
queryString += ` ORDER BY${orders.map(grabOrderString).join(",")}`;
|
||||
}
|
||||
|
||||
queryString += ` ${orderSrt}`;
|
||||
}
|
||||
|
||||
if (genObject?.limit && !count) queryString += ` LIMIT ${genObject.limit}`;
|
||||
if (!count) {
|
||||
const limit =
|
||||
genObject?.limit !== undefined && genObject.limit !== null
|
||||
? sqlNonNegativeInt(genObject.limit, "limit")
|
||||
: undefined;
|
||||
|
||||
if (genObject?.offset) {
|
||||
queryString += ` OFFSET ${genObject.offset}`;
|
||||
} else if (genObject?.page && genObject.limit && !count) {
|
||||
queryString += ` OFFSET ${(genObject.page - 1) * genObject.limit}`;
|
||||
let offset: number | undefined;
|
||||
|
||||
if (genObject?.offset !== undefined && genObject.offset !== null) {
|
||||
offset = sqlNonNegativeInt(genObject.offset, "offset");
|
||||
} else if (genObject?.page && limit) {
|
||||
const page = sqlNonNegativeInt(genObject.page, "page");
|
||||
offset = Math.max(page - 1, 0) * limit;
|
||||
}
|
||||
|
||||
if (limit) {
|
||||
queryString += ` LIMIT ${limit}`;
|
||||
} else if (offset) {
|
||||
queryString += ` LIMIT ${MAX_LIMIT}`;
|
||||
}
|
||||
|
||||
if (offset) {
|
||||
queryString += ` OFFSET ${offset}`;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
string: queryString,
|
||||
values: sqlSearhValues,
|
||||
values: [...selectValues, ...whereValues],
|
||||
where,
|
||||
whereValues,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user