Safely sandbox and execute user submitted JavaScript?

后端 未结 5 1600
别跟我提以往
别跟我提以往 2020-11-30 00:52

I would like to have the ability to let users submit arbitrary JavaScript code, which is then sent to a Node.JS server and safely executed before the output is sent back to

5条回答
  •  执笔经年
    2020-11-30 01:17

    You can use sandbox support in nodejs with vm.runInContext('js code', context), sample in api documentation:

    https://nodejs.org/api/vm.html#vm_vm_runinthiscontext_code_options

    const util = require('util');
    const vm = require('vm');
    
    const sandbox = { globalVar: 1 };
    vm.createContext(sandbox);
    
    for (var i = 0; i < 10; ++i) {
        vm.runInContext('globalVar *= 2;', sandbox);
    }
    console.log(util.inspect(sandbox));
    
    // { globalVar: 1024 }
    

    WARN: As pointed by "s4y" it seems to be flawled. Please look at the comments.

提交回复
热议问题