How to use vm2 - 10 common examples

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 CapacitorSet / box-js / analyze.js View on Github external
// See https://github.com/nodejs/node/issues/8071#issuecomment-240259088
// It will prevent console.log from calling the "inspect" property,
// which can be kinda messy with Proxies
require("util").inspect.defaultOptions.customInspect = false;

if (argv["dangerous-vm"]) {
	lib.verbose("Analyzing with native vm module (dangerous!)");
	const vm = require("vm");
	vm.runInNewContext(code, sandbox, {
		displayErrors: true,
		// lineOffset: -fs.readFileSync(path.join(__dirname, "patch.js"), "utf8").split("\n").length,
		filename: "sample.js",
	});
} else {
	lib.debug("Analyzing with vm2 v" + require("vm2/package.json").version);
	const vm = new VM({
		timeout: (argv.timeout || 10) * 1000,
		sandbox,
	});

	vm.run(code);
}

function ActiveXObject(name) {
	lib.verbose(`New ActiveXObject: ${name}`);
	name = name.toLowerCase();
	if (name.match("xmlhttp") || name.match("winhttprequest"))
		return require("./emulator/XMLHTTP");
	if (name.match("dom")) {
		return {
			createElement: require("./emulator/DOM"),
github wavebox / waveboxapp / src / app / src / Extensions / Chrome / CRExtensionRuntime / CRExtensionWebRequest / CRExtensionWebRequest.js View on Github external
url: details.url,
      method: details.method,
      frameId: 0,
      parentFrameId: -1,
      tabId: details.webContentsId,
      type: details.resourceType,
      timeStamp: details.timestamp
    }
    const lambdaScript = `
      (function(request) {
        ${this._blockingOnBeforeRequestScript.js}
      })(${JSON.stringify(request)})
    `

    // Run our guest code
    const vm = new VM()
    let modifier
    try {
      modifier = vm.run(lambdaScript)
    } catch (ex) {
      this._blockingOnBeforeRequestErrorSuppress.total++
      if (new Date().getTime() - this._blockingOnBeforeRequestErrorSuppress.last > BLOCKING_ON_BEFORE_REQUEST_ERROR_SUPPRESS_MS) {
        this._blockingOnBeforeRequestErrorSuppress.last = new Date().getTime()
        console.error([
          `Extension Error: Failed to execute blocking onBeforeRequest for extension`,
          `    Extension ID: ${this.extension.id}`,
          `    Subsequent errors will not be reported for another ${BLOCKING_ON_BEFORE_REQUEST_ERROR_SUPPRESS_MS}ms`,
          `    Total Errorred runs: ${this._blockingOnBeforeRequestErrorSuppress.total}`,
          `    Below is a log of the failed code:`,
          '    ---------------',
          '',
          lambdaScript,
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 Cherrison / CrackMinApp / nodejs / nodejs / wuWxss.js View on Github external
//    handle.cssFile = path.resolve(frameName, "..", name);
      //    wxAppCode[name]();
      // }
 
      let wxAppCode = {};
      let handle = {cssFile: name};
      let gg = new GwxCfg();
      let tsandbox = {
         $gwx: GwxCfg.prototype["$gwx"],
         __mainPageFrameReady__: GwxCfg.prototype["$gwx"],   //解决 $gwx is not defined
         __vd_version_info__: GwxCfg.prototype["$gwx"],  //解决 __vd_version_info__ is not defined
         __wxAppCode__: wxAppCode,
         setCssToHead: cssRebuild.bind(handle)
      }
 
      let vm = new VM({sandbox: tsandbox});
      vm.run(code);
      for (let name in wxAppCode) {
         if (name.endsWith(".wxss")) {
            handle.cssFile = path.resolve(frameName, "..", name);
            wxAppCode[name]();
         }
      }
   }
	function preRun(dir,frameFile,mainCode,files,cb){
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 jsreport / jsreport-core / lib / render / safeSandbox.js View on Github external
run: (code, { filename, mainFilename, mainSource } = {}) => {
      const script = new VMScript(code, filename)
      const prefix = errorPrefix != null ? errorPrefix : 'Error ocurred.'

      // NOTE: if we need to upgrade vm2 we will need to check the source of this function
      // in vm2 repo and see if we need to change this,
      // we needed to override this method because we want "displayErrors" to be true in order
      // to show nice error when the compile of a script fails
      script.compile = function compile () {
        if (this._compiled) return this

        this._compiled = new originalVM.Script(this.code, {
          filename: this.filename,
          displayErrors: true
        })

        return this
      }
github BiancoRoyal / node-red-contrib-modbus / src / modbus-flex-server.js View on Github external
this.serverAddress = config.serverAddress || '0.0.0.0'
    this.serverPort = parseInt(config.serverPort)
    this.responseDelay = parseInt(config.responseDelay)
    this.delayUnit = config.delayUnit
    this.unitId = config.unitId
    this.minAddress = config.minAddress
    this.splitAddress = config.splitAddress
    this.showErrors = config.showErrors

    this.funcGetCoil = new VMScript(config.funcGetCoil).compile()
    this.funcGetDiscreteInput = new VMScript(config.funcGetDiscreteInput).compile()
    this.funcGetInputRegister = new VMScript(config.funcGetInputRegister).compile()
    this.funcGetHoldingRegister = new VMScript(config.funcGetHoldingRegister).compile()

    this.funcSetCoil = new VMScript(config.funcSetCoil).compile()
    this.funcSetRegister = new VMScript(config.funcSetRegister).compile()

    let node = this
    node.bufferFactor = 8

    node.coilsBufferSize = parseInt(config.coilsBufferSize * node.bufferFactor)
    node.registersBufferSize = parseInt(config.registersBufferSize * node.bufferFactor)

    node.coils = Buffer.alloc(node.coilsBufferSize, 0)
    node.registers = Buffer.alloc(node.registersBufferSize, 0)

    node.modbusServer = null

    mbBasics.setNodeStatusTo('initialized', node)

    //     1...10000*  address - 1      Coils (outputs)    0   Read/Write
    // 10001...20000*  address - 10001  Discrete Inputs    01  Read
github harpagon210 / steemsmartcontracts / libs / SmartContracts.js View on Github external
await actions[api.action](api.payload);
                done(null);
              }
            } catch (error) {
              done(error);
            }
          }

          execute();
        `;

        // the code of the smart contarct comes as a Base64 encoded string
        codeTemplate = codeTemplate.replace('###ACTIONS###', Base64.decode(code));

        // compile the code for faster executions later on
        const script = new VMScript(codeTemplate).compile();

        const tables = {};

        // prepare the db object that will be available in the VM
        const db = {
          // createTable is only available during the smart contract deployment
          createTable: (tableName, indexes = []) => SmartContracts.createTable(
            ipc, tables, name, tableName, indexes,
          ),
          // perform a query find on a table of the smart contract
          find: (table, query, limit = 1000, offset = 0, indexes = []) => SmartContracts.find(
            ipc, name, table, query, limit, offset, indexes,
          ),
          // perform a query find on a table of an other smart contract
          findInTable: (contractName, table, query, limit = 1000, offset = 0, index = '', descending = false) => SmartContracts.find(
            ipc, contractName, table, query, limit, offset, index, descending,
github staticdeploy / app-server / test / getAppServerRouter / configuration.ts View on Github external
function getInjectedAPP_CONFIG(body: string) {
    const $ = load(body);
    const scriptContent = $("script#app-config").html();
    const vm = new VM({ sandbox: { window: {} } });
    vm.run(scriptContent!);
    return vm.run("window.APP_CONFIG");
}

vm2

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

MIT
Latest version published 2 years ago

Package Health Score

43 / 100
Full package analysis