I'm making a math-teaching webpage (NodeJS backend and Angular frontend). I want a special kind of users (creator) to create mathematical exercises. One of these exercises can look like this:
Marie has ${nums[0]} oranges and ${nums[1]} apples. How many fruits does she have?
Now I want the creator to write a number generating function like this:
const generate = () => {
  const nums = new Array(2).fill(0).map(e => Math.floor(Math.random() * 10)
  return { nums: nums, answer: nums.reduce((p, c) => p + c, 0) }
}
This function should be send to the server and stored. When the user want to try the test, the question should be executed on the server. What should I do to protect the server from malicious code like:
const generate = () => {
  process.exit()
}
                Really short answer, this is never really safe for the server. It is impossible to prove that a program is safe. There are mitigations such as sandboxing that help, but it is ultimately always a risk. For this application, possibly an unnecessary one.
Consider some way of communicating the formula that does not require exec. One way might be to send an abstract syntax tree of some sort, or to parse the mathematical expression.
This npm package seems promising. Fill a math expression string template the same way you fill the written question template. It might be necessary to provide another object to define what random numbers are needed and map them to names for use in the templates. math-expression-evaluator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With