patriksimek / vm2

Advanced vm/sandbox for Node.js
MIT License
3.87k stars 295 forks source link

vm2 loading files like bridge.js not playing well with packaging #440

Closed skogs-pa closed 2 years ago

skogs-pa commented 2 years ago

While trying to use require('vm2'), I run into the following error.

Error: ENOENT: no such file or directory, open '/red-acted/dist/bridge.js

How do you work around this? Initially, I thought it's just a problem with the bundler but it started happening with no bundler.

Is there a solution other than copying the relevant files (bridge.js etc) to where the source code is?

XmiliaH commented 2 years ago

The script files loaded into the sandbox are loaded on runtime and are not included by bundlers automatically. It is possible to use plugins such as babel-plugin-static-fs to include the sources of the files where it would be loaded dynamically.

skogs-pa commented 2 years ago

Got it. Thanks for the explanation. I am now copying bridge.js, setup-sandbox.js, and set-node-sandbox.js files next to the bundled index.js using a plugin. That works!

samesfahani-tuplehealth commented 2 years ago

May I politely ask why this is the case? Why are these files being loaded at runtime from fs.fileSync rather than just being imported?

EDIT: Oh I see the problem. They are imported normally, but also compiled at run time to run in a VM (makes sense). However, bundlers are concatenating files together while building, so the runtime code fails. That is tricky...

XmiliaH commented 2 years ago

It might be possible to rewrite the files an put the code in a top level function. The source can then be obtained from the function through toString and imported into the VM. However, the bundler might rewrite the content in an unsafe manner.

samesfahani-tuplehealth commented 2 years ago

I can see how a bundler might mess with code integrity in a VM scope. It would need to be heavily tested for sure, but using Function.toString is smart.

Ah, the joys of trying to use tools like esbuild and swc in a mature codebase... 😂