How to safely evaluate custom expressions

I want to parse custom expressions that check for a boolean using standard javascript, for example:

var1 > obj1.prop1 && var2 + 1 <= 5

Since these expressions are written by the user, I want to be sure that they are clean, because they will be evaluated on the server side using NodeJS.

Instead of parsing an expression as text looking for patterns and reinventing the wheel, is there a way to use Node's power to directly evaluate an expression without the risk of code injection?

+4
source share
3 answers

You may not like this answer. But you have to do the work. There is no magic bullet.

, " javascript" " ". . JavaScript 'require("fs").rmdirSync("/")'

, , JavaScript. , , .

, , . , "5", " > ", "& &" '< ='. "var1" 'obj1.prop1' 'var2'. , .

script , , , . JavaScript , , , , .

, , . , , .

+2

, , , , , , , unix. , .

root unix, nobody.

process.setgid('nobody');
process.setuid('nobody');

, , - - :

const root = global = {};
const require = function() {
  console.log('tryed to call require', arguments);
}

eval("require('fs')");

, , , ES6 import, require, import .

, , JavaScript?, vm.runInContext('globalVar *= 2;', sandbox);, . sandcastle -, , , .

, , , - , .

0

You can use the library mathjsthat comes with your own expression parser.

Website: http://mathjs.org/

0
source

Source: https://habr.com/ru/post/1651144/


All Articles