/* global before, describe, it, require, arraymultiplier, __dirname */ 'use strict'; var fs = require('fs') , vm = require('vm') , chai = require('chai') , Browser = require('zombie') , expect = chai.expect; var arraymultiplierBuf = fs.readFileSync(__dirname + '/../../app/scripts/arraymultiplier.js') , arraymultiplierScript = arraymultiplierBuf.toString() .replace(/\/*.*\//g, '') .replace(/\n/g, '') , evaluateArraymultiplierScript = new vm.Script(arraymultiplierScript); evaluateArraymultiplierScript.runInThisContext(); describe('Scripts', function () { it('returns the product of three array items', function () { expect(arraymultiplier([1, 2, 3])).to.equal(6); }); }); describe('Headless A-B tests', function () { var browser = new Browser({site: 'http://localhost:9001'}); before(function (done) { browser.visit('/', done); }); it('should find h1 children', function () {
before(function() { // runs foreclosure.js file in the context above const script = new vm.Script(foreclosure); script.runInNewContext(context); });
common = require('../common'); assert = common.assert; var Script = require('vm').Script; common.debug('run in a new empty context'); var context = Script.createContext(); var result = Script.runInContext('"passed";', context); assert.equal('passed', result); common.debug('create a new pre-populated context'); context = Script.createContext({'foo': 'bar', 'thing': 'lala'}); assert.equal('bar', context.foo); assert.equal('lala', context.thing); common.debug('test updating context'); result = Script.runInContext('var foo = 3;', context); assert.equal(3, context.foo); assert.equal('lala', context.thing);
assert.throws(function() { script.runInNewContext(); }, /test/);
assert.throws(() => { script.runInThisContext(script); }, /^Error: test$/);
var common = require('../common'); var assert = require('assert'); var Script = require('vm').Script; common.globalCheck = false; common.debug('run a string'); var script = new Script('\'passed\';'); common.debug('script created'); var result1 = script.runInNewContext(); var result2 = script.runInNewContext(); assert.equal('passed', result1); assert.equal('passed', result2); common.debug('thrown error'); script = new Script('throw new Error(\'test\');'); assert.throws(function() { script.runInNewContext(); }); common.debug('undefined reference'); var error; script = new Script('foo.bar = 5;'); try { script.runInNewContext(); } catch (e) { error = e; } assert.ok(error);
res.pipe(concat({encoding: 'string'}, function(data) { const script = new vm.Script(data) const context = {} script.runInNewContext(context) callback(null, context['es2015-i18n-tag']) }))
module.exports = (worker, done) => { let vm = require('vm'); let clone = require('clone'); let nunjucks = require('nunjucks'); let dateFilter = require('nunjucks-date-filter'); let _ = require('lodash'); let util = require('../../util/util'); // Configure nunjucks to not watch any files let environment = nunjucks.configure([], { watch: false, autoescape: false }); environment.addFilter('is_string', function(obj) { return _.isString(obj); }); environment.addFilter('is_array', function(obj) { return _.isArray(obj); }); environment.addFilter('is_object', function(obj) { return _.isPlainObject(obj); }); environment.addFilter('date', dateFilter); environment.addFilter('submissionTable', function(obj, components) { return new nunjucks.runtime.SafeString(util.renderFormSubmission(obj, components)); }); environment.addFilter('componentValue', function(obj, key, components) { var compValue = util.renderComponentValue(obj, key, components); return new nunjucks.runtime.SafeString(compValue.value); }); environment.addFilter('componentLabel', function(key, components) { var label = key; if (!components.hasOwnProperty(key)) { return label; } var component = components[key]; label = component.label || component.placeholder || component.key; return label; }); let filters = worker.filters || {}; Object.keys(filters).forEach(filter => { try { // Essentially eval, but it only gets executed in a vm within a child process. environment.addFilter(filter, new Function(`return ${filters[filter].toString()}`)()); } catch (e) { // TODO: Add user logs to fix issues with email templates. /* eslint-disable no-console */ console.log(e); /* eslint-enable no-console */ } }); let getScript = (data) => { if (typeof data === 'string') { // Script to render a single string. return ` environment.params = clone(context); if (context._private) { delete context._private; } output = environment.renderString(input, context); `; } // Script to render an object of properties. return ` environment.params = clone(context); if (context._private) { delete context._private; } context._rendered = {}; for (var prop in input) { if (input.hasOwnProperty(prop)) { context._rendered[prop] = output[prop] = environment.renderString( environment.renderString(input[prop], context), context ); } } `; }; let render = worker.render; let context = worker.context || {}; // Convert all toString functions back to functions. let functions = worker._functions || []; functions.forEach(key => { context[key] = new Function(`return ${context[key].toString()}`)(); }); // Build the sandbox context with our dependencies let sandbox = { clone, environment, input: render, context, output: (typeof render === 'string' ? '' : {}) }; let script = new vm.Script(getScript(render)); try { script.runInContext(vm.createContext(sandbox), {timeout: 15000}); } catch (e) { /* eslint-disable no-console */ console.log(e.message); console.log(e.stack); /* eslint-enable no-console */ return done({resolve: null}); } return done({resolve: sandbox.output}); };
var vm = require('vm'); var util = require('util'); var sandbox = { globalVar: 1, require:require, console:console }; var context = vm.createContext(sandbox); var script = new vm.Script('var u=require("util"); u.log(typeof require)', { filename: 'myfile.vm' }); script.runInContext(context); console.log(util.inspect(context));
exec(code, name) { const script = new vm.Script(code, name); return script.runInContext(this.context); }
function runScript (content) { const script = new Script(content); const sandbox = {}; script.runInNewContext(sandbox); return sandbox.globals; }
function createContext() { var ctx = vm.createContext(Object.defineProperty({}, "console", { value: { log: log } })); func_toString.runInContext(ctx); return ctx; }
assert.throws(function() { script.runInThisContext(script); });
var common = require('../common'); var assert = require('assert'); var Script = require('vm').Script; var script = new Script('"passed";'); common.debug('run in a new empty context'); var context = script.createContext(); var result = script.runInContext(context); assert.equal('passed', result); common.debug('create a new pre-populated context'); context = script.createContext({'foo': 'bar', 'thing': 'lala'}); assert.equal('bar', context.foo); assert.equal('lala', context.thing); common.debug('test updating context'); script = new Script('foo = 3;'); result = script.runInContext(context); assert.equal(3, context.foo); assert.equal('lala', context.thing); // Issue GH-227: Script.runInNewContext('', null, 'some.js');
util.eachComponent(this.form.components, function(component) { // By default, each field is shown. show[component.key] = true; // Only change display options if all required conditional properties are present. if ( component.conditional && (component.conditional.show !== null && component.conditional.show !== '') && (component.conditional.when !== null && component.conditional.when !== '') ) { // Default the conditional values. component.conditional.show = boolean[component.conditional.show]; component.conditional.eq = component.conditional.eq || ''; // Get the conditional component. var cond = util.getComponent(this.form.components, component.conditional.when.toString()); if (!cond) { return; } var value = submission.data[cond.key]; if (value && typeof value !== 'object') { // Check if the conditional value is equal to the trigger value show[component.key] = value.toString() === component.conditional.eq.toString() ? boolean[component.conditional.show] : !boolean[component.conditional.show]; } // Special check for check boxes component. else if (value && typeof value === 'object') { // Check if the conditional trigger value is true. show[component.key] = boolean[value[component.conditional.eq].toString()]; } // Check against the components default value, if present and the components hasnt been interacted with. else if (!value && cond.defaultValue) { show[component.key] = cond.defaultValue.toString() === component.conditional.eq.toString() ? boolean[component.conditional.show] : !boolean[component.conditional.show]; } // If there is no value, we still need to process as not equal. else { show[component.key] = !boolean[component.conditional.show]; } } // Custom conditional logic. else if (component.customConditional) { try { // Create the sandbox. var sandbox = vm.createContext({ data: submission.data }); // Execute the script. var script = new vm.Script(component.customConditional); script.runInContext(sandbox, { timeout: 250 }); if (boolean.hasOwnProperty(sandbox.show)) { show[component.key] = boolean[sandbox.show]; } else { show[component.key] = true; } } catch (e) { debug('Custom Conditional Error: '); debug(e); // Default to true, if a validation error occurred. show[component.key] = true; } } }.bind(this));
define(["require", "q", "./runtime-util"], function(rjs, Q, util) { var ourCajaVM; function unsafeCaja() { var compileExpr = function(src) { return function(env) { var define = env.define; return Function("define", src)(define); } }; ourCajaVM = { compileExpr: compileExpr }; } if(util.isBrowser()) { // caja.js had better be on the page already if(typeof caja === "undefined") { console.warn("Page was loaded without SES, so evals will be unguarded. Does this page load https://caja.appspot.com/caja.js?"); unsafeCaja(); } else { caja.initialize({ debug: true, forceES5Mode: true }); caja.load(undefined, undefined, function(frame) { ourCajaVM = { compileExpr: function(s) { return function(env) { frame.code("https://", "application/javascript", s).api(env).run(); } } }; }); } } else { var FS = require("fs"); var VM = require("vm"); var RUN_SES = false; // NOTE(joe): skipping on servers for now; SES isn't really there yet if(RUN_SES) { var source = FS.readFileSync(require.nodeRequire.resolve("ses/initSES.js")); var oldLog = console.log; console.log = function() { /* intentional no-op to suppress SES logging */ } var script = new VM.Script(source); script.runInThisContext(); ourCajaVM = cajaVM; console.log = oldLog; } else { unsafeCaja(); } } function safeEval(string, env) { var f = ourCajaVM.compileExpr(string); return f(env); } function loadClosure(runtime, mod, dependencies) { var deferred = Q.defer(); try { var answer = mod.apply(null, dependencies); deferred.resolve(answer); } catch(e) { deferred.reject(e); } return deferred.promise; } function loadSingle(runtime, src, dependencies) { var deferred = Q.defer(); try { safeEval(src, { define: function(_, body) { try { // NOTE(joe): dependencies should be empty list, or the whole // object should just be passed in here var moduleAsObject = body.apply(null, dependencies); // NOTE(joe): modules should be objects, but old ones are // functions if(typeof moduleAsObject === "function") { deferred.resolve(moduleAsObject); } else { deferred.resolve(moduleAsObject.theModule.apply(null, dependencies)); } } catch(e) { deferred.reject(e); } } }); } catch(e) { deferred.reject(e); } return deferred.promise; } function goodIdea(runtime, name, src) { var deferred = Q.defer(); require.undef(name); try { safeEval(src, { define: function(deps, body) { define(name, deps, body); function success(val) { deferred.resolve(val); } // Since requirejs seems to not call our errback, use its global // error handler. var oldOnError = require.onError; require.onError = function(err) { require.onError = oldOnError; var names = []; for(var i = 0; i < err.requireModules.length; i++) { require.undef(err.requireModules[i]); names.push(err.requireModules[i]); } deferred.reject(runtime.makePyretFailException(runtime.ffi.makeModuleLoadFailureL(names))); }; require([name], success); } }); } catch(e) { deferred.reject(e); } return deferred.promise; } return { safeEval: safeEval, goodIdea: goodIdea, loadSingle: loadSingle, loadClosure: loadClosure } });
Validator.prototype.validate = function(submission, next) { var valid = true; var error = null; debug('Starting validation'); // Skip validation if no data is provided. if (!submission.data) { debug('No data skipping validation'); return next(); } // Using the submission, determine which fields are supposed to be shown; Only validate displayed fields. this.buildIgnoreList(submission); // Build the validator schema. this.buildSchema(); /** * Invoke the Joi validator with our data. * * @type {function(this:Validator)} */ var joiValidate = function() { Joi.validate(submission.data, this.schema, {stripUnknown: true}, function(validateErr, value) { if (validateErr) { debug(validateErr); return next(validateErr); } next(null, value); }); }.bind(this); // Check for custom validations. for (var key in this.customValidations) { // If there is a value for this submission.... if (this.customValidations.hasOwnProperty(key) && (submission.data[key] !== undefined)) { var component = this.customValidations[key]; // Try a new sandboxed validation. try { // Replace with variable substitutions. component.validate.custom = component.validate.custom.replace(/({{\s+(.*)\s+}})/, function(match, $1, $2) { return submission.data[$2]; }); // Create the sandbox. var sandbox = vm.createContext({ input: submission.data[key], component: component, valid: valid }); // Execute the script. var script = new vm.Script(component.validate.custom); script.runInContext(sandbox, { timeout: 100 }); valid = sandbox.valid; } catch (err) { // Say this isn't valid based on bad code executed... valid = err.toString(); } // If there is an error, then set the error object and break from iterations. if (valid !== true) { error = { message: valid, path: key, type: component.type + '.custom' }; break; } } } // If an error has occured in custom validation, fail immediately. if (error) { var temp = {name: 'ValidationError', details: [error]}; debug(error); return next(temp); } // Iterate through each of the unique keys. var uniques = _.keys(this.unique); if (uniques.length > 0) { async.eachSeries(uniques, function(key, done) { var component = this.unique[key]; // Unique fields must always be set with a value. debug('Key: ' + key); if ( !submission.data.hasOwnProperty(key) && !submission.data[key] ) { // Throw an error if this isn't a resource field. if (key.indexOf('.') === -1) { debug('Unique field: ' + key + ', was not a resource field.'); return done(new Error('Unique fields cannot be empty.')); } else { return done(); } } // Get the query. var query = {form: util.idToBson(submission.form)}; query['data.' + key] = submission.data[key]; // Only search for non-deleted items. if (!query.hasOwnProperty('deleted')) { query['deleted'] = {$eq: null}; } // Try to find an existing value within the form. debug(query); this.model.findOne(query, function(err, result) { if (err) { debug(err); return done(err); } if (result && submission._id && (result._id.toString() === submission._id)) { return done(); } if (result) { return done(new Error(component.label + ' must be unique.')); } done(); }); }.bind(this), function(err) { if (err) { return next(err.message); } joiValidate(); }); } else { joiValidate(); } };
// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; const common = require('../common'); const assert = require('assert'); const Script = require('vm').Script; // Run a string let script = new Script('\'passed\';'); const result = script.runInThisContext(script); assert.strictEqual('passed', result); // Thrown error script = new Script('throw new Error(\'test\');'); assert.throws(() => { script.runInThisContext(script); }, /^Error: test$/); global.hello = 5; script = new Script('hello = 2'); script.runInThisContext(script); assert.strictEqual(2, global.hello);
// Copyright & License details are available under JXCORE_LICENSE file var common = require('../common'); var assert = require('assert'); var Script = require('vm').Script; common.globalCheck = false; common.debug('run a string'); var result = Script.runInThisContext('\'passed\';'); assert.equal('passed', result); common.debug('thrown error'); assert.throws(function() { Script.runInThisContext('throw new Error(\'test\');'); }); hello = 5; Script.runInThisContext('hello = 2'); assert.equal(2, hello); common.debug('pass values'); code = 'foo = 1;' + 'bar = 2;' + 'if (typeof baz !== \'undefined\') throw new Error(\'test fail\');'; foo = 2; obj = { foo: 0, baz: 3 }; var baz = Script.runInThisContext(code); assert.equal(0, obj.foo);
'use strict'; const Test = require('tape'); const Util = require('util'); const Fs = require('fs'); const Vm = require('vm'); const Path = require('path'); let filePath = Path.resolve(__dirname, './../index.js'); const IndexFileRaw = Fs.readFileSync( filePath, { encoding: 'utf8' }); let sandbox = {}; const Script = new Vm.Script(IndexFileRaw, { filename: 'index.js' }); Script.runInNewContext(sandbox); Test('Js-Basics', suite => { Test('Variables with String values', t => { t.ok(sandbox.firstName, 'firstName variable exists.'); t.ok(sandbox.lastName, 'lastName variable exists.'); t.ok(sandbox.birthPlace, 'birthPlace variable exists.'); t.end(); }); Test('Variables with Number values', t => { t.ok(sandbox.favoriteNumber, 'favoriteNumber variable exists.'); t.ok(sandbox.currentYear, 'currentYear variable exists.'); t.ok(sandbox.thatOnePrinceSong, 'thatOnePrinceSong variable exists.'); t.end(); });
assert.throws(function() { Script.runInThisContext('throw new Error(\'test\');'); });
[{fn: function() {}}, 'fn=', {'fn': ''}], [{fn: new Function('')}, 'fn=', {'fn': ''}], [{math: Math}, 'math=', {'math': ''}], [{e: extendedFunction}, 'e=', {'e': ''}], [{d: new Date()}, 'd=', {'d': ''}], [{d: Date}, 'd=', {'d': ''}], [{f: new Boolean(false), t: new Boolean(true)}, 'f=&t=', {'f': '', 't': ''}], [{f: false, t: true}, 'f=false&t=true', {'f': 'false', 't': 'true'}], [{n: null}, 'n=', {'n': ''}], [{nan: NaN}, 'nan=', {'nan': ''}], [{inf: Infinity}, 'inf=', {'inf': ''}] ]; // }}} var Script = require('vm').Script; var foreignObject = Script.runInContext('({"foo": ["bar", "baz"]})', Script.createContext()); var qsNoMungeTestCases = [ ['', {}], ['foo=bar&foo=baz', {'foo': ['bar', 'baz']}], ['foo=bar&foo=baz', foreignObject], ['blah=burp', {'blah': 'burp'}], ['gragh=1&gragh=3&goo=2', {'gragh': ['1', '3'], 'goo': '2'}], ['frappucino=muffin&goat%5B%5D=scone&pond=moose', {'frappucino': 'muffin', 'goat[]': 'scone', 'pond': 'moose'}], ['trololol=yes&lololo=no', {'trololol': 'yes', 'lololo': 'no'}] ]; assert.strictEqual('918854443121279438895193', qs.parse('id=918854443121279438895193').id);
var vm = require('vm'); var fs = require('fs'); global.count1 = 100; var count2 = 100; var script = new vm.Script(fs.readFileSync('script.js','utf8')); script.runInThisContext({filename: 'count.vm'}); console.log(count1); console.log(count2);
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; const common = require('../common'); const assert = require('assert'); const Script = require('vm').Script; common.globalCheck = false; console.error('run a string'); let script = new Script('\'passed\';'); console.error('script created'); const result1 = script.runInNewContext(); const result2 = script.runInNewContext(); assert.strictEqual('passed', result1); assert.strictEqual('passed', result2); console.error('thrown error'); script = new Script('throw new Error(\'test\');'); assert.throws(function() { script.runInNewContext(); }, /test/); console.error('undefined reference'); script = new Script('foo.bar = 5;');
this._init = function() { var propertiesObj = propsReader(filePath); var allProperties = propertiesObj.getAllProperties(); var scriptString = "'use strict';" + "var result = "; /** * Cache all require rules */ var requieredKeys = []; for(var ruleKey in propRules) { var rule = propRules[ruleKey]; if(rule['required'] === true) { requieredKeys.push(ruleKey); } } /** * Loop all properties */ for(var propsKey in allProperties) { var oldValue = allProperties[propsKey]; var newValue = undefined; if(oldValue == undefined || oldValue === "") { /** * In case value is undefined or empty say the new value is string * No need to pull the correct type from vm */ newValue = ""; } else { /** * GET THE CORRECT VARIABLE BY TYPE 'false'/'true' will be * converted to false/true '100' will be converted to 100 */ var context = new vm.createContext(sandbox); try{ // Primitive OR sandbox function OR javascript exprection var script = new vm.Script(scriptString + oldValue + ";"); script.runInContext(context); } catch(e) { // String var script = new vm.Script(scriptString + "\"" + oldValue + "\"" + ";"); script.runInContext(context); } newValue = sandbox["result"]; } //Fetch props rule by key string var propsValidate = propRules[propsKey]; if(!propsValidate) { /** * Case key not found by string means it could be an regex * run on all rules and find the maching one */ for(var validateKey in propRules) { if( propsKey.match(new RegExp(validateKey, "i")) ) { propsValidate = propRules[validateKey]; break; } } } if(propsValidate) { /** * Validate the rule type */ var type = typeof(newValue); if(type != propsValidate.type) { throw new Error("Config file contain invalid value for [" + propsKey + "], Expected:[" + propsValidate.type + "], Got:[" + type + "]"); } /** * Validate is the rule is required , update and remove from the required list */ if(propsValidate['required']) { for(var requireIndex in requieredKeys) { if(propsKey.match(new RegExp(requieredKeys[requireIndex], "i"))) { break; } } if(requireIndex) { requieredKeys.splice(requireIndex, 1); } } if(propsValidate['onDetect']) { var detectResult = propsValidate.onDetect(propsKey, newValue); if(detectResult === false) { throw new Error("Config file contain invalid value for [" + propsKey + "], Expected:[" + propsValidate.type + "], Got:[" + type + "] (Fail on detection)"); } } } /** * All passed, update the prop */ this.properties[propsKey] = newValue; } if(requieredKeys.length > 0) { var missingKeys = requieredKeys.join(", "); throw new Error("Config file is missing requiered fields [" + missingKeys + "]"); } };
assert.throws(function() { script.runInNewContext(); }, /f is not defined/);
function exec(code, filename, context) { var script = new vm_1.Script(code, { filename: filename }); return script.runInNewContext(context); }