Files
bun-mariadb/src/lib/mariadb/db-update.ts
T
tbenandClaude Opus 5.5 b81b09324a 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]>
2026-10-14 02:10:35 +01:00

175 lines
4.4 KiB
TypeScript

import dbHandler from "../db-handler";
import _ from "lodash";
import type {
BunMariaDBConfig,
DBResponseObject,
SQLInsertGenValueType,
ServerQueryParam,
} 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 },
Table extends string = string,
> = {
table: Table;
data: Schema;
query?: ServerQueryParam<Schema>;
targetId?: number | string;
config?: BunMariaDBConfig;
};
export default async function DbUpdate<
Schema extends { [k: string]: any } = { [k: string]: any },
Table extends string = string,
>({
table,
data,
query,
targetId,
config,
}: Params<Schema, Table>): Promise<DBResponseObject> {
let sqlObj: ReturnType<typeof sqlGenerator> = {
string: "",
values: [],
where: "",
whereValues: [],
};
try {
let finalQuery = query || {};
if (targetId) {
finalQuery = _.merge<ServerQueryParam<any>, ServerQueryParam<any>>(
finalQuery,
{
query: {
id: {
value: Number(targetId),
},
},
},
);
}
const sqlQueryObj = sqlGenerator({
tableName: table,
genObject: finalQuery,
});
const whereClause = sqlQueryObj.where;
if (!whereClause) {
return {
success: false,
msg: `No WHERE clause`,
};
}
/**
* 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`;
const sanitizedData = sanitizeHtmlFields({
table,
data,
config,
});
const finalData: { [k: string]: SQLInsertGenValueType } = {
updated_at: Date.now(),
...sanitizedData,
};
const keys = Object.keys(finalData);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (!key) continue;
const isLast = i == keys.length - 1;
sql += ` ${quoteIdentifier(key)}=?`;
values.push(finalData[key] ?? null);
if (!isLast) {
sql += `,`;
}
}
const idPlaceholders = matched_ids.map(() => "?").join(",");
sql += ` WHERE id IN (${idPlaceholders})`;
values = [...values, ...matched_ids];
const res = await dbHandler({
query: sql,
values: values as any,
config,
});
sqlObj.string = sql;
sqlObj.values = values as any[];
if (res.error) {
return { ...res, debug: { sqlObj } };
}
const updated_res = await dbHandler({
query: `SELECT * FROM ${quoteIdentifier(table)} WHERE id IN (${idPlaceholders})`,
values: matched_ids,
config,
});
return {
...updated_res,
debug: {
sqlObj,
},
db_res: res.db_res,
};
} catch (error: any) {
return {
success: false,
error: error.message,
debug: {
sqlObj,
},
};
}
}