Update safeParseJson to check for dangerous object keys recursively
Improve detection of prototype pollution patterns in JSON parsing
This commit is contained in:
+22
-15
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user