forked from longtao.wu/droboticflow
🛡️ Validate database browser UI inputs
This commit is contained in:
parent
f9c85e5483
commit
6ccc467eba
@ -34,3 +34,199 @@ export function buildDatabaseBrowserPageOptions({ limitText, skipText }) {
|
||||
error: errors.join("; "),
|
||||
};
|
||||
}
|
||||
|
||||
function isRecord(value) {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function hasEmptyPathSegment(value) {
|
||||
return value.startsWith(".") || value.endsWith(".") || value.includes("..");
|
||||
}
|
||||
|
||||
function containsNUL(value) {
|
||||
return value.includes("\u0000");
|
||||
}
|
||||
|
||||
function parseJSONRecord(rawValue, field) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(String(rawValue ?? "").trim() || "{}");
|
||||
} catch (_error) {
|
||||
throw new Error(`${field} must be a valid JSON object`);
|
||||
}
|
||||
if (!isRecord(parsed)) {
|
||||
throw new Error(`${field} must be a JSON object`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function firstIssue(issues) {
|
||||
return issues[0] || "";
|
||||
}
|
||||
|
||||
export function validateDatabaseCollectionName(value, { field = "collection name" } = {}) {
|
||||
const name = String(value ?? "").trim();
|
||||
if (!name) {
|
||||
return `${field} is required`;
|
||||
}
|
||||
if (name === "." || name === "..") {
|
||||
return `${field} is invalid`;
|
||||
}
|
||||
if (containsNUL(name)) {
|
||||
return `${field} cannot contain NUL bytes`;
|
||||
}
|
||||
if (/[\\/]/.test(name)) {
|
||||
return `${field} cannot contain path separators`;
|
||||
}
|
||||
if (name.includes("$")) {
|
||||
return `${field} cannot contain $`;
|
||||
}
|
||||
if (name.toLowerCase().startsWith("system.")) {
|
||||
return `${field} cannot use the reserved system prefix`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export function validateDatabaseIndexName(value, { required = false } = {}) {
|
||||
const name = String(value ?? "").trim();
|
||||
if (!name) {
|
||||
return required ? "index name is required" : "";
|
||||
}
|
||||
if (name === "_id_") {
|
||||
return "index name _id_ is reserved";
|
||||
}
|
||||
if (containsNUL(name)) {
|
||||
return "index name cannot contain NUL bytes";
|
||||
}
|
||||
if (/[\\/]/.test(name)) {
|
||||
return "index name cannot contain path separators";
|
||||
}
|
||||
if (name.includes("$")) {
|
||||
return "index name cannot contain $";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export function validateDatabaseIndexKeys(keys) {
|
||||
if (!isRecord(keys)) {
|
||||
return "index keys must be a JSON object";
|
||||
}
|
||||
const entries = Object.entries(keys);
|
||||
if (entries.length === 0) {
|
||||
return "index keys are required";
|
||||
}
|
||||
for (const [key, value] of entries) {
|
||||
const trimmedKey = key.trim();
|
||||
if (!trimmedKey) {
|
||||
return "index keys cannot contain empty field names";
|
||||
}
|
||||
if (containsNUL(trimmedKey)) {
|
||||
return "index keys cannot contain NUL bytes";
|
||||
}
|
||||
if (trimmedKey.startsWith("$")) {
|
||||
return "index keys cannot contain Mongo operator keys";
|
||||
}
|
||||
if (hasEmptyPathSegment(trimmedKey)) {
|
||||
return "index keys cannot contain empty path segments";
|
||||
}
|
||||
const normalizedDirection = String(value).trim().toLowerCase();
|
||||
if (!["1", "1.0", "-1", "-1.0", "text", "hashed", "2d", "2dsphere"].includes(normalizedDirection)) {
|
||||
return "index key direction must be 1, -1, text, hashed, 2d, or 2dsphere";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export function parseDatabaseIndexKeysText(rawValue) {
|
||||
const keys = parseJSONRecord(rawValue, "index keys");
|
||||
const error = validateDatabaseIndexKeys(keys);
|
||||
if (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
export function validateDatabaseFilter(value, { field = "filter" } = {}) {
|
||||
return firstIssue(validateDatabaseFilterValue(value, field));
|
||||
}
|
||||
|
||||
function validateDatabaseFilterValue(value, field) {
|
||||
const issues = [];
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item, index) => {
|
||||
issues.push(...validateDatabaseFilterValue(item, `${field}[${index}]`));
|
||||
});
|
||||
return issues;
|
||||
}
|
||||
if (!isRecord(value)) {
|
||||
return issues;
|
||||
}
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
const trimmedKey = key.trim();
|
||||
const itemField = trimmedKey ? `${field}.${trimmedKey}` : field;
|
||||
if (!trimmedKey) {
|
||||
issues.push(`${field} cannot contain empty field names`);
|
||||
continue;
|
||||
}
|
||||
if (containsNUL(trimmedKey)) {
|
||||
issues.push(`${field} cannot contain NUL bytes`);
|
||||
continue;
|
||||
}
|
||||
if (trimmedKey === "$where") {
|
||||
issues.push(`${field} cannot use the $where operator`);
|
||||
continue;
|
||||
}
|
||||
if (!trimmedKey.startsWith("$") && hasEmptyPathSegment(trimmedKey)) {
|
||||
issues.push(`${field} cannot contain empty path segments`);
|
||||
continue;
|
||||
}
|
||||
issues.push(...validateDatabaseFilterValue(item, itemField));
|
||||
}
|
||||
return issues;
|
||||
}
|
||||
|
||||
export function parseDatabaseFilterText(rawValue) {
|
||||
const filter = parseJSONRecord(rawValue, "filter");
|
||||
const error = validateDatabaseFilter(filter);
|
||||
if (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
return filter;
|
||||
}
|
||||
|
||||
export function validateDatabaseDocumentPayload(value, { field = "document" } = {}) {
|
||||
if (!isRecord(value)) {
|
||||
return `${field} must be a JSON object`;
|
||||
}
|
||||
if (Object.keys(value).length === 0) {
|
||||
return `${field} is required`;
|
||||
}
|
||||
return firstIssue(validateDatabaseDocumentValue(value, field));
|
||||
}
|
||||
|
||||
function validateDatabaseDocumentValue(value, field) {
|
||||
const issues = [];
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item, index) => {
|
||||
issues.push(...validateDatabaseDocumentValue(item, `${field}[${index}]`));
|
||||
});
|
||||
return issues;
|
||||
}
|
||||
if (!isRecord(value)) {
|
||||
return issues;
|
||||
}
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
const trimmedKey = key.trim();
|
||||
const itemField = trimmedKey ? `${field}.${trimmedKey}` : field;
|
||||
if (!trimmedKey) {
|
||||
issues.push(`${field} cannot contain empty field names`);
|
||||
continue;
|
||||
}
|
||||
if (trimmedKey.startsWith("$")) {
|
||||
issues.push(`${field} cannot contain Mongo operator keys`);
|
||||
continue;
|
||||
}
|
||||
issues.push(...validateDatabaseDocumentValue(item, itemField));
|
||||
}
|
||||
return issues;
|
||||
}
|
||||
|
||||
@ -18,7 +18,14 @@ import {
|
||||
} from "lucide-react";
|
||||
import { cn } from "../lib/utils";
|
||||
import { formatCompactDateTime } from "../lib/datetime";
|
||||
import { buildDatabaseBrowserPageOptions } from "../lib/database-browser.js";
|
||||
import {
|
||||
buildDatabaseBrowserPageOptions,
|
||||
parseDatabaseFilterText,
|
||||
parseDatabaseIndexKeysText,
|
||||
validateDatabaseCollectionName,
|
||||
validateDatabaseDocumentPayload,
|
||||
validateDatabaseIndexName,
|
||||
} from "../lib/database-browser.js";
|
||||
import type {
|
||||
DatabaseCollectionSummary,
|
||||
DatabaseIndexSummary,
|
||||
@ -256,10 +263,19 @@ export default function DatabaseBrowser() {
|
||||
setQueryError(pageOptions.error);
|
||||
return null;
|
||||
}
|
||||
let filter: Record<string, any>;
|
||||
try {
|
||||
filter = parseDatabaseFilterText(filterText) as Record<string, any>;
|
||||
} catch (error) {
|
||||
setQueryLoading(false);
|
||||
setQueryResult(null);
|
||||
setQueryError(error instanceof Error ? error.message : "查询条件格式错误");
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const item = await databaseApi.queryCollection(collection.name, {
|
||||
connectionId: selectedConnectionId,
|
||||
filter: filterText,
|
||||
filter: safeJSONStringify(filter),
|
||||
limit: pageOptions.limit,
|
||||
skip: pageOptions.skip,
|
||||
});
|
||||
@ -665,6 +681,11 @@ export default function DatabaseBrowser() {
|
||||
setCollectionActionError("请输入集合名称。");
|
||||
return;
|
||||
}
|
||||
const validationError = validateDatabaseCollectionName(name);
|
||||
if (validationError) {
|
||||
setCollectionActionError(validationError);
|
||||
return;
|
||||
}
|
||||
setCollectionActionLoading(true);
|
||||
setCollectionActionError("");
|
||||
try {
|
||||
@ -691,6 +712,11 @@ export default function DatabaseBrowser() {
|
||||
setCollectionActionError("请输入新的集合名称。");
|
||||
return;
|
||||
}
|
||||
const validationError = validateDatabaseCollectionName(newName, { field: "new collection name" });
|
||||
if (validationError) {
|
||||
setCollectionActionError(validationError);
|
||||
return;
|
||||
}
|
||||
setCollectionActionLoading(true);
|
||||
setCollectionActionError("");
|
||||
try {
|
||||
@ -748,6 +774,10 @@ export default function DatabaseBrowser() {
|
||||
setDocumentActionError("");
|
||||
try {
|
||||
const document = parseEditorDocument();
|
||||
const validationError = validateDatabaseDocumentPayload(document);
|
||||
if (validationError) {
|
||||
throw new Error(validationError);
|
||||
}
|
||||
const currentDocumentId = documentIdValue(selectedDocument);
|
||||
const result =
|
||||
!isNewDocumentMode && currentDocumentId
|
||||
@ -780,13 +810,14 @@ export default function DatabaseBrowser() {
|
||||
setIndexesError("请先选择集合。");
|
||||
return;
|
||||
}
|
||||
const indexNameError = validateDatabaseIndexName(indexDraftName);
|
||||
if (indexNameError) {
|
||||
setIndexesError(indexNameError);
|
||||
return;
|
||||
}
|
||||
let keys: Record<string, any>;
|
||||
try {
|
||||
const parsed = JSON.parse(indexDraftKeys);
|
||||
if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") {
|
||||
throw new Error("索引 keys 必须是 JSON 对象。");
|
||||
}
|
||||
keys = parsed as Record<string, any>;
|
||||
keys = parseDatabaseIndexKeysText(indexDraftKeys) as Record<string, any>;
|
||||
} catch (error) {
|
||||
setIndexesError(error instanceof Error ? error.message : "索引定义格式错误");
|
||||
return;
|
||||
|
||||
@ -1,7 +1,16 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { buildDatabaseBrowserPageOptions, parseDatabaseBrowserPageNumber } from "../../src/lib/database-browser.js";
|
||||
import {
|
||||
buildDatabaseBrowserPageOptions,
|
||||
parseDatabaseBrowserPageNumber,
|
||||
parseDatabaseFilterText,
|
||||
parseDatabaseIndexKeysText,
|
||||
validateDatabaseCollectionName,
|
||||
validateDatabaseDocumentPayload,
|
||||
validateDatabaseIndexName,
|
||||
validateDatabaseIndexKeys,
|
||||
} from "../../src/lib/database-browser.js";
|
||||
|
||||
test("database browser page parser keeps blank values as defaults", () => {
|
||||
assert.deepEqual(parseDatabaseBrowserPageNumber("", { field: "Limit", defaultValue: 50, minValue: 1 }), {
|
||||
@ -50,3 +59,40 @@ test("database browser page options collect query errors before API calls", () =
|
||||
"Limit must be an integer; Skip must be greater than or equal to 0",
|
||||
);
|
||||
});
|
||||
|
||||
test("database browser collection name validator mirrors backend reserved names", () => {
|
||||
assert.equal(validateDatabaseCollectionName("orders_2026"), "");
|
||||
assert.match(validateDatabaseCollectionName("system.profile"), /reserved system prefix/);
|
||||
assert.match(validateDatabaseCollectionName("orders/archive"), /path separators/);
|
||||
assert.match(validateDatabaseCollectionName("orders$archive"), /cannot contain \$/);
|
||||
});
|
||||
|
||||
test("database browser index validators reject unsafe index definitions", () => {
|
||||
assert.equal(validateDatabaseIndexName("orders_created_at"), "");
|
||||
assert.match(validateDatabaseIndexName("_id_"), /reserved/);
|
||||
assert.deepEqual(parseDatabaseIndexKeysText('{ "createdAt": -1, "status": 1 }'), {
|
||||
createdAt: -1,
|
||||
status: 1,
|
||||
});
|
||||
assert.equal(validateDatabaseIndexKeys({ name: "text", location: "2dsphere" }), "");
|
||||
assert.match(validateDatabaseIndexKeys({ $where: 1 }), /operator keys/);
|
||||
assert.match(validateDatabaseIndexKeys({ "metadata..name": 1 }), /empty path segments/);
|
||||
assert.throws(() => parseDatabaseIndexKeysText('{ "createdAt": "ascending" }'), /index key direction/);
|
||||
});
|
||||
|
||||
test("database browser filter parser rejects unsafe query operators before API calls", () => {
|
||||
assert.deepEqual(parseDatabaseFilterText('{ "$or": [{ "status": "open" }, { "priority": { "$in": [1, 2] } }] }'), {
|
||||
$or: [{ status: "open" }, { priority: { $in: [1, 2] } }],
|
||||
});
|
||||
assert.deepEqual(parseDatabaseFilterText(""), {});
|
||||
assert.throws(() => parseDatabaseFilterText('{ "$where": "return true" }'), /cannot use the \$where operator/);
|
||||
assert.throws(() => parseDatabaseFilterText('{ "metadata..name": "demo" }'), /empty path segments/);
|
||||
assert.throws(() => parseDatabaseFilterText('{ "": "demo" }'), /empty field names/);
|
||||
});
|
||||
|
||||
test("database browser document payload validator rejects empty and operator-key documents", () => {
|
||||
assert.equal(validateDatabaseDocumentPayload({ name: "demo", nested: [{ count: 1 }] }), "");
|
||||
assert.match(validateDatabaseDocumentPayload({}), /required/);
|
||||
assert.match(validateDatabaseDocumentPayload({ $set: { name: "demo" } }), /operator keys/);
|
||||
assert.match(validateDatabaseDocumentPayload({ nested: [{ $inc: { count: 1 } }] }), /operator keys/);
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user