Comments (8)
I have updated the docs so the difference between VM and NodeVM should be clear now.
from vm2.
You can do that with vm2.
var vm = require('vm2');
var vm = new vm.VM();
vm.run('var dummy = 15;');
console.log(vm.run('dummy')); // Outputs 15
Your code doesn't work btw, throws:
ReferenceError: dummy is not defined
from vm2.
My example was a quick hack - let me be more specific.
Let's say we have a js file that contains the following js code
eval(userScript);
var results = [];
for (var i = 0 ; i < fooObjects.length; i++) {
results.push(echo(i));
}
output = JSON.stringify(results);
Let's call this file 'helper.js'.
Additionally - users have the ability to supply their own js code that is meant to interact with the code in 'helper.js'. So - a user can supply the following js (this code is in a file called 'userScript.js' ) ...
function echo(num) {
return doSomething(num) ;
}
function doSomething(num) {
console.log("in 'doSomething' method. 'num' = " + num);
return num * 2;
}
Using Node's existing VM - I can do the following in NodeJS ...
const fs = require('fs');
const vm = require('vm');
var helper = fs.readFileSync(__dirname + '/helper.js', { encoding: "utf8" });
var userScript = fs.readFileSync(__dirname + '/userScript.js', { encoding: "utf8" });
var sandbox = {
input: JSON.parse('[1,2,3]');
output: "",
userScript: userScript,
log: [],
console: {
log: function(arg) { sandbox.log.push(arg); }
}
};
var context = vm.createContext(sandbox);
var script = new vm.Script(helper);
script.runInContext(context);
console.log('output', sandbox.output); // prints a string representation of the json for the results array
console.log('log', sandbox.log); // prints the "in 'doSomething' method. 'num' = ..." messages that were added to the sandbox.log array by the doSomething method
This is obviously a contrived example - but the 'mechanics' of how the 'helper.js' code eval's the 'userScript.js' code is the same as in my working example. How can I do this using VW2 ?
Thanks
Dave
from vm2.
Hope it helps.
var vm = require('vm2');
var helper = 'var log = [], console = {log: function(msg) { log.push(msg) }}; (function() { eval(userScript); return {output: multiply(input), log: log} })();';
var userScript = 'function multiply(num) { console.log("test"); return num * 2; }';
var vm = new vm.VM({
sandbox: {
input: 5,
userScript: userScript
}
});
var result = vm.run(helper);
console.log(result.output);
console.log(result.log);
from vm2.
Hi
Using your instructions above - I was able to replicate the base functionality of the default 'vm' using vm2.
The next step is to be able to allow users to 'require' modules (I think they're called modules - I'm new to NodeJS).
Continuing the example above - let's say my user wants to use the 'requests' module/library to retrieve data from some webservice endpoints. I need to be able to do something like this (note the change in the userScript ...
var vm = require('vm2');
var helper = 'var log = [], console = {log: function(msg) { log.push(msg) }}; (function() { eval(userScript); return {output: multiply(input), log: log} })();';
var userScript = 'var request = require('request'); /* function which uses 'request' would go here * / function multiply(num) { console.log("test"); return num * 2; }';
var vm = new vm.VM({
sandbox: {
input: 5,
userScript: userScript
},
require: true,
requireExternal: true
});
var result = vm.run(helper);
console.log(result.output);
console.log(result.log);
When I try and run the above - what used to work (before I added the "var request = require('request');") no longer does. I get the following error ..
undefined:1
var request = require('request');
^
ReferenceError: require is not defined
at eval (eval at <anonymous> (vm:5:10), <anonymous>:1:15)
at vm:5:5
at vm:22:2
at VM.run (/Users/dekhaus/node_modules/vm2/lib/main.js:196:19)
at executeScript (/Users/dekhaus/projects/django/itriage/node/server.js:111:22)
at IncomingMessage.<anonymous> (/Users/dekhaus/projects/django/itriage/node/server.js:42:24)
at emitNone (events.js:67:13)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:893:12)
at doNTCallback2 (node.js:430:9)
How do I call 'require' in my user supplied script ?
Thanks
Dave
from vm2.
You need to instantiate the vm.NodeVM
class rather than vm.VM
class.
from vm2.
@patriksimek
I'm struggling with this as well. Can you document the difference between vm.VM and vm.NodeVM ?
With the example:
var testVM = require('vm2').NodeVM;
var options = {
require: true
};
var vm = new testVM(options);
var result = vm.run("require('request')");
console.log(result);
Throws the error:
throw new VMError("Access denied to require '" + modulename + "'", "
from vm2.
Hi @patriksimek , i m new to the concept of vm and i am in the middle of implementing a concept wrt vm2 utilization, but, i am finding it difficult to make the implementation since i have found very less documentation and examples on the usage of all its available options. (or may be i couldn't find the proper available resource). Kindly help me with the resources that i can refer in order to proceed with my implementation.
from vm2.
Related Issues (20)
- VM and NodeVM behaves differently on await HOT 3
- Any tips for improving performance of `vm.run()`? HOT 9
- [VM2 Sandbox Escape] Vulnerability in [email protected] HOT 13
- Sandbox Escape in [email protected] HOT 3
- Adding a Security Policy HOT 1
- Modules not loading any more? HOT 16
- Overriding functions of objects from sandbox parameter inside NodeVM HOT 3
- Accessing .buffer property on a Float32Array HOT 8
- Lib memory leak HOT 8
- Hello, is there any way to make the large functions in node equal to those in VM2? Or not isolate large functions? HOT 16
- Usage with NextJS HOT 8
- this.pathResolve is not a function in 3.9.18 HOT 2
- Work in a bundle HOT 3
- Use external modules without filesystem access HOT 1
- Typescript Set transpilation issues
- Node's test runner not available as builtin
- Isolating Imported Modules
- Discontinued HOT 63
- [content removed for the very unfriendly management] HOT 3
- vm2 Sandbox Escape vulnerability (Github Dependabot Issue) HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from vm2.