I want to let users input a string that will be evaluated in math.js as an expression. What can I do to prevent malicious use of this feature?
1 Answers
What sort of malicious use do you mean?
math.js has it's own expression parser, so it is safe against for example XSS attacks. You can't just throw in arbitrary JavaScript code like with JavaScripts eval
, which can be dangerous to use.
What you can easily do though is execute an expression which blows up memory and CPU, like creating an extremely large matrix or something (math.eval('zeros(1e100, 1e100)')
).
If you want to protect against that, you will have to run the expression parser in a separate web worker (client side) or child_process (node.js server), so you can kill the process when it takes too long. You could use a library like workerpool for this. This library is used for example by the REST API of math.js (http://api.mathjs.org) to kill off expression running for more 10 sec.

- 6,602
- 3
- 38
- 58
-
Maybe he means that it is "safe to use". I have the problem that I throw in an equation and would like to use math.js to check if it is valid, but as soon as I use `math.eval(equation)` or `math.parse(equation)` the web console says `SyntaxError: Unexpected end of expression (char x)` (e.g. if it is "a+") or `Error: Undefined symbol ...` (e.g. if it is "test"). How do evaluate if the equation is correct then? Thx – Avatar Apr 02 '15 at 15:33
-
2You can put a try/catch block around your `math.eval(eq)`. If the expression is not valid, an error is thrown, which you can catch and handle. – Jos de Jong Apr 03 '15 at 06:44
-
Thanks but I do not know where to put the try catch with the scope: `var fe = function(x) { var scope = {x: x}; var expr = math.eval(func_equation, scope); return expr; };` – Avatar Apr 03 '15 at 10:40
-
Around `var expr = math.eval(func_equation, scope);`, as this method call `math.eval` can throw exceptions. – Jos de Jong Apr 03 '15 at 13:03