1

I'm working on a tool to help teach programming, and at a certain point, I am having clients send javascript as a string to a server. I am always going to call the functions A and B from their code, but I'm unsure of how to restrict their access?

What I'm doing right now:

eval(code);
userFunctionA = eval("getA");
userFunctionB = eval("getB");

var result = userFunctionA(param1, param2);

Unfourtunately by using eval, they have access to all of my global variables and other functions, how do I restrict their access?

Here's the best reference I found, but they are very concerned with "window", and since mine is a node server, I don't have a window, and I cannot use the suggested iFrame or worker: Is it possible to restrict the scope of a javascript function?

Note: I'm looking for a solution that doesn't require me to break their string of code into functions before reading them, as this would disable learning things like:

function a() {fdafs}
b = a();
a = function (x){fsadg}
Community
  • 1
  • 1
rgrambo
  • 127
  • 1
  • 1
  • 9

1 Answers1

2

If you make the eval() code its own Module then you get the benefit of the module wrapper that goes around each module when require'd. The module wrapper constrains global scope to the module. Basically, it is a form of namespacing.

So if you simply do

evaluator.js

module.exports = function(funcToCall) {
  eval(funcToCall);
}

app.js

const evaluator = require('evaluator');

evaluator(code);
peteb
  • 18,552
  • 9
  • 50
  • 62