Eval and Dynamic Code Execution Errors
Eval and Dynamic Code Execution Errors
JavaScript's eval() function and similar dynamic code execution methods frequently conflict with CSP:
// Common Error: eval() blocked
// Console: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not
// an allowed source of script in the following Content Security Policy directive
// PROBLEM: Code using eval()
const userCode = getUserInput();
eval(userCode); // CSP violation
// SOLUTION 1: Replace eval with safer alternatives
// Instead of eval for JSON parsing:
// BAD:
const data = eval('(' + jsonString + ')');
// GOOD:
const data = JSON.parse(jsonString);
// SOLUTION 2: Replace eval for dynamic property access
// BAD:
const value = eval('obj.' + propertyPath);
// GOOD:
function getNestedProperty(obj, path) {
return path.split('.').reduce((current, key) => current?.[key], obj);
}
const value = getNestedProperty(obj, propertyPath);
// SOLUTION 3: Replace eval for mathematical expressions
// BAD:
const result = eval(mathExpression);
// GOOD: Use a safe expression parser
class SafeMathParser {
constructor() {
this.operators = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => a / b,
'^': (a, b) => Math.pow(a, b)
};
}
parse(expression) {
// Remove whitespace and validate
expression = expression.replace(/\s/g, '');
if (!/^[\d+\-*/^().]+$/.test(expression)) {
throw new Error('Invalid expression');
}
// Convert to postfix notation and evaluate
return this.evaluatePostfix(this.toPostfix(expression));
}
// ... implementation details ...
}
// SOLUTION 4: For templating engines requiring eval
// Use CSP-compatible alternatives:
// Instead of lodash templates with eval:
const template = _.template(templateString); // Uses eval internally
// Use a CSP-safe templating engine:
const Handlebars = require('handlebars');
const template = Handlebars.compile(templateString); // No eval required