import Fastify, { FastifyRequest } from "fastify"; import { Data } from "./Data"; import { KeyGenerator } from "./KeyGenerator"; import readline from "node:readline"; const PORT = parseInt(process.env.PORT || '3000'); const fastify = Fastify(); fastify.get('/keygen', async (req, res) => { let key = KeyGenerator.generateKey(); try { await Data.addKey(req.ip, key); console.log('keygen', req.ip, key); res.send(key); } catch (err) { console.log('errgen', req.ip, err); res.send({ error: err }); } }); fastify.get('/keys', async (req, res) => { try { let prof = await Data.getKeyProfile(req.ip); console.log('grab', req.ip, prof.keys); return res.send(prof.keys); } catch (err) { console.log('errgrab', req.ip, err); res.send({ error: err }); } }); type AdminRequest = FastifyRequest<{ Querystring: { key: string, value: any, ip: string } }> fastify.get('/set', async (req: AdminRequest, res) => { let prof; try { prof = await Data.getKeyProfile(req.ip); if (!prof.admin) { console.log('adminseterr', req.ip, 'not admin'); return res.send({ error: 'not admin' }); } } catch (err) { return; } const { ip, key, value } = req.query; try { let mod = await Data.getKeyProfile(ip); return res.send(JSON.stringify(await Data.setProfileValue(mod, key, JSON.parse(value)))); } catch (err) { console.log('adminseterr', req.ip, err); return res.send({ error: err }); } }); fastify.get('/get', async (req: AdminRequest, res) => { let prof; try { prof = await Data.getKeyProfile(req.ip); if (!prof.admin) { console.log('admingeterr', req.ip, 'not admin'); return res.send({ error: 'not admin' }); } } catch (err) { return; } const { ip, key } = req.query; try { let mod = await Data.getKeyProfile(ip); if (key) { return res.send(mod[key]); } else { return res.send(mod); } } catch (err) { console.log('admingeterr', req.ip, err); return res.send({ error: err }); } }); fastify.get('/reset', async (req: AdminRequest, res) => { let prof; try { prof = await Data.getKeyProfile(req.ip); if (!prof.admin) { console.log('adminreseterr', req.ip, 'not admin'); return res.send({ error: 'not admin' }); } } catch (err) { return; } const { ip } = req.query; try { return res.send(JSON.stringify(await Data.resetKeyProfile(ip))); } catch (err) { console.log('adminreseterr', req.ip, err); return res.send({ error: err }); } }); const rl = readline.createInterface(process.stdin, process.stdout); rl.on('line', async data => { let str = data.toString(); let args = str.split(' '); let argcat = str.substring(args[0].length).trim(); let cmd = args[0]; switch (cmd) { case 'set': if (!args[3]) return console.log('Not enough arguments: set '); let ip = args[1]; let key = args[2]; let val = args[3]; try { let prof = await Data.getKeyProfile(ip); await Data.setProfileValue(prof, key, JSON.parse(val)); } catch (err) { console.error(err); } break; } }); fastify.listen({ port: PORT }, (err, address) => { if (err) throw err }); process.on('SIGINT', async () => { await Data.db.close(); await fastify.close(); });