How to use the vm2.VMScript 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 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 flood-io / element / packages / element / src / test-script / Compiler.ts View on Github external
public get vmScript(): VMScript {
		if (!this.vmScriptMemo) {
			this.vmScriptMemo = new VMScript(this.source, this.sandboxedFilename)
		}

		return this.vmScriptMemo
	}
github samtecspg / articulate / api / lib / services / agent / agent.converse-generate-response-fallback.service.js View on Github external
username: webhook.webhookUser ? webhook.webhookUser : undefined,
            password: webhook.webhookPassword ? webhook.webhookPassword : undefined,
            templateContext: CSO
        });
        CSO.webhook = { 
            [webhook.webhookKey]: {...webhookResponse}
        };
        if (webhook.postScript){
            const vm = new VM({
                timeout: 1000,
                sandbox: {
                    CSO
                }
            });

            const script = new VMScript(webhook.postScript);
            try {
                CSO = vm.run(script);
            } catch (err) {
                console.error(`Failed to execute postScript of the webhook ${webhook.webhookKey}`, err);
            }
        }
        if (webhookResponse.textResponse) {
            return { textResponse: webhookResponse.textResponse, actions: webhookResponse.actions ? webhookResponse.actions : [], fulfilled: true, webhook: { [webhook.webhookKey]: webhookResponse }, isFallback: true };
        }
        const response = await agentService.converseCompileResponseTemplates({ responses: fallbackAction.responses, templateContext: CSO });
        return { ...response, webhook: { [webhook.webhookKey]: webhookResponse }, fulfilled: true, isFallback: true };
    }
    const selectedFallbackResponse = fallbackAction.responses[Math.floor(Math.random() * fallbackAction.responses.length)];
    return { textResponse: selectedFallbackResponse.textResponse, actions: selectedFallbackResponse.actions, fulfilled: true, isFallback: true };
};
github kristianoye / kmud / src / compiler / VM2Wrapper.js View on Github external
run(context, module) {
        var script = new VMScript(context.content, context.resolvedName);
        var vm = new NodeVM({
            console: 'inherit',
            sandbox: module.loader,
            require: {
                external: false,
                root: driver.config.mudlib.baseDirectory
            },
            nesting: true,
            wrapper: 'none'
        });
        var result = vm.run(context.content);
    }
}
github BiancoRoyal / node-red-contrib-modbus / src / modbus-flex-server.js View on Github external
const { VM, VMScript } = require('vm2')

    this.name = config.name
    this.logEnabled = config.logEnabled
    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
github pastelsky / package-build-stats / src / getParseTime.js View on Github external
function getParseTime(currentScript, trialCount = 5) {
  let baseVMScript, currentVMScript

  let baseCounter = 0
  let baseResults = []

  let currentCounter = 0
  let currentResults = []

  try {
    while (baseCounter++ < trialCount) {
      baseVMScript = new VMScript(`${Math.random()}; ${baseScript}`)
      const start = now()
      baseVMScript.compile()
      const end = now()
      baseResults.push(end - start)
    }

    while (currentCounter++ < trialCount) {
      currentVMScript = new VMScript(`${Math.random()}; ${currentScript}`)
      const start = now()
      currentVMScript.compile()
      const end = now()
      currentResults.push(end - start)
    }

    const baseMedian = stats.median(baseResults)
    const currentMedian = stats.median(currentResults)
github BiancoRoyal / node-red-contrib-modbus / src / modbus-flex-server.js View on Github external
RED.nodes.createNode(this, config)
    const { VM, VMScript } = require('vm2')

    this.name = config.name
    this.logEnabled = config.logEnabled
    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
github casual-simulation / aux / src / aux-vm-node / vm / VM2Sandbox.ts View on Github external
constructor(library: SandboxLibrary) {
        this._transpiler = new Transpiler();
        this._recursionCounter = 0;
        this._library = library;
        this._sandbox = {
            __getContext__: () => {
                return this._context;
            },
            __getVariables__: () => {
                return this._finalVars;
            },
        };

        this._script = new VMScript(`
            var __ctx__ = __getContext__();
            (function(__code) {
                let __finalVars__ = __getVariables__();
                return eval(__code);
            }).call(__ctx__.thisArg, __ctx__.code);
        `);
        this._vm = new VM({
            timeout: VM2Sandbox.DEFAULT_TIMEOUT,
            sandbox: this._sandbox,
        });
    }

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