Lately am building an API with Node.js that receives untrusted code to run it using vm2.
The issue is I want to run async functions, so I need to use NodeVM which does not support timeout for infinite loop, the solutions that I found all about using child process then kill it if it's not working.
But I am receiving the code as a string and I want to prevent having an infinite loop in it, so I thought of using regex to inject the while/for loop with a timeout condition or something so throw an exception whenever infinite loop happened.
Is that possible?
The perfect solution that worked for me is to use AST. so I learned more about it so I can inject the string with anything anywhere I want.
Then I followed these steps:
1- convert string code to AST using
Esprimaparser.2- Inject the Infinite loop code protection, which is:
use
breakor throw an error, notice that you need a unique variable name generator every time you catch a loop.3- Convert it back to a string using
escodegen.