Update safeParseJson to check for dangerous object keys recursively

Improve detection of prototype pollution patterns in JSON parsing
This commit is contained in:
2026-05-06 22:38:31 +02:00
parent 579e60f5d5
commit ea792b0034
11 changed files with 1105 additions and 1129 deletions
+22 -15
View File
@@ -159,14 +159,28 @@ export function safeParseJson(jsonString: string): unknown {
throw new Error('Invalid JSON');
}
// Check for dangerous prototype pollution patterns
const reStringified = JSON.stringify(parsed);
if (
reStringified.includes('constructor') ||
reStringified.includes('prototype') ||
reStringified.includes('__proto__') ||
reStringified.includes('function')
) {
// Check for dangerous prototype pollution patterns in object keys only
const checkDangerousPatterns = (obj: unknown): boolean => {
if (typeof obj !== 'object' || obj === null) {
return false;
}
const dangerousKeys = ['constructor', 'prototype', '__proto__'];
if (dangerousKeys.some((key) => Object.keys(obj).includes(key))) {
return true;
}
// Recursively check nested objects
for (const key in obj as Record<string, unknown>) {
if (checkDangerousPatterns((obj as Record<string, unknown>)[key])) {
return true;
}
}
return false;
};
if (checkDangerousPatterns(parsed)) {
throw new Error('dangerous code pattern detected');
}
@@ -180,13 +194,6 @@ export function safeParseJson(jsonString: string): unknown {
// ==================== Path & File Utilities ====================
export function sanitizeFilePath(path: string): string {
if (path.includes('..')) {
throw new Error('Invalid path - cannot contain .. segments');
}
return path;
}
// ==================== HTTP Helpers ====================
export function isValidHttpUrl(url: string): boolean {