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:
2026-10-14 02:10:35 +01:00
co-authored by Claude Opus 5.5
parent 155263a79f
commit b81b09324a
23 changed files with 603 additions and 382 deletions
+9 -1
View File
@@ -54,7 +54,15 @@ export default async function dbHandler<
const res_array = (() => {
try {
return JSON.parse(JSON.stringify(res)) as T[];
return JSON.parse(
JSON.stringify(res, (_key, value) =>
typeof value == "bigint"
? Number.isSafeInteger(Number(value))
? Number(value)
: value.toString()
: value,
),
) as T[];
} catch (error) {
return undefined;
}
+4 -6
View File
@@ -6,6 +6,7 @@ import type {
ServerQueryParam,
} from "../../types";
import sqlGenerator from "../../utils/sql-generator";
import { quoteIdentifier } from "../../utils/sql-identifier";
type Params<
Schema extends { [k: string]: any } = { [k: string]: any },
@@ -17,10 +18,6 @@ type Params<
config?: BunMariaDBConfig;
};
function quoteIdentifier(identifier: string): string {
return `\`${identifier.replace(/`/g, "``")}\``;
}
export default async function DbDelete<
Schema extends { [k: string]: any } = { [k: string]: any },
Table extends string = string,
@@ -49,11 +46,11 @@ export default async function DbDelete<
}
sqlObj = sqlGenerator({
tableName: quoteIdentifier(table),
tableName: table,
genObject: finalQuery,
});
const whereClause = sqlObj.string.match(/WHERE .*/)?.[0];
const whereClause = sqlObj.where;
if (!whereClause) {
return {
@@ -68,6 +65,7 @@ export default async function DbDelete<
let sql = `DELETE FROM ${quoteIdentifier(table)} ${whereClause}`;
sql += ` RETURNING *`;
sqlObj.string = sql;
sqlObj.values = sqlObj.whereValues;
const res = await dbHandler({
query: sql,
+11 -13
View File
@@ -4,6 +4,7 @@ import type {
BunMariaDBConfig,
} from "../../types";
import generateTypeDefinition from "./db-generate-type-defs";
import resolveTable from "../schema/resolve-table";
type Params = {
dbSchema: BUN_MARIADB_DatabaseSchemaType;
@@ -32,20 +33,17 @@ export default function dbSchemaToType({
const schemas = dbTablesSchemas
.map((table) => {
let final_table = _.cloneDeep(table);
const has_parent = Boolean(
table.parentTableName &&
dbTablesSchemas.find(
(t) => t.tableName === table.parentTableName,
),
);
if (final_table.parentTableName) {
const parent_table = dbTablesSchemas.find(
(t) => t.tableName === final_table.parentTableName,
);
if (parent_table) {
final_table = _.merge(parent_table, {
tableName: final_table.tableName,
tableDescription: final_table.tableDescription,
});
}
}
// Merge parent fields into a copy; never mutate the parent schema
const final_table = has_parent
? resolveTable(table, datasquirelSchema)
: _.cloneDeep(table);
const defObj = generateTypeDefinition({
paradigm: "TypeScript",
+2 -6
View File
@@ -18,10 +18,6 @@ type Params<
config?: BunMariaDBConfig;
};
function quoteIdentifier(identifier: string): string {
return `\`${identifier.replace(/`/g, "``")}\``;
}
export default async function DbSelect<
Schema extends { [k: string]: any } = { [k: string]: any },
Table extends string = string,
@@ -51,7 +47,7 @@ export default async function DbSelect<
}
sqlObj = sqlGenerator({
tableName: quoteIdentifier(table),
tableName: table,
genObject: finalQuery,
});
@@ -87,7 +83,7 @@ export default async function DbSelect<
if (count) {
const countSqlObject = sqlGenerator({
tableName: quoteIdentifier(table),
tableName: table,
genObject: finalQuery,
count,
});
+8 -2
View File
@@ -1,14 +1,19 @@
import dbHandler from "../db-handler";
import type { DBResponseObject, SQLInsertGenValueType } from "../../types";
import type {
BunMariaDBConfig,
DBResponseObject,
SQLInsertGenValueType,
} from "../../types";
type Params = {
sql: string;
values?: SQLInsertGenValueType[];
config?: BunMariaDBConfig;
};
export default async function DbSQL<
T extends { [k: string]: any } = { [k: string]: any },
>({ sql, values }: Params): Promise<DBResponseObject<T>> {
>({ sql, values, config }: Params): Promise<DBResponseObject<T>> {
try {
const trimmedSql = sql.trim();
const isSelect = trimmedSql.match(/^select/i);
@@ -16,6 +21,7 @@ export default async function DbSQL<
const res = await dbHandler<T>({
query: trimmedSql,
values: values as any,
config,
});
if (!res.success) {
+50 -20
View File
@@ -8,6 +8,7 @@ import type {
} from "../../types";
import sqlGenerator from "../../utils/sql-generator";
import sanitizeHtmlFields from "../../utils/sanitize-html-fields";
import { quoteIdentifier } from "../../utils/sql-identifier";
type Params<
Schema extends { [k: string]: any } = { [k: string]: any },
@@ -20,10 +21,6 @@ type Params<
config?: BunMariaDBConfig;
};
function quoteIdentifier(identifier: string): string {
return `\`${identifier.replace(/`/g, "``")}\``;
}
export default async function DbUpdate<
Schema extends { [k: string]: any } = { [k: string]: any },
Table extends string = string,
@@ -34,7 +31,12 @@ export default async function DbUpdate<
targetId,
config,
}: Params<Schema, Table>): Promise<DBResponseObject> {
let sqlObj: ReturnType<typeof sqlGenerator> = { string: "", values: [] };
let sqlObj: ReturnType<typeof sqlGenerator> = {
string: "",
values: [],
where: "",
whereValues: [],
};
try {
let finalQuery = query || {};
@@ -53,11 +55,11 @@ export default async function DbUpdate<
}
const sqlQueryObj = sqlGenerator({
tableName: quoteIdentifier(table),
tableName: table,
genObject: finalQuery,
});
const whereClause = sqlQueryObj.string.match(/WHERE .*/)?.[0];
const whereClause = sqlQueryObj.where;
if (!whereClause) {
return {
@@ -66,6 +68,38 @@ export default async function DbUpdate<
};
}
/**
* Capture the matching row ids first, so the updated rows can be
* re-fetched even if the update changes a column used in the WHERE
* clause.
*/
const matched_res = await dbHandler<{ id: number }>({
query: `SELECT id FROM ${quoteIdentifier(table)} ${whereClause}`,
values: sqlQueryObj.whereValues as any,
config,
});
if (!matched_res.success) {
return {
...matched_res,
success: false,
debug: { sqlObj: sqlQueryObj },
};
}
const matched_ids = (matched_res.payload || [])
.map((row) => row.id)
.filter((id) => id !== undefined && id !== null);
if (matched_ids.length === 0) {
return {
success: false,
msg: "No rows matched the update query",
payload: [],
debug: { sqlObj: sqlQueryObj },
};
}
let values: SQLInsertGenValueType[] = [];
let sql = ``;
sql += `UPDATE ${quoteIdentifier(table)} SET`;
@@ -97,8 +131,10 @@ export default async function DbUpdate<
}
}
sql += ` ${whereClause}`;
values = [...values, ...sqlQueryObj.values];
const idPlaceholders = matched_ids.map(() => "?").join(",");
sql += ` WHERE id IN (${idPlaceholders})`;
values = [...values, ...matched_ids];
const res = await dbHandler({
query: sql,
@@ -106,22 +142,16 @@ export default async function DbUpdate<
config,
});
if (res.error) {
return res;
}
sqlObj.string = sql;
sqlObj.values = values as any[];
let updated_sql = ``;
let updated_sql_values: any[] = [];
updated_sql += `SELECT * FROM ${quoteIdentifier(table)} ${whereClause}`;
updated_sql_values = [...sqlQueryObj.values];
if (res.error) {
return { ...res, debug: { sqlObj } };
}
const updated_res = await dbHandler({
query: updated_sql,
values: updated_sql_values,
query: `SELECT * FROM ${quoteIdentifier(table)} WHERE id IN (${idPlaceholders})`,
values: matched_ids,
config,
});