1

I am working on a project which teaches JavaScript techniques (like Code Academy). Mainly I do this for self education purposes.

I have difficulties with one important part: As the whole project is a web project, the user types in his code directly into the web site. My problem is, how do I check if the submitted code is passes all tests for the current exercise? My approach would be to eval the code and run my unit tests against it. The thing here is, how do I limit the scope for the eval'ed code and how can I test it? I already found a solution here about how to limit the scope:

function maskedEval(scr)
{
    // set up an object to serve as the context for the code
    // being evaluated. 
    var mask = {};
    // mask global properties 
    for (p in this)
        mask[p] = undefined;

    // execute script in private context
    (new Function( "with(this) { " + scr + "}")).call(mask);
}

But I don't have a solution how to run my test against the evaluated code. Is this the correct way to do this or should I do it completely different?

Community
  • 1
  • 1
nein.
  • 2,037
  • 2
  • 15
  • 17
  • 1
    why dumb it down at all? just run it and check the results and resulting side-effects. and, btw, that eval "protection" has holes large enough to drive a truck through... – dandavis Aug 08 '13 at 20:19
  • Sure, but I want to keep the user code in a separate namespace – nein. Aug 08 '13 at 20:30
  • sounds like a perfect job for an iframe. you can scan contentWindow from above to access anything you could "on-page", if the domains match as you say... – dandavis Aug 08 '13 at 20:34

1 Answers1

2

If you run the code on the client-side there is no real need to limit its scope as it can only affect the client himself.

If, however, you send the code to be evaluated on the server side you might want to look into sandboxing libraries for node.js such as http://gf3.github.io/sandbox/ (the first one I found on google, there are probably many more).

Aegis
  • 1,749
  • 11
  • 12