UNPKG

1.6 kBJavaScriptView Raw
1// Expression parser security
2//
3// Executing arbitrary expressions like enabled by the expression parser of
4// mathjs involves a risk in general. When you're using mathjs to let users
5// execute arbitrary expressions, it's good to take a moment to think about
6// possible security and stability implications, especially when running the
7// code server side.
8//
9// There is a small number of functions which yield the biggest security risk
10// in the expression parser of math.js:
11//
12// - `import` and `createUnit` which alter the built-in functionality and allow
13// overriding existing functions and units.
14// - `eval`, `parse`, `simplify`, and `derivative` which parse arbitrary input
15// into a manipulable expression tree.
16//
17// To make the expression parser less vulnerable whilst still supporting most
18// functionality, these functions can be disabled, as demonstrated in this
19// example.
20
21const math = require('../../index')
22const limitedEval = math.eval
23
24math.import({
25 'import': function () { throw new Error('Function import is disabled') },
26 'createUnit': function () { throw new Error('Function createUnit is disabled') },
27 'eval': function () { throw new Error('Function eval is disabled') },
28 'parse': function () { throw new Error('Function parse is disabled') },
29 'simplify': function () { throw new Error('Function simplify is disabled') },
30 'derivative': function () { throw new Error('Function derivative is disabled') }
31}, { override: true })
32
33console.log(limitedEval('sqrt(16)')) // Ok, 4
34console.log(limitedEval('parse("2+3")')) // Error: Function parse is disabled