eval-server/index.js

70 lines
1.7 KiB
JavaScript

const { VM } = require('vm2')
const { Server } = require('socket.io')
const util = require('util')
const { stylize } = require('./colors')
const randomstring = require('randomstring')
const ChatMessage = require('prismarine-chat')('1.20.1')
const mc = require('minecraft-protocol')
const moment = require('moment-timezone')
const crypto = require('crypto')
const BRIDGE_PREFIX = 'function:'
const io = new Server(3069)
io.on('connection', (socket) => {
let functions
let proxy
const handler = {
get (target, prop) {
if (!target[prop]) throw new Error(`Function "${prop}" not available`)
return (...args) => target[prop](...args)
}
}
socket.on('setFunctions', (...args) => {
functions = {}
for (const eachFuntion of args) {
functions[eachFuntion] = (...args) => socket.emit(BRIDGE_PREFIX + eachFuntion, ...args)
}
proxy = new Proxy(functions, handler)
})
let vm
function resetVM () {
vm = new VM({
timeout: 3000,
sandbox: {
bridge: () => proxy,
randomstring,
ChatMessage,
mc,
moment,
crypto
}
})
}
resetVM()
socket.on('runCode', (transactionId, code) => {
try {
const output = vm.run(code)
socket.emit('codeOutput', transactionId, false, util.inspect(output, { stylize }))
} catch (e) {
socket.emit('codeOutput', transactionId, true, e.toString())
}
})
socket.on('reset', resetVM)
})
process.on('uncaughtException', (e) => {
console.log(`Caught an uncaught exception!\n${e.stack}`)
})