const crypt = require("../crypt"); // methods const isAuthed = require("./is-authed"); function parseRq (bytes) { try { return JSON.parse(bytes.toString()); } catch (e) { return undefined; } } class APIMethods { constructor (parent) { this.parent = parent; } info (con, req, cb) { cb({ result: require("./server-info"), trace_id: req.trace_id, ended: true }); } authed (con, req, cb) { isAuthed(con, req, cb); } /*setSession (isEncrypted, address, { key, counter }, cb) { if (!global.config.server.secureMode) return cb({ error: "Encryption is off by configuration file into server" }); if (!isEncrypted) return cb({ error: "Encryption required" }); try { this.parent.sessions[address] = new crypt.AES(key, counter); return cb({ result: "Session key installed" }); } catch (err) { return cb({ error: "Invalid params. Must be key and counter" }); } }*/ } class API { constructor () { this.methods = new APIMethods(this); this.sessions = new WeakMap(); } decrypt (address, bytes) { throw new Error("Deprecated. Use TLS. If you see this error, please, add issue into: https://git.fullgream.tech/fullgream/ai-adventure-labs/issues"); } async exec (connection, bytes, cb) { const request = parseRq(bytes); if (request === undefined) return cb({ error: "required JSON object request" }); if (typeof request === "object" && request !== null) { const { method, trace_id } = request; if (!method) return cb({ error: "method missed", ended: true }); if (!trace_id) return cb({ error: "trace_id missed", ended: true }); const selmethod = this.methods[method]; if (selmethod === undefined) return cb({ error: "unknown method: " + method, trace_id, ended: true }); return selmethod(connection, request, cb); } else { return cb({ error: "required JSON-object based request" }); } } } module.exports = { API };