const fastify = require('fastify')({ logger: true }); const { spawn } = require('child_process'); const { createProxyMiddleware } = require('http-proxy-middleware'); let OMNITOOL_READY = false; let ALREADY_STARTING = false; const PROXY_PORT = 4444; const TARGET_HOST = '0.0.0.0'; const PROXY_TARGET = 'http://0.0.0.0:1688'; const VERSION = '0.0.2c'; console.log(`************ Omnitool Proxy Server v${VERSION} ************`); let omnitoolLogs = []; async function startOmnitoolServer() { if (ALREADY_STARTING) return; ALREADY_STARTING = true; console.log('Starting Omnitool Server...'); return new Promise((resolve, reject) => { const omnitoolStartProcess = spawn('./omnitool_start.sh'); omnitoolStartProcess.stdout.on('data', (data) => { omnitoolLogs.push(data.toString()); console.log(`omnitool stdout: ${data}`); if (data.toString().includes(`Server has started and is ready to accept connections`)) { OMNITOOL_READY = true; console.log('Omnitool server started successfully'); resolve(); } }); omnitoolStartProcess.stderr.on('data', (data) => { console.error(`omnitool stderr: ${data}`); }); omnitoolStartProcess.on('close', (code) => { console.log(`Omnitool server process exited with code ${code}`); if (!OMNITOOL_READY) { ALREADY_STARTING = false; reject(`Omnitool server did not start within the timeout period.`); } }); }); } fastify.get('/', async (request, reply) => { const localUrl = request.headers['host']; if (!OMNITOOL_READY) { let htmlContent = ` Proxy Server
`; reply.type('text/html').send(htmlContent); } else { console.log('Proxying request as OMNITOOL is ready'); const proxy = createProxyMiddleware({ target: PROXY_TARGET, changeOrigin: true, ws: true, logLevel: 'debug' }); proxy(request.raw, reply.raw, () => {}); } }); fastify.get('/omnitool-logs', async (request, reply) => { reply.send({ logs: omnitoolLogs, ready: OMNITOOL_READY }); }); fastify.get('/start-omnitool-server', async (request, reply) => { if (!OMNITOOL_READY) { if (ALREADY_STARTING) { return { message: "Omnitool server already starting" }; } try { await startOmnitoolServer(); reply.send({ message: "Omnitool server started successfully" }); } catch (error) { console.error(error); reply.send({ message: `Error starting Omnitool server: ${error}` }); } } else { reply.send({ message: "Omnitool server already running" }); } }); const start = async () => { try { await fastify.listen({ port: PROXY_PORT, host: TARGET_HOST }); console.log(`Server is listening on http://${TARGET_HOST}:${PROXY_PORT}`); } catch (err) { console.error(`Error starting server: ${err}`); process.exit(1); } }; start();