Last active
April 6, 2023 07:16
-
-
Save y21/55f4866eb9dea49d52b15edb5c16b026 to your computer and use it in GitHub Desktop.
vm2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {NodeVM} = require('vm2'); | |
const {isMainThread, Worker, parentPort} = require('worker_threads'); | |
if (isMainThread) { | |
const worker = new Worker(__filename); | |
let lastMessage = null; | |
worker.on('message', () => lastMessage = Date.now()); | |
worker.on('online', () => lastMessage = Date.now()); | |
const checker = setInterval(() => { | |
// Last ping was >5s ago, terminate it | |
if (lastMessage !== null && Date.now() - lastMessage >= 5000) { | |
clearInterval(checker); | |
worker.terminate(); | |
console.log('killed'); | |
} | |
}, 1000); | |
} else { | |
// worker_threads code | |
const vm = new NodeVM({ | |
require: { | |
external: ['axios'], | |
builtin: false | |
}, | |
sandbox:{ | |
logs:[], | |
response:'', | |
}, | |
eval:false, | |
wasm:false, | |
}); | |
vm.run(`for(;;);`); | |
setInterval(() => parentPort.postMessage('ping'), 500); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment