eval-server/vm.js
2024-11-01 20:26:03 +07:00

93 lines
2.7 KiB
JavaScript

const { parentPort } = require('worker_threads')
const { VM } = require('@n8n/vm2')
const util = require('util')
const { stylize } = require('./colors')
const randomstring = require('randomstring')
const ChatMessage = require('prismarine-chat')('1.20.6')
const mc = require('minecraft-protocol')
const mineflayer = require('mineflayer')
const moment = require('moment-timezone')
const crypto = require('crypto')
const nbt = require('prismarine-nbt')
const net = require('net')
const axios = require('axios')
const BRIDGE_PREFIX = 'function:'
let promiseResolves = {}
let proxy
let vm
const handler = {
get (target, prop) {
if (!target[prop]) throw new Error(`Function "${prop}" not available`)
return (...args) => target[prop](...args)
}
}
let functions
parentPort.on('message', (msg) => {
switch (msg.type) {
case 'setFunctions':
const parsed = JSON.parse(msg.jsonArray)
functions = {}
for (const eachFuntion of parsed) {
functions[eachFuntion] = (...args) => {
parentPort.postMessage({ type: 'socketEmit', data: [BRIDGE_PREFIX + eachFuntion, ...args] })
const uuid = crypto.randomUUID()
return new Promise((resolve) => {
promiseResolves[uuid] = resolve
parentPort.postMessage({ type: 'socketOnce', uuid, name: `functionOutput:${eachFuntion}`})
})
}
}
proxy = new Proxy(functions, handler)
vm = new VM({
timeout: 1000,
sandbox: {
get bridge () { return proxy },
randomstring,
ChatMessage,
mc,
mineflayer,
moment,
crypto,
nbt,
net,
axios,
inspect: (input, options) => util.inspect(input, { depth: options.depth, customInspect: false })
}
})
break
case 'resolvePromise':
promiseResolves[msg.uuid](msg.data)
break
case 'runCode':
try {
const output = vm.run(msg.code)
parentPort.postMessage({ type: 'codeOutput', output: util.inspect(output, { stylize }), error: false })
} catch (e) {
parentPort.postMessage({ type: 'codeOutput', output: e.toString(), error: true })
}
break
}
})
process.on('uncaughtException', (e) => {
console.log(`Caught an uncaught exception in the worker!\n${e.stack}`)
})