patriksimek / vm2

Advanced vm/sandbox for Node.js
MIT License
3.86k stars 293 forks source link

fetch not available in vm2 with node 19 #512

Closed kcthota closed 1 year ago

kcthota commented 1 year ago

Starting node 18+, fetch is included and accessible from global scope. However I can't get the following code to work on node 19.0.1.

It just says ReferenceError: fetch is not defined. Am I missing something obvious?

I can workaround by passing fetch object into sandbox, but I am curious why fetch is not accessible?

const { NodeVM } = require('vm2');

const vm = new NodeVM({
    timeout: 2000,
    sandbox: {},
    require: {},
    networkEnabled: true,
});

const userInput = `
    (async function() {
        console.log(\`running node ${process.version}\`);        
        const response = await fetch('https://news.ycombinator.com', {
            method: "GET"
        });
        const body = await response.text();
        console.log(body);
    })();
`;
try {
    vm.run(userInput);
} catch (error) {
    console.error(error);
}
XmiliaH commented 1 year ago

There are multiple reasons as to why fetch is not exposed into the sandbox by default. The first one is backwards compatiblity as users might expect that no unsafe function get exposed into the sandbox. Secondly, as the function would likley be considered unsafe you most likely want to implement a wrapper that checks hostname and other parameters before. Therefore, if you want the sandbox to have the fetch function you need to pass it in through the sandbox parameter.