0

I am working on a test case visualizer where the user can run his code and check if it is correct. I'm using Node Js and I'm getting user's code from a text-area. Assuming that this is what I'm getting from the user:

function add(x, y) {
    return x + y;
}

And this is what I'm doing at the backend:

app.post("/main", function(req, res) {
    console.log("hello");
    var x = 1;
    var y = 2;
    req.body.code //missing
})

How can I use this input as a function and run it to get the values?

1
  • 3
    And then one day, the user sends while(true); Commented May 30, 2021 at 8:59

3 Answers 3

2

Do NOT use eval() !!

Running arbitrary code from a user on your server might be the easiest way I have ever heard of to get hacked. Any user can do anything they want with your server if you do this.

There are numerous parsers (like esprima) that can parse/validate the code without actually running it. Go for one of those instead of opening the front door to your server.

Sign up to request clarification or add additional context in comments.

Comments

1

What I ended up doing is that I used vm2 sandbox

vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules. It works well, and you can limit access to certain methods.

First require it:

const { VM } = require('vm2');

then, specify the timeout, and the sandbox:

const vm = new VM({
    console: 'inherit',
    timeout: 1000,
    sandbox: { global_variable },
    require: {
        external: true,
    },
});

global_variable is nothing but a "var" that I used to export the output.

Now let's use the following function in a string named "func":

function Main(x,y){
return x+y};

concatenate it with:

global_variable.exports=Main(5,5);

Now run the code via:

vm.run("func")

To print the answer, just do:

global_variable.exports;

This solution works only if you have a javascript code that you need to run. I am still looking for other solutions that run for multiple languages in node js. If you have any suggestions please do let me know.

Comments

-2

The simplest way would be using eval() function. Say, your client passes function as a string to the server (code parameter in body). So you can do this:

Just a reminder: This method is very unsafe and it's not a good practice to use eval, so depending on you situation, you may be able to use other methods

app.post("/main", function(req, res) {
  console.log("hello");
  var x = 1;
  var y = 2;
  eval(req.body.code); // This will return an Error if code is wrong
  add(x,y);
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.