How to use the vm2.NodeVM function in vm2

To help you get started, we’ve selected a few vm2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github azu / power-doctest / packages / @power-doctest / tester / src / index.ts View on Github external
process.addListener("unhandledRejection", listener);
            });
            // clearTimeout
            clearTimeout(timeoutId);
        };
        process.on("uncaughtException", uncaughtException);
        process.on("unhandledRejection", unhandledRejection as any);
        const poweredCode = convertCode(code, {
            assertAfterCallbackName: postCallbackName,
            filePath: filePath
        });
        // total count of assert
        const totalAssertionCount = poweredCode.split(CALLBACK_FUNCTION_NAME).length - 1;
        // current count of assert
        let countOfExecutedAssertion = 0;
        const vm = new NodeVM({
            console: options.console ? "inherit" : "off",
            timeout: timeout,
            sandbox: {
                [postCallbackName]: (_id: string) => {
                    countOfExecutedAssertion++;
                    if (runMode === "all" && countOfExecutedAssertion === totalAssertionCount) {
                        // when all finish
                        restoreListener();
                        resolve();
                    } else if (runMode === "any") {
                        // when anyone finish
                        restoreListener();
                        resolve();
                    }
                },
                // User defined context
github n8n-io / n8n / packages / nodes-base / nodes / FunctionItem.node.ts View on Github external
const options = {
			console: 'inherit',
			sandbox,
			require: {
				external: false,
				builtin: [] as string[],
				root: './',
			}
		};

		if (process.env.NODE_FUNCTION_ALLOW_BUILTIN) {
			options.require.builtin = process.env.NODE_FUNCTION_ALLOW_BUILTIN.split(',');
		}

		const vm = new NodeVM(options);

		// Get the code to execute
		const functionCode = this.getNodeParameter('functionCode') as string;


		let jsonData: IDataObject;
		try {
			// Execute the function code
			jsonData = await vm.run(`module.exports = async function() {${functionCode}}()`);
		} catch (e) {
			return Promise.reject(e);
		}

		// Do very basic validation of the data
		if (jsonData === undefined) {
			throw new Error('No data got returned. Always an object has to be returned!');
github dataform-co / dataform / api / vm / query.ts View on Github external
export function compile(query: string, projectDir?: string): string {
  let compiledQuery = query;
  if (projectDir) {
    const vm = new NodeVM({
      wrapper: "none",
      require: {
        context: "sandbox",
        root: projectDir,
        external: true
      },
      sourceExtensions: ["js", "sql"],
      compiler: (code, path) => compiler(code, path)
    });
    // This use of genIndex needs some rethinking. It uses the version built into
    // @dataform/api instead of @dataform/core, which would be more correct, as done in compile.ts.
    // Possibly query compilation as a whole needs a redesign.
    const indexScript = indexFileGenerator(
      createGenIndexConfig(
        { projectDir },
        `(function() {
github imgcook-dsl / react-standard / test / index.js View on Github external
const co = require('co');
const xtpl = require('xtpl');
const fs = require('fs');
const thunkify = require('thunkify');
const path = require('path');
const prettier = require('prettier');
const { NodeVM } = require('vm2');
const _ = require('lodash');
const data = require('./data');

const vm = new NodeVM({
  console: 'inherit',
  sandbox: {}
});

co(function*() {
  const xtplRender = thunkify(xtpl.render);
  const code = fs.readFileSync(
    path.resolve(__dirname, '../src/index.js'),
    'utf8'
  );
  const renderInfo = vm.run(code)(data, {
    prettier: prettier,
    _: _,
    responsive: {
      width: 750,
      viewportWidth: 375
github ArkEcosystem / desktop-wallet / src / renderer / services / plugin-manager / plugin-sandbox.js View on Github external
getComponentVM () {
    return new NodeVM({
      sandbox: {
        ...this.sandbox,
        walletApi: this.walletApi
      },
      require: {
        builtin: [],
        context: 'sandbox',
        external: {
          modules: [],
          transitive: true
        },
        root: [
          path.resolve(this.plugin.fullPath)
        ]
      }
    })
github dataform-co / dataform / api / vm / compile.ts View on Github external
const findCompiler = (): CompilerFunction => {
    try {
      return (
        indexGeneratorVm.run('return require("@dataform/core").compiler', vmIndexFileName) ||
        legacyCompiler.compile
      );
    } catch (e) {
      return legacyCompiler.compile;
    }
  };
  const compiler = findCompiler();
  if (!compiler) {
    throw new Error("Could not find compiler function.");
  }

  const userCodeVm = new NodeVM({
    wrapper: "none",
    require: {
      context: "sandbox",
      root: compileConfig.projectDir,
      external: true
    },
    sourceExtensions: ["js", "sql", "sqlx"],
    compiler
  });

  const res: string = userCodeVm.run(
    findGenIndex()(createGenIndexConfig(compileConfig)),
    vmIndexFileName
  );
  return res;
}
github embark-framework / embark / src / lib / core / modules / coderunner / vm.ts View on Github external
private setupNodeVm(cb: Callback) {
    this.vm = new NodeVM(this.options);
    cb();
  }
github chrismaltby / gb-studio / src / components / library / GBScriptEditor.js View on Github external
import { debounce } from "lodash";
import ScriptBuilder from "../../lib/compiler/scriptBuilder";

import "brace/ext/language_tools";
import "brace/theme/tomorrow";
import "brace/mode/javascript";
import "brace/ext/searchbox";
import {
  getSceneActors,
  getSpriteSheets
} from "../../reducers/entitiesReducer";
import { ActorShape, SpriteShape } from "../../reducers/stateShape";

const sb = new ScriptBuilder();

const vm = new NodeVM({
  timeout: 1000,
  sandbox: {}
});

const wordList = Object.keys(sb)
  .filter(key => {
    return typeof sb[key] === "function";
  })
  .map(key => {
    window.sb = sb;
    const fnArgs = String(sb[key])
      .replace(/[\s\S]=>[\s\S]+/g, "")
      .replace(/[()]/g, "")
      .replace(/(.*)/, "($1)");
    return {
      caption: key + fnArgs,
github rung-tools / rung-cli / src / vm.js View on Github external
export function createVM(strings) {
    const vm = new NodeVM({
        require: {
            external: true
        }
    });

    vm.freeze(compileHTML, '__render__');
    vm.freeze(translator(strings), '_');

    return vm;
}
github browserless / chrome / src / puppeteer-provider.ts View on Github external
if (this.config.demoMode) {
      jobdebug(`${jobId}: Running in demo-mode, closing with 403.`);
      return this.server.rejectReq(req, res, 403, 'Unauthorized', false);
    }

    if (!this.queue.hasCapacity) {
      jobdebug(`${jobId}: Too many concurrent and queued requests, rejecting with 429.`);
      return this.server.rejectReq(req, res, 429, `Too Many Requests`);
    }

    if (detached) {
      jobdebug(`${jobId}: Function is detached, resolving request.`);
      res.json({ id: jobId });
    }

    const vm = new NodeVM({
      require: {
        builtin,
        external,
        root: './node_modules',
      },
    });
    const handler: (args: any) => Promise = vm.run(code, `browserless-function-${jobId}.js`);
    const earlyClose = () => {
      jobdebug(`${job.id}: Function terminated prior to execution removing from queue`);
      this.removeJob(job);
    };

    const job: IJob = Object.assign(
      (done: IDone) => {
        const doneOnce = _.once(done);
        const debug = (message: string) => jobdebug(`${job.id}: ${message}`);

vm2

vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules. Securely!

MIT
Latest version published 12 months ago

Package Health Score

43 / 100
Full package analysis