2017-08-29 30 views
2

最近運行的代碼的結果,我一直在嘗試使用軟件包來實現沙箱執行VM2已經由@Patrik西梅克出版如何獲得這是由節點VM2

我試圖運行一些js代碼,我認爲它是一個定製邏輯,我將這個邏輯存儲在一個字符串變量中。

我需要在沙盒環境中執行此自定義邏輯(因爲這是不可信的代碼),並根據此結果取回實際環境中的響應以繼續正常的應用程序流。

我嘗試了幾種方法來獲得最終結果。自定義邏輯正在沙盒內成功執行,但我無法找到將此結果發回主進程的方式,但我得到的結果爲undefined。所以,到目前爲止沒有任何工作。

希望我在這裏得到一些答案。

定製邏輯(其將被存儲在字符串內)

function addValues(a,b){ 
    var c = a + b; 
    console.log('Addition of 2 values'); 
    console.log(c); 
    return c; 
} 

addValues(10,10); // function call 

實際實施

// vm2 
const {NodeVM} = require('vm2'); 
     const vm = new NodeVM({ 
      console: 'inherit', 
      sandbox: {}, 
      require: { 
       external: true, 
       builtin: ['fs','path'], 
       root: "./", 
       mock: { 
        fs: { 
         readFileSync() { return 'Nice try!';} 
        } 
       }, 
       wrapper : "" 
      } 
     }); 


// Sandbox function 
let functionInSandbox = vm.run("module.exports = function(customLogic){ 
            customLogic //need to execute this custom logic 
           }); 



// Make a call to execute untrusty code by passing it as an argument 
// to sandbox environment and obtain the result 

var resultOfSandbox = functionInSandbox(customLogic); 
console.log("Result of Sandbox :"); 
console.log(resultOfSandbox); // undefined (need to get the result of custom logic execution) 

回答

0

需要定義沙箱變量。聲明一個空對象,將其附加到你的沙箱選項,並在你的腳本中添加另一個屬性到你的對象。我想代碼片段會說明一切:

const c = ` 
function addValues(a,b){ 
    var c = a + b; 
    console.log('Addition of 2 values'); 
    console.log(c); 
    return c; 
} 

// we'll define ext as a sandbox variable, so it will be available 
ext.exports = addValues(10,10); // function call 
`; 

let ext = {}; 
const { NodeVM } = require('vm2'); 
const vm = new NodeVM({ 
    console: 'inherit', 
    // pass our declared ext variable to the sandbox 
    sandbox: { ext }, 
    require: { 
    external: true, 
    builtin: ['fs', 'path'], 
    root: './', 
    }, 
}); 

// run your code and see the results in ext 
vm.run(c, 'vm.js'); 
console.log(ext); 
+0

感謝您的迴應。您的建議完美適用於檢索執行結果。但是,就我而言,**自定義邏輯**是一種將被動態獲取的東西,因此它不會被修改。例如:「將sandbox變量(ext)分配給函數調用,就像你所建議的那樣」**(即:ext.exports = addValues(10,10);)**。有沒有其他方法可以執行邏輯,並檢索其結果? –