From c634e03cb553e21158fddc6d4221a54aa799de79 Mon Sep 17 00:00:00 2001 From: marzavec Date: Mon, 18 Mar 2019 23:36:21 -0700 Subject: refactoring 1 of 2 --- CHANGELOG.md | 10 + server/main.js | 27 +- server/package-lock.json | 21 +- server/package.json | 1 - server/src/commands/admin/addmod.js | 2 +- server/src/commands/admin/reload.js | 2 +- server/src/commands/admin/saveconfig.js | 2 +- server/src/commands/core/chat.js | 2 +- server/src/commands/core/invite.js | 2 +- server/src/commands/core/join.js | 2 +- server/src/commands/core/morestats.js | 16 +- server/src/commands/core/stats.js | 2 +- server/src/commands/mod/ban.js | 2 +- server/src/commands/mod/kick.js | 2 +- server/src/commands/mod/unban.js | 2 +- server/src/core/rateLimiter.js | 103 ------- server/src/core/server.js | 434 ---------------------------- server/src/managers/commands.js | 251 ---------------- server/src/managers/config.js | 240 --------------- server/src/managers/imports-manager.js | 148 ---------- server/src/managers/index.js | 6 - server/src/managers/stats.js | 59 ---- server/src/scripts/configLib/SetupWizard.js | 107 +++++++ server/src/scripts/configure.js | 14 +- server/src/scripts/setupSchema/Banner.js | 28 ++ server/src/scripts/setupSchema/Footer.js | 7 + server/src/scripts/setupSchema/Questions.js | 55 ++++ server/src/serverLib/CommandManager.js | 250 ++++++++++++++++ server/src/serverLib/ConfigManager.js | 89 ++++++ server/src/serverLib/CoreApp.js | 66 +++++ server/src/serverLib/ImportsManager.js | 121 ++++++++ server/src/serverLib/MainServer.js | 434 ++++++++++++++++++++++++++++ server/src/serverLib/RateLimiter.js | 103 +++++++ server/src/serverLib/StatsManager.js | 59 ++++ server/src/serverLib/index.js | 8 + 35 files changed, 1366 insertions(+), 1311 deletions(-) delete mode 100644 server/src/core/rateLimiter.js delete mode 100644 server/src/core/server.js delete mode 100644 server/src/managers/commands.js delete mode 100644 server/src/managers/config.js delete mode 100644 server/src/managers/imports-manager.js delete mode 100644 server/src/managers/index.js delete mode 100644 server/src/managers/stats.js create mode 100644 server/src/scripts/configLib/SetupWizard.js create mode 100644 server/src/scripts/setupSchema/Banner.js create mode 100644 server/src/scripts/setupSchema/Footer.js create mode 100644 server/src/scripts/setupSchema/Questions.js create mode 100644 server/src/serverLib/CommandManager.js create mode 100644 server/src/serverLib/ConfigManager.js create mode 100644 server/src/serverLib/CoreApp.js create mode 100644 server/src/serverLib/ImportsManager.js create mode 100644 server/src/serverLib/MainServer.js create mode 100644 server/src/serverLib/RateLimiter.js create mode 100644 server/src/serverLib/StatsManager.js create mode 100644 server/src/serverLib/index.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ffc4d4..99d40e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,16 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +## [2.1.9 pre 2.2] - 2019-03-18 +### Changed +- Configuration script setup, making it more portable/sane +- Refactored naming scheme and entry point + +### Removed +- Configuration setup from `./serverLib/ConfigManager` +- Unused feature allowing command modules to add to the configuration/setup process +- `deasync` dependency + ## [2.1.9] - 2019-02-21 ### Added - `./server/src/commands/core/emote.js` module to provide action text diff --git a/server/main.js b/server/main.js index 2e66cc1..70042e8 100644 --- a/server/main.js +++ b/server/main.js @@ -9,26 +9,7 @@ 'use strict'; -// import required classes -const Managers = require('./src/managers'); -const wsServer = require('./src/core/server'); - -// initialize core reference -const core = {}; - -// load and initialize main manager classes -core.managers = {}; -core.managers.dynamicImports = global.dynamicImports = new Managers.ImportsManager(core, __dirname); -core.managers.dynamicImports.init(); - -const configManager = core.managers.config = new Managers.Config(core, __dirname, core.managers.dynamicImports); -core.config = configManager.loadSync(); - -const commands = core.commands = new Managers.CommandManager(core); -commands.loadCommands(); - -const stats = core.managers.stats = new Managers.Stats(core); -stats.set('start-time', process.hrtime()); - -// initialize and start the server -const server = new wsServer(core); +// import and initialize the core application +const CoreApp = require('./src/serverLib/CoreApp'); +const coreApp = new CoreApp(); +coreApp.init(); diff --git a/server/package-lock.json b/server/package-lock.json index b23f7f6..27205bc 100644 --- a/server/package-lock.json +++ b/server/package-lock.json @@ -1,6 +1,6 @@ { "name": "hack.chat-v2", - "version": "2.1.0", + "version": "2.1.9", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -27,11 +27,6 @@ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" }, - "bindings": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.2.1.tgz", - "integrity": "sha1-FK1hE4EtLTfXLme0ystLtyZQXxE=" - }, "brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", @@ -89,15 +84,6 @@ "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-3.0.3.tgz", "integrity": "sha512-jyCETtSl3VMZMWeRo7iY1FL19ges1t55hMo5yaam4Jrsm5EPL89UQkoQRyiI+Yf4k8r2ZpdngkV8hr1lIdjb3Q==" }, - "deasync": { - "version": "0.1.14", - "resolved": "https://registry.npmjs.org/deasync/-/deasync-0.1.14.tgz", - "integrity": "sha512-wN8sIuEqIwyQh72AG7oY6YQODCxIp1eXzEZlZznBuwDF8Q03Tdy9QNp1BNZXeadXoklNrw+Ip1fch+KXo/+ASw==", - "requires": { - "bindings": "~1.2.1", - "node-addon-api": "^1.6.0" - } - }, "deep-equal": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-0.2.2.tgz", @@ -234,11 +220,6 @@ "resolved": "https://registry.npmjs.org/ncp/-/ncp-1.0.1.tgz", "integrity": "sha1-0VNn5cuHQyuhF9K/gP30Wuz7QkY=" }, - "node-addon-api": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-1.6.2.tgz", - "integrity": "sha512-479Bjw9nTE5DdBSZZWprFryHGjUaQC31y1wHo19We/k0BZlrmhqQitWoUL0cD8+scljCbIUL+E58oRDEakdGGA==" - }, "once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", diff --git a/server/package.json b/server/package.json index 8595033..51a149d 100644 --- a/server/package.json +++ b/server/package.json @@ -21,7 +21,6 @@ "chalk": "^2.4.2", "common-tags": "^1.8.0", "dateformat": "^3.0.3", - "deasync": "^0.1.14", "didyoumean2": "^2.0.2", "fs-extra": "^7.0.1", "prompt": "^1.0.0", diff --git a/server/src/commands/admin/addmod.js b/server/src/commands/admin/addmod.js index c4fcdd5..a30b175 100644 --- a/server/src/commands/admin/addmod.js +++ b/server/src/commands/admin/addmod.js @@ -10,7 +10,7 @@ exports.run = async (core, server, socket, data) => { } // add new trip to config - core.config.mods.push({ trip: data.trip }); // purposely not using `config.set()` to avoid auto-save + core.config.mods.push({ trip: data.trip }); // find targets current connections let newMod = server.findSockets({ trip: data.trip }); diff --git a/server/src/commands/admin/reload.js b/server/src/commands/admin/reload.js index 947f9d9..27be19c 100644 --- a/server/src/commands/admin/reload.js +++ b/server/src/commands/admin/reload.js @@ -10,7 +10,7 @@ exports.run = async (core, server, socket, data) => { } // do command reload and store results - let loadResult = core.managers.dynamicImports.reloadDirCache('src/commands'); + let loadResult = core.dynamicImports.reloadDirCache('src/commands'); loadResult += core.commands.loadCommands(); // clear and rebuild all module hooks diff --git a/server/src/commands/admin/saveconfig.js b/server/src/commands/admin/saveconfig.js index b8a769b..a95a39a 100644 --- a/server/src/commands/admin/saveconfig.js +++ b/server/src/commands/admin/saveconfig.js @@ -10,7 +10,7 @@ exports.run = async (core, server, socket, data) => { } // attempt save, notify of failure - if (!core.managers.config.save()) { + if (!core.configManager.save()) { return server.reply({ cmd: 'warn', text: 'Failed to save config, check logs.' diff --git a/server/src/commands/core/chat.js b/server/src/commands/core/chat.js index 3455453..bb9584e 100644 --- a/server/src/commands/core/chat.js +++ b/server/src/commands/core/chat.js @@ -57,7 +57,7 @@ exports.run = async (core, server, socket, data) => { server.broadcast( payload, { channel: socket.channel}); // stats are fun - core.managers.stats.increment('messages-sent'); + core.stats.increment('messages-sent'); }; // module hook functions diff --git a/server/src/commands/core/invite.js b/server/src/commands/core/invite.js index 8374309..046e47a 100644 --- a/server/src/commands/core/invite.js +++ b/server/src/commands/core/invite.js @@ -59,7 +59,7 @@ exports.run = async (core, server, socket, data) => { }, socket); // stats are fun - core.managers.stats.increment('invites-sent'); + core.stats.increment('invites-sent'); }; // module meta diff --git a/server/src/commands/core/join.js b/server/src/commands/core/join.js index 8b6a971..ce900db 100644 --- a/server/src/commands/core/join.js +++ b/server/src/commands/core/join.js @@ -135,7 +135,7 @@ exports.run = async (core, server, socket, data) => { }, socket); // stats are fun - core.managers.stats.increment('users-joined'); + core.stats.increment('users-joined'); }; // module meta diff --git a/server/src/commands/core/morestats.js b/server/src/commands/core/morestats.js index 69740a9..a71729c 100644 --- a/server/src/commands/core/morestats.js +++ b/server/src/commands/core/morestats.js @@ -43,17 +43,17 @@ exports.run = async (core, server, socket, data) => { cmd: 'info', text: stripIndents`current-connections: ${uniqueClientCount} current-channels: ${uniqueChannels} - users-joined: ${(core.managers.stats.get('users-joined') || 0)} - invites-sent: ${(core.managers.stats.get('invites-sent') || 0)} - messages-sent: ${(core.managers.stats.get('messages-sent') || 0)} - users-banned: ${(core.managers.stats.get('users-banned') || 0)} - users-kicked: ${(core.managers.stats.get('users-kicked') || 0)} - stats-requested: ${(core.managers.stats.get('stats-requested') || 0)} - server-uptime: ${formatTime(process.hrtime(core.managers.stats.get('start-time')))}` + users-joined: ${(core.stats.get('users-joined') || 0)} + invites-sent: ${(core.stats.get('invites-sent') || 0)} + messages-sent: ${(core.stats.get('messages-sent') || 0)} + users-banned: ${(core.stats.get('users-banned') || 0)} + users-kicked: ${(core.stats.get('users-kicked') || 0)} + stats-requested: ${(core.stats.get('stats-requested') || 0)} + server-uptime: ${formatTime(process.hrtime(core.stats.get('start-time')))}` }, socket); // stats are fun - core.managers.stats.increment('stats-requested'); + core.stats.increment('stats-requested'); }; // module hook functions diff --git a/server/src/commands/core/stats.js b/server/src/commands/core/stats.js index b271bb1..ff4b1ef 100644 --- a/server/src/commands/core/stats.js +++ b/server/src/commands/core/stats.js @@ -27,7 +27,7 @@ exports.run = async (core, server, socket, data) => { }, socket); // stats are fun - core.managers.stats.increment('stats-requested'); + core.stats.increment('stats-requested'); }; // module meta diff --git a/server/src/commands/mod/ban.js b/server/src/commands/mod/ban.js index 8236136..93c536b 100644 --- a/server/src/commands/mod/ban.js +++ b/server/src/commands/mod/ban.js @@ -56,7 +56,7 @@ exports.run = async (core, server, socket, data) => { badClient.terminate(); // stats are fun - core.managers.stats.increment('users-banned'); + core.stats.increment('users-banned'); }; // module meta diff --git a/server/src/commands/mod/kick.js b/server/src/commands/mod/kick.js index 0e8ee0a..808defa 100644 --- a/server/src/commands/mod/kick.js +++ b/server/src/commands/mod/kick.js @@ -69,7 +69,7 @@ exports.run = async (core, server, socket, data) => { }, { channel: socket.channel, uType: 'user' }); // stats are fun - core.managers.stats.increment('users-kicked', kicked.length); + core.stats.increment('users-kicked', kicked.length); }; // module meta diff --git a/server/src/commands/mod/unban.js b/server/src/commands/mod/unban.js index 0cd8ca7..71be9bb 100644 --- a/server/src/commands/mod/unban.js +++ b/server/src/commands/mod/unban.js @@ -49,7 +49,7 @@ exports.run = async (core, server, socket, data) => { }, { uType: 'mod' }); // stats are fun - core.managers.stats.decrement('users-banned'); + core.stats.decrement('users-banned'); }; // module meta diff --git a/server/src/core/rateLimiter.js b/server/src/core/rateLimiter.js deleted file mode 100644 index 0c2a384..0000000 --- a/server/src/core/rateLimiter.js +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Tracks frequency of occurances based on `id` (remote address), then allows or - * denies command execution based on comparison with `threshold` - * - * Version: v2.0.0 - * Developer: Marzavec ( https://github.com/marzavec ) - * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) - * - */ - -class Police { - /** - * Create a ratelimiter instance. - */ - constructor () { - this._records = {}; - this._halflife = 30 * 1000; // milliseconds - this._threshold = 25; - this._hashes = []; - } - - /** - * Finds current score by `id` - * - * @param {String} id target id / address - * @public - * - * @memberof Police - */ - search (id) { - let record = this._records[id]; - - if (!record) { - record = this._records[id] = { - time: Date.now(), - score: 0 - } - } - - return record; - } - - /** - * Adjusts the current ratelimit score by `deltaScore` - * - * @param {String} id target id / address - * @param {Number} deltaScore amount to adjust current score by - * @public - * - * @memberof Police - */ - frisk (id, deltaScore) { - let record = this.search(id); - - if (record.arrested) { - return true; - } - - record.score *= Math.pow(2, -(Date.now() - record.time ) / this._halflife); - record.score += deltaScore; - record.time = Date.now(); - - if (record.score >= this._threshold) { - return true; - } - - return false; - } - - /** - * Statically set server to no longer accept traffic from `id` - * - * @param {String} id target id / address - * @public - * - * @memberof Police - */ - arrest (id, hash) { - let record = this.search(id); - - record.arrested = true; - this._hashes[hash] = id; - } - - /** - * Remove statically assigned limit from `id` - * - * @param {String} id target id / address - * @public - * - * @memberof Police - */ - pardon (id) { - if (typeof this._hashes[id] !== 'undefined') { - id = this._hashes[id]; - } - - let record = this.search(id); - record.arrested = false; - } -} - -module.exports = Police; diff --git a/server/src/core/server.js b/server/src/core/server.js deleted file mode 100644 index 4132b55..0000000 --- a/server/src/core/server.js +++ /dev/null @@ -1,434 +0,0 @@ -/** - * Main websocket server handling communications and connection events - * - * Version: v2.0.0 - * Developer: Marzavec ( https://github.com/marzavec ) - * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) - * - */ - -const wsServer = require('ws').Server; -const socketReady = require('ws').OPEN; -const crypto = require('crypto'); -const ipSalt = [...Array(Math.floor(Math.random()*128)+128)].map(i=>(~~(Math.random()*36)).toString(36)).join(''); -const internalCmdKey = [...Array(Math.floor(Math.random()*128)+128)].map(i=>(~~(Math.random()*36)).toString(36)).join(''); -const Police = require('./rateLimiter'); -const pulseSpeed = 16000; // ping all clients every X ms - -class server extends wsServer { - /** - * Create a HackChat server instance. - * - * @param {Object} core Reference to the global core object - */ - constructor (core) { - super({ port: core.config.websocketPort }); - - this._core = core; - this._hooks = {}; - this._police = new Police(); - this._cmdBlacklist = {}; - this._cmdKey = internalCmdKey; - - this._heartBeat = setInterval(() => this.beatHeart(), pulseSpeed); - - this.on('error', (err) => { - this.handleError('server', err); - }); - - this.on('connection', (socket, request) => { - this.newConnection(socket, request); - }); - - this.loadHooks(); - } - - /** - * Send empty `ping` frame to each client - * - */ - beatHeart () { - let targetSockets = this.findSockets({}); - - if (targetSockets.length === 0) { - return; - } - - for (let i = 0, l = targetSockets.length; i < l; i++) { - try { - if (targetSockets[i].readyState === socketReady) { - targetSockets[i].ping(); - } - } catch (e) { } - } - } - - /** - * Bind listeners for the new socket created on connection to this class - * - * @param {Object} socket New socket object - * @param {Object} request Initial headers of the new connection - */ - newConnection (socket, request) { - socket.remoteAddress = request.headers['x-forwarded-for'] || request.connection.remoteAddress; - - socket.on('message', (data) => { - this.handleData(socket, data); - }); - - socket.on('close', () => { - this.handleClose(socket); - }); - - socket.on('error', (err) => { - this.handleError(socket, err); - }); - } - - /** - * Handle incoming messages from clients, parse and check command, then hand-off - * - * @param {Object} socket Calling socket object - * @param {String} data Message sent from client - */ - handleData (socket, data) { - // Don't penalize yet, but check whether IP is rate-limited - if (this._police.frisk(socket.remoteAddress, 0)) { - this._core.commands.handleCommand(this, socket, { - cmd: 'socketreply', - cmdKey: this._cmdKey, - text: 'Your IP is being rate-limited or blocked.' - }); - - return; - } - - // Penalize here, but don't do anything about it - this._police.frisk(socket.remoteAddress, 1); - - // Ignore ridiculously large packets - if (data.length > 65536) { - return; - } - - // Start sent data verification - var payload = null; - try { - payload = JSON.parse(data); - } catch (e) { - // Client sent malformed json, gtfo - socket.close(); - } - - if (payload === null) { - return; - } - - if (typeof payload.cmd === 'undefined') { - return; - } - - if (typeof payload.cmd !== 'string') { - return; - } - - if (typeof socket.channel === 'undefined' && (payload.cmd !== 'join' && payload.cmd !== 'chat')) { - return; - } - - if (typeof this._cmdBlacklist[payload.cmd] === 'function') { - return; - } - - // Execute `in` (incoming data) hooks and process results - payload = this.executeHooks('in', socket, payload); - - if (typeof payload === 'string') { - // A hook malfunctioned, reply with error - this._core.commands.handleCommand(this, socket, { - cmd: 'socketreply', - cmdKey: this._cmdKey, - text: payload - }); - - return; - } else if (payload === false) { - // A hook requested this data be dropped - return; - } - - // Finished verification & hooks, pass to command modules - this._core.commands.handleCommand(this, socket, payload); - } - - /** - * Handle socket close from clients - * - * @param {Object} socket Closing socket object - */ - handleClose (socket) { - this._core.commands.handleCommand(this, socket, { - cmd: 'disconnect', - cmdKey: this._cmdKey - }); - } - - /** - * "Handle" server or socket errors - * - * @param {Object||String} socket Calling socket object, or 'server' - * @param {String} err The sad stuff - */ - handleError (socket, err) { - console.log(`Server error: ${err}`); - } - - /** - * Send data payload to specific socket/client - * - * @param {Object} payload Object to convert to json for transmission - * @param {Object} socket The target client - */ - send (payload, socket) { - // Add timestamp to command - payload.time = Date.now(); - - // Execute `in` (incoming data) hooks and process results - payload = this.executeHooks('out', socket, payload); - - if (typeof payload === 'string') { - // A hook malfunctioned, reply with error - this._core.commands.handleCommand(this, socket, { - cmd: 'socketreply', - cmdKey: this._cmdKey, - text: payload - }); - - return; - } else if (payload === false) { - // A hook requested this data be dropped - return; - } - - try { - if (socket.readyState === socketReady) { - socket.send(JSON.stringify(payload)); - } - } catch (e) { } - } - - /** - * Overload function for `this.send()` - * - * @param {Object} payload Object to convert to json for transmission - * @param {Object} socket The target client - */ - reply (payload, socket) { - this.send(payload, socket); - } - - /** - * Finds sockets/clients that meet the filter requirements, then passes the data to them - * - * @param {Object} payload Object to convert to json for transmission - * @param {Object} filter see `this.findSockets()` - */ - broadcast (payload, filter) { - let targetSockets = this.findSockets(filter); - - if (targetSockets.length === 0) { - return false; - } - - for (let i = 0, l = targetSockets.length; i < l; i++) { - this.send(payload, targetSockets[i]); - } - - return true; - } - - /** - * Finds sockets/clients that meet the filter requirements, returns result as array - * - * @param {Object} data Object to convert to json for transmission - * @param {Object} filter The socket must of equal or greater attribs matching `filter` - * = {} // matches all - * = { channel: 'programming' } // matches any socket where (`socket.channel` === 'programming') - * = { channel: 'programming', nick: 'Marzavec' } // matches any socket where (`socket.channel` === 'programming' && `socket.nick` === 'Marzavec') - */ - findSockets (filter) { - let filterAttribs = Object.keys(filter); - let reqCount = filterAttribs.length; - let curMatch; - let matches = []; - for ( let socket of this.clients ) { - curMatch = 0; - - for (let i = 0; i < reqCount; i++) { - if (typeof socket[filterAttribs[i]] !== 'undefined') { - switch(typeof filter[filterAttribs[i]]) { - case 'object': { - if (Array.isArray(filter[filterAttribs[i]])) { - if (filter[filterAttribs[i]].indexOf(socket[filterAttribs[i]]) !== -1) { - curMatch++; - } - } else { - if (socket[filterAttribs[i]] === filter[filterAttribs[i]]) { - curMatch++; - } - } - break; - } - - case 'function': { - if (filter[filterAttribs[i]](socket[filterAttribs[i]])) { - curMatch++; - } - break; - } - - default: { - if (socket[filterAttribs[i]] === filter[filterAttribs[i]]) { - curMatch++; - } - break; - } - } - } - } - - if (curMatch === reqCount) { - matches.push(socket); - } - } - - return matches; - } - - /** - * Hashes target socket's remote address using non-static variable length salt - * encodes and shortens the output, returns that value - * - * @param {Object||String} target Either the target socket or ip as string - */ - getSocketHash (target) { - let sha = crypto.createHash('sha256'); - - if (typeof target === 'string') { - sha.update(target + ipSalt); - } else { - sha.update(target.remoteAddress + ipSalt); - } - - return sha.digest('base64').substr(0, 15); - } - - /** - * (Re)loads all command module hooks, then sorts their order of operation by - * priority, ascending (0 being highest priority) - * - */ - loadHooks () { - // clear current hooks (if any) - this.clearHooks(); - // notify each module to register their hooks (if any) - this._core.commands.initCommandHooks(this); - - if (typeof this._hooks['in'] !== 'undefined') { - // start sorting, with incoming first - let curHooks = [ ...this._hooks['in'].keys() ]; - let hookObj = []; - for (let i = 0, j = curHooks.length; i < j; i++) { - hookObj = this._hooks['in'].get(curHooks[i]); - hookObj.sort( (h1, h2) => h1.priority - h2.priority ); - this._hooks['in'].set(hookObj); - } - } - - if (typeof this._hooks['out'] !== 'undefined') { - // then outgoing - curHooks = [ ...this._hooks['out'].keys() ]; - for (let i = 0, j = curHooks.length; i < j; i++) { - hookObj = this._hooks['out'].get(curHooks[i]); - hookObj.sort( (h1, h2) => h1.priority - h2.priority ); - this._hooks['out'].set(hookObj); - } - } - } - - /** - * Adds a target function to an array of hooks. Hooks are executed either before - * processing user input (`in`) or before sending data back to the client (`out`) - * and allows a module to modify each payload before moving forward - * - * @param {String} type The type of event, typically `in` (incoming) or `out` (outgoing) - * @param {String} command Should match the desired `cmd` attrib of the payload - * @param {Function} hookFunction Target function to execute, should accept `server`, `socket` and `payload` as parameters - * @param {Number} priority Execution priority, hooks with priority 1 will be executed before hooks with priority 200 for example - */ - registerHook (type, command, hookFunction, priority) { - if (typeof priority === 'undefined') { - priority = 25; - } - - if (typeof this._hooks[type] === 'undefined') { - this._hooks[type] = new Map(); - } - - if (!this._hooks[type].has(command)) { - this._hooks[type].set(command, []); - } - - this._hooks[type].get(command).push({ - run: hookFunction, - priority: priority - }); - } - - /** - * Loops through registered hooks & processes the results. Returned data will - * be one of three possiblities: - * A payload (modified or not) that will continue through the data flow - * A boolean false to indicate halting the data through flow - * A string which indicates an error occured in executing the hook - * - * @param {String} type The type of event, typically `in` (incoming) or `out` (outgoing) - * @param {Object} socket Either the target client or the client triggering the hook (depending on `type`) - * @param {Object} payload Either incoming data from client or outgoing data (depending on `type`) - */ - executeHooks (type, socket, payload) { - let command = payload.cmd; - - if (typeof this._hooks[type] !== 'undefined') { - if (this._hooks[type].has(command)) { - let hooks = this._hooks[type].get(command); - - for (let i = 0, j = hooks.length; i < j; i++) { - try { - payload = hooks[i].run(this._core, this, socket, payload); - } catch (err) { - let errText = `Hook failure, '${type}', '${command}': ${err}`; - console.log(errText); - return errText; - } - - // A hook function may choose to return false to prevent all further processing - if (payload === false) { - return false; - } - } - } - } - - return payload; - } - - /** - * Wipe server hooks to make ready for module reload calls - */ - clearHooks () { - this._hooks = {}; - } -} - -module.exports = server; diff --git a/server/src/managers/commands.js b/server/src/managers/commands.js deleted file mode 100644 index 434a16e..0000000 --- a/server/src/managers/commands.js +++ /dev/null @@ -1,251 +0,0 @@ -/** - * Commands / protocol manager- loads, validates and handles command execution - * - * Version: v2.0.0 - * Developer: Marzavec ( https://github.com/marzavec ) - * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) - * - */ - -const path = require('path'); -const chalk = require('chalk'); -const didYouMean = require('didyoumean2').default; - -class CommandManager { - /** - * Create a `CommandManager` instance for handling commands/protocol - * - * @param {Object} core Reference to the global core object - */ - constructor (core) { - this.core = core; - this._commands = []; - this._categories = []; - } - - /** - * (Re)initializes name spaces for commands and starts load routine - * - */ - loadCommands () { - this._commands = []; - this._categories = []; - - const core = this.core; - - const commandImports = core.managers.dynamicImports.getImport('src/commands'); - let cmdErrors = ''; - Object.keys(commandImports).forEach(file => { - let command = commandImports[file]; - let name = path.basename(file); - cmdErrors += this._validateAndLoad(command, file, name); - }); - - return cmdErrors; - } - - /** - * Checks the module after having been `require()`ed in and reports errors - * - * @param {Object} command reference to the newly loaded object - * @param {String} file file path to the module - * @param {String} name command (`cmd`) name - */ - _validateAndLoad (command, file, name) { - let error = this._validateCommand(command); - - if (error) { - let errText = `Failed to load '${name}': ${error}`; - console.log(errText); - return errText; - } - - if (!command.category) { - let base = path.join(this.core.managers.dynamicImports.base, 'commands'); - - let category = 'Uncategorized'; - if (file.indexOf(path.sep) > -1) { - category = path.dirname(path.relative(base, file)) - .replace(new RegExp(path.sep.replace('\\', '\\\\'), 'g'), '/'); - } - - command.info.category = category; - - if (this._categories.indexOf(category) === -1) { - this._categories.push(category); - } - } - - if (typeof command.init === 'function') { - try { - command.init(this.core); - } catch (err) { - let errText = `Failed to initialize '${name}': ${err}`; - console.log(errText); - return errText; - } - } - - this._commands.push(command); - - return ''; - } - - /** - * Checks the module after having been `require()`ed in and reports errors - * - * @param {Object} object reference to the newly loaded object - */ - _validateCommand (object) { - if (typeof object !== 'object') - return 'command setup is invalid'; - - if (typeof object.run !== 'function') - return 'run function is missing'; - - if (typeof object.info !== 'object') - return 'info object is missing'; - - if (typeof object.info.name !== 'string') - return 'info object is missing a valid name field'; - - return null; - } - - /** - * Pulls all command names from a passed `category` - * - * @param {String} category [Optional] filter return results by this category - */ - all (category) { - return !category ? this._commands : this._commands.filter(c => c.info.category.toLowerCase() === category.toLowerCase()); - } - - /** - * Pulls all category names - * - */ - categories () { - return this._categories; - } - - /** - * Pulls command by name or alia(s) - * - * @param {String} name name or alias of command - */ - get (name) { - return this.findBy('name', name) - || this._commands.find(command => command.info.aliases instanceof Array && command.info.aliases.indexOf(name) > -1); - } - - /** - * Pulls command by arbitrary search of the `module.info` attribute - * - * @param {String} key name or alias of command - * @param {String} value name or alias of command - */ - findBy (key, value) { - return this._commands.find(c => c.info[key] === value); - } - - /** - * Runs `initHooks` function on any modules that utilize the event - * - * @param {Object} server main server object - */ - initCommandHooks (server) { - this._commands.filter(c => typeof c.initHooks !== 'undefined').forEach(c => c.initHooks(server)); - } - - /** - * Finds and executes the requested command, or fails with semi-intelligent error - * - * @param {Object} server main server reference - * @param {Object} socket calling socket reference - * @param {Object} data command structure passed by socket (client) - */ - handleCommand (server, socket, data) { - // Try to find command first - let command = this.get(data.cmd); - - if (command) { - return this.execute(command, server, socket, data); - } else { - // Then fail with helpful (sorta) message - return this._handleFail(server, socket, data); - } - } - - /** - * Requested command failure handler, attempts to find command and reports back - * - * @param {Object} server main server reference - * @param {Object} socket calling socket reference - * @param {Object} data command structure passed by socket (client) - */ - _handleFail(server, socket, data) { - const maybe = didYouMean(data.cmd, this.all().map(c => c.info.name), { - threshold: 5, - thresholdType: 'edit-distance' - }); - - if (maybe) { - // Found a suggestion, pass it on to their dyslexic self - return this.handleCommand(server, socket, { - cmd: 'socketreply', - cmdKey: server._cmdKey, - text: `Command not found, did you mean: \`${maybe}\`?` - }); - } - - // Request so mangled that I don't even, silently fail - return; - } - - /** - * Attempt to execute the requested command, fail if err or bad params - * - * @param {Object} command target command module - * @param {Object} server main server reference - * @param {Object} socket calling socket reference - * @param {Object} data command structure passed by socket (client) - */ - async execute(command, server, socket, data) { - if (typeof command.requiredData !== 'undefined') { - let missing = []; - for (let i = 0, len = command.requiredData.length; i < len; i++) { - if (typeof data[command.requiredData[i]] === 'undefined') - missing.push(command.requiredData[i]); - } - - if (missing.length > 0) { - console.log(`Failed to execute '${command.info.name}': missing required ${missing.join(', ')}\n\n`); - this.handleCommand(server, socket, { - cmd: 'socketreply', - cmdKey: server._cmdKey, - text: `Failed to execute '${command.info.name}': missing required ${missing.join(', ')}\n\n` - }); - - return null; - } - } - - try { - return await command.run(this.core, server, socket, data); - } catch (err) { - let errText = `Failed to execute '${command.info.name}': ${err}`; - console.log(errText); - - this.handleCommand(server, socket, { - cmd: 'socketreply', - cmdKey: server._cmdKey, - text: errText - }); - - return null; - } - } -} - -module.exports = CommandManager; diff --git a/server/src/managers/config.js b/server/src/managers/config.js deleted file mode 100644 index 7b49aa8..0000000 --- a/server/src/managers/config.js +++ /dev/null @@ -1,240 +0,0 @@ -/** - * Server configuration manager, handling loading, creation, parsing and saving - * of the main config.json file - * - * Version: v2.0.0 - * Developer: Marzavec ( https://github.com/marzavec ) - * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) - * - */ - -const stripIndents = require('common-tags').stripIndents; -const dateFormat = require('dateformat'); -const chalk = require('chalk'); -const fse = require('fs-extra'); -const prompt = require('prompt'); -const path = require('path'); -const deSync = require('deasync'); - -// For hashing the admin's password into a trip. -const crypto = require('crypto'); - -const hash = (password) => { - let sha = crypto.createHash('sha256'); - sha.update(password); - return sha.digest('base64').substr(0, 6); -}; - -class ConfigManager { - /** - * Create a `ConfigManager` instance for (re)loading classes and config - * - * @param {Object} core reference to the global core object - * @param {String} base executing directory name; __dirname - * @param {Object} dynamicImports dynamic import engine reference - */ - constructor (core, base, dynamicImports) { - this._core = core; - this._base = base; - - this._configPath = path.resolve(base, 'config/config.json'); - - this._dynamicImports = dynamicImports; - } - - /** - * Pulls both core config questions along with any optional config questions, - * used in building the initial config.json or re-building it. - * - * @param {Object} currentConfig an object containing current server settings, if any - * @param {Object} optionalConfigs optional (non-core) module config - */ - getQuestions (currentConfig, optionalConfigs) { - let salt = null; // this is so it can be accessed from adminTrip. - - // core server setup questions - const questions = { - properties: { - tripSalt: { - type: 'string', - required: !currentConfig.tripSalt, - default: currentConfig.tripSalt, - hidden: true, - replace: '*', - before: value => { - salt = value; - return salt; - } - }, - adminName: { - pattern: /^"?[a-zA-Z0-9_]+"?$/, - type: 'string', - message: 'Nicks can only contain letters, numbers and underscores', - required: !currentConfig.adminName, - default: currentConfig.adminName, - before: value => value.replace(/"/g, '') - }, - adminTrip: { - type: 'string', - required: !currentConfig.adminTrip, - default: currentConfig.adminTrip, - hidden: true, - replace: '*', - description: 'adminPass', - before: value => hash(value + salt) - }, - websocketPort: { - type: 'number', - required: !currentConfig.websocketPort, - default: currentConfig.websocketPort || 6060 - } - } - }; - - // non-core server setup questions, for future plugin support - Object.keys(optionalConfigs).forEach(configName => { - const config = optionalConfigs[configName]; - const question = config.getQuestion(currentConfig, configName); - - if (!question) { - return; - } - - question.description = (question.description || configName) + ' (Optional)'; - questions.properties[configName] = question; - }); - - return questions; - } - - /** - * `load` function overload, only blocking - * - */ - loadSync () { - let conf = {}; - conf = this.load(); - - // websocketport is the last core config question, wait until it's been populated - while(conf === null || typeof conf.websocketPort === 'undefined') { - deSync.sleep(100); - } - - return conf; - } - - /** - * (Re)builds the config.json (main server config), or loads the config into mem - * if rebuilding, process will exit- this is to allow a process manager to take over - * - * @param {Boolean} reconfiguring set to true by `scripts/configure.js`, will exit if true - */ - load (reconfiguring = false) { - if (reconfiguring || !fse.existsSync(this._configPath)) { - // gotta have that sexy console - console.log(stripIndents` - ${chalk.magenta('°º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸°º¤ø,¸¸,ø¤º°`°º¤ø')} - ${chalk.gray('--------------(') + chalk.white(' HackChat Setup Wizard v1.0 ') + chalk.gray(')--------------')} - ${chalk.magenta('°º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸°º¤ø,¸¸,ø¤º°`°º¤ø')} - - For advanced setup, see the documentation at: - ${chalk.green('https://github.com/hack-chat/main/tree/master/documentation')} - - ${chalk.white('Note:')} ${chalk.green('npm/yarn run config')} will re-run this utility. - - You will now be asked for the following: - - ${chalk.magenta(' Salt')}, the salt for username trip - - ${chalk.magenta('Admin Name')}, the initial admin username - - ${chalk.magenta('Admin Pass')}, the initial admin password - - ${chalk.magenta(' Port')}, the port for the websocket - \u200b - `); - - let currentConfig = this._config || {}; - if (reconfiguring && fse.existsSync(this._configPath)) { - this._backup(); - currentConfig = fse.readJSONSync(this._configPath); - } - - prompt.get(this.getQuestions(currentConfig, this._dynamicImports.optionalConfigs), (err, res) => { - if (typeof res.mods === 'undefined') { - res.mods = []; - } - - if (err) { - console.error(err); - process.exit(666); // SPOOKY! - } - - try { - fse.outputJsonSync(this._configPath, res); - } catch (e) { - console.error(`Couldn't write config to ${this._configPath}\n${e.stack}`); - if (!reconfiguring) { - process.exit(666); // SPOOKY! - } - } - - console.log('Config generated! You may now start the server normally.') - - process.exit(reconfiguring ? 0 : 42); - }); - - return null; - } - - this._config = fse.readJSONSync(this._configPath); - - return this._config; - } - - /** - * Creates backup of current config into _configPath - * - */ - _backup () { - const backupPath = `${this._configPath}.${dateFormat('dd-mm-yy-HH-MM-ss')}.bak`; - fse.copySync(this._configPath, backupPath); - - return backupPath; - } - - /** - * First makes a backup of the current `config.json`, then writes current config - * to disk - * - */ - save () { - const backupPath = this._backup(); - - if (!fse.existsSync(this._configPath)){ - fse.mkdirSync(this._configPath); - } - - try { - fse.writeJSONSync(this._configPath, this._config); - fse.removeSync(backupPath); - - return true; - } catch (err) { - console.log(`Failed to save config file: ${err}`); - - return false; - } - } - - /** - * Updates current config[`key`] with `value` then writes changes to disk - * - * @param {*} key arbitrary configuration key - * @param {*} value new value to change `key` to - */ - set (key, value) { - const realKey = `${key}`; - this._config[realKey] = value; - - this.save(); - } -} - -module.exports = ConfigManager; diff --git a/server/src/managers/imports-manager.js b/server/src/managers/imports-manager.js deleted file mode 100644 index d8b2144..0000000 --- a/server/src/managers/imports-manager.js +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Import managment base, used to load commands/protocol and configuration objects - * - * Version: v2.0.0 - * Developer: Marzavec ( https://github.com/marzavec ) - * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) - * - */ - -const read = require('readdir-recursive'); -const path = require('path'); - -class ImportsManager { - /** - * Create a `ImportsManager` instance for (re)loading classes and config - * - * @param {Object} core reference to the global core object - * @param {String} base executing directory name; __dirname - */ - constructor (core, base) { - this._core = core; - this._base = base; - - this._imports = {}; - this._optionalConfigs = {}; - } - - /** - * Pull core reference - * - * @type {Object} readonly - */ - get core () { - return this._core; - } - - /** - * Pull base path that all imports are required in from - * - * @type {String} readonly - */ - get base () { - return this._base; - } - - /** - * Pull optional (none-core) config options - * - * @type {Object} - */ - get optionalConfigs () { - return Object.assign({}, this._optionalConfigs); - } - - /** - * Initialize this class and start loading target directories - * - */ - init () { - let errorText = ''; - ImportsManager.load_dirs.forEach(dir => { - errorText += this.loadDir(dir); - }); - - return errorText; - } - - /** - * Gather all js files from target directory, then verify and load - * - * @param {String} dirName The name of the dir to load, relative to the _base path. - */ - loadDir (dirName) { - const dir = path.resolve(this._base, dirName); - - let errorText = ''; - try { - read.fileSync(dir).forEach(file => { - const basename = path.basename(file); - if (basename.startsWith('_') || !basename.endsWith('.js')) return; - - let imported; - try { - imported = require(file); - } catch (e) { - let err = `Unable to load modules from ${dirName} (${path.relative(dir, file)})\n${e}`; - errorText += err; - console.error(err); - return errorText; - } - - if (imported.configs) { - imported.configs.forEach(config => { - this._optionalConfigs[config.name] = config; - }); - } - - if (!this._imports[dirName]) { - this._imports[dirName] = {}; - } - - this._imports[dirName][file] = imported; - }); - } catch (e) { - let err = `Unable to load modules from ${dirName}\n${e}`; - errorText += err; - console.error(err); - return errorText; - } - - return errorText; - } - - /** - * Unlink references to each loaded module, pray to google that gc knows it's job, - * then reinitialize this class to start the reload - * - * @param {String} dirName The name of the dir to load, relative to the _base path. - */ - reloadDirCache (dirName) { - Object.keys(this._imports[dirName]).forEach((mod) => { - delete require.cache[require.resolve(mod)]; - }); - - return this.init(); - } - - /** - * Pull reference to imported modules that were imported from dirName, or - * load required directory if not found - * - * @param {String} dirName The name of the dir to load, relative to the _base path. - */ - getImport (dirName) { - let imported = this._imports[dirName]; - - if (!imported) { - this.loadDir(dirName); - } - - return Object.assign({}, this._imports[dirName]); - } -} - -// automagically loaded directorys on instantiation -ImportsManager.load_dirs = ['src/commands']; - -module.exports = ImportsManager; diff --git a/server/src/managers/index.js b/server/src/managers/index.js deleted file mode 100644 index 2fac8fb..0000000 --- a/server/src/managers/index.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = { - CommandManager: require('./commands'), - Config: require('./config'), - ImportsManager: require('./imports-manager'), - Stats: require('./stats') -}; diff --git a/server/src/managers/stats.js b/server/src/managers/stats.js deleted file mode 100644 index 20f1ae3..0000000 --- a/server/src/managers/stats.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Simple generic stats collection script for events occurances (etc) - * - * Version: v2.0.0 - * Developer: Marzavec ( https://github.com/marzavec ) - * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) - * - */ - -class Stats { - /** - * Create a stats instance. - * - */ - constructor () { - this._stats = {}; - } - - /** - * Retrieve value of arbitrary `key` reference - * - * @param {String} key Reference to the arbitrary store name - */ - get (key) { - return this._stats[key]; - } - - /** - * Set value of arbitrary `key` reference - * - * @param {String} key Reference to the arbitrary store name - * @param {Number} value New value for `key` - */ - set (key, value) { - this._stats[key] = value; - } - - /** - * Increase value of arbitrary `key` reference, by 1 or `amount` - * - * @param {String} key Reference to the arbitrary store name - * @param {Number} amount Value to increase `key` by, or 1 if omitted - */ - increment (key, amount) { - this.set(key, (this.get(key) || 0) + (amount || 1)); - } - - /** - * Reduce value of arbitrary `key` reference, by 1 or `amount` - * - * @param {String} key Reference to the arbitrary store name - * @param {Number} amount Value to decrease `key` by, or 1 if omitted - */ - decrement (key, amount) { - this.set(key, (this.get(key) || 0) - (amount || 1)); - } -} - -module.exports = Stats; diff --git a/server/src/scripts/configLib/SetupWizard.js b/server/src/scripts/configLib/SetupWizard.js new file mode 100644 index 0000000..339878d --- /dev/null +++ b/server/src/scripts/configLib/SetupWizard.js @@ -0,0 +1,107 @@ +/** + * Server setup wizard, quick server setup and all that jazz. . . + * + * Version: v2.0.0 + * Developer: Marzavec ( https://github.com/marzavec ) + * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) + * + */ + +const fse = require('fs-extra'); +const prompt = require('prompt'); +const path = require('path'); + +class SetupWizard { + /** + * Create a `SetupWizard` instance for initializing the server's config.json + * + * @param {Object} serverConfig reference to the server config class + */ + constructor (serverConfig) { + this.serverConfig = serverConfig; + } + + /** + * Roll a d20 and begin the wizarding process + * + */ + async start () { + // load the current config to use as defaults, if available + let currentConfig = await this.serverConfig.load() || {}; + + // auto generate the salt if not currrently created + currentConfig.tripSalt = currentConfig.tripSalt || + [...Array(Math.floor(Math.random()*1024)+1024)].map(i=>(~~(Math.random()*36)).toString(36)).join(''); + + // load the setup questions & set their defaults + let questions = require('../setupSchema/Questions.js'); + questions.properties = this.setQuestionDefaults(questions.properties, currentConfig); + + // force password re-entry + questions.properties.adminTrip.default = ''; + questions.properties.adminTrip.required = true; + + // output the packages setup banner + require('../setupSchema/Banner.js'); + + // let's start playing 20 questions + prompt.start(); + prompt.get(questions, (err, result) => this.finalize(err, result)); + } + + /** + * Compares the currently loaded config with the stock questions, adds a default + * and required option to the question + * + * @param {Object} questions the set of questions from /setupSchema + * @param {Object} currentConfig the current server options + */ + setQuestionDefaults (questions, currentConfig) { + Object.keys(questions).forEach(qName => { + if (typeof currentConfig[qName] !== 'undefined') { + questions[qName].default = currentConfig[qName]; + questions[qName].required = false; + } else { + questions[qName].required = true; + } + }); + + return questions; + } + + /** + * Looks like all the questions have been answered, check for errors or save + * the new config file + * + * @param {Object} err any errors generated by Prompt + * @param {Object} result the answers / new config setup + */ + async finalize (err, result) { + // output errors and die if needed + if (err) { + console.error(err); + process.exit(0); + } + + // initialize default mods config + if (typeof result.mods === 'undefined') { + result.mods = []; + } + + // finally create the actual JSON file + try { + this.serverConfig.config = result; + await this.serverConfig.save(); + } catch (e) { + console.error(`Couldn't write config to ${this.serverConfig.configPath} + ${e.stack}`); + } + + // output the packages final notice before quitting + require('../setupSchema/Footer.js'); + + process.exit(0); + } +} + +module.exports = SetupWizard; diff --git a/server/src/scripts/configure.js b/server/src/scripts/configure.js index 0ecd858..d7f2bf2 100644 --- a/server/src/scripts/configure.js +++ b/server/src/scripts/configure.js @@ -1,5 +1,5 @@ /** - * Server configuration script, used reconfiguring server options + * Server configuration script, to (re)configure server options * * Version: v2.0.0 * Developer: Marzavec ( https://github.com/marzavec ) @@ -11,13 +11,11 @@ // import required classes const path = require('path'); -const ImportsManager = require('../managers/imports-manager'); -const ConfigManager = require('../managers/config'); +const ConfigManager = require('../serverLib/ConfigManager'); +const SetupWizard = require('./configLib/SetupWizard'); // import and initialize configManager & dependencies -const importManager = new ImportsManager(null, path.join(__dirname, '../..')); -importManager.init(); -const configManager = new ConfigManager(null, path.join(__dirname, '../..'), importManager); +const serverConfig = new ConfigManager(path.join(__dirname, '../..')); +const setup = new SetupWizard(serverConfig); -// execute config load with `reconfiguring` flag set to true -configManager.load(true); +setup.start(); diff --git a/server/src/scripts/setupSchema/Banner.js b/server/src/scripts/setupSchema/Banner.js new file mode 100644 index 0000000..823f0fe --- /dev/null +++ b/server/src/scripts/setupSchema/Banner.js @@ -0,0 +1,28 @@ +/** + * This script will be run before the package starts asking for the config data, + * used to output a simple guide for the coming questions, or to spam some sexy + * ascii art at the user. + * + */ + +const stripIndents = require('common-tags').stripIndents; +const chalk = require('chalk'); + +// gotta have that sexy console +console.log(stripIndents` + ${chalk.magenta('°º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸°º¤ø,¸¸,ø¤º°`°º¤ø')} + ${chalk.gray('--------------(') + chalk.white(' HackChat Setup Wizard v2.0 ') + chalk.gray(')--------------')} + ${chalk.magenta('°º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸°º¤ø,¸¸,ø¤º°`°º¤ø')} + + For advanced setup, see the documentation at: + ${chalk.green('https://github.com/hack-chat/main/tree/master/documentation')} + + ${chalk.white('Note:')} ${chalk.green('npm/yarn run config')} will re-run this utility. + + You will now be asked for the following: + - ${chalk.magenta(' Salt')}, the salt for username trip + - ${chalk.magenta('Admin Name')}, the initial admin username + - ${chalk.magenta('Admin Pass')}, the initial admin password + - ${chalk.magenta(' Port')}, the port for the websocket + \u200b +`); diff --git a/server/src/scripts/setupSchema/Footer.js b/server/src/scripts/setupSchema/Footer.js new file mode 100644 index 0000000..d2ee14f --- /dev/null +++ b/server/src/scripts/setupSchema/Footer.js @@ -0,0 +1,7 @@ +/** + * This script will be run once all questions have finished and no errors have + * occured. You can congratulate the user on their fine choice in software usage + * + */ + +console.log('Config generated! You may now start the server normally.'); diff --git a/server/src/scripts/setupSchema/Questions.js b/server/src/scripts/setupSchema/Questions.js new file mode 100644 index 0000000..f84d32f --- /dev/null +++ b/server/src/scripts/setupSchema/Questions.js @@ -0,0 +1,55 @@ +/** + * This object contains Prompt ( https://www.npmjs.com/package/prompt ) style + * questions that the SetupWizard will require an answer to. Questions are asked + * in the order they are specified here. + * + * The resulting config.json file will be used by the server, accessed by the + * name specified. IE, a valid use is; config.adminName + * + */ + +const Questions = { + properties: { + tripSalt: { + description: 'Salt (leave as default)', + type: 'string', + hidden: true, + replace: '*', + before: value => { + salt = value; + return value; + } + }, + + adminName: { + description: 'Admin Nickname', + pattern: /^"?[a-zA-Z0-9_]+"?$/, + type: 'string', + message: 'Nicks can only contain letters, numbers and underscores', + before: value => value.replace(/"/g, '') + }, + + adminTrip: { + type: 'string', + hidden: true, + replace: '*', + description: 'Admin Password', + message: 'You must enter or re-enter a password', + before: value => { + const crypto = require('crypto'); + let sha = crypto.createHash('sha256'); + sha.update(value + salt); + return sha.digest('base64').substr(0, 6); + } + }, + + websocketPort: { + type: 'integer', + message: 'The port may only be a number!', + description: 'Websocket Port', + default: '6060' + } + } +} + +module.exports = Questions; diff --git a/server/src/serverLib/CommandManager.js b/server/src/serverLib/CommandManager.js new file mode 100644 index 0000000..71c8884 --- /dev/null +++ b/server/src/serverLib/CommandManager.js @@ -0,0 +1,250 @@ +/** + * Commands / protocol manager- loads, validates and handles command execution + * + * Version: v2.0.0 + * Developer: Marzavec ( https://github.com/marzavec ) + * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) + * + */ + +const path = require('path'); +const didYouMean = require('didyoumean2').default; + +class CommandManager { + /** + * Create a `CommandManager` instance for handling commands/protocol + * + * @param {Object} core Reference to the global core object + */ + constructor (core) { + this.core = core; + this._commands = []; + this._categories = []; + } + + /** + * (Re)initializes name spaces for commands and starts load routine + * + */ + loadCommands () { + this._commands = []; + this._categories = []; + + const core = this.core; + + const commandImports = core.dynamicImports.getImport('src/commands'); + let cmdErrors = ''; + Object.keys(commandImports).forEach(file => { + let command = commandImports[file]; + let name = path.basename(file); + cmdErrors += this._validateAndLoad(command, file, name); + }); + + return cmdErrors; + } + + /** + * Checks the module after having been `require()`ed in and reports errors + * + * @param {Object} command reference to the newly loaded object + * @param {String} file file path to the module + * @param {String} name command (`cmd`) name + */ + _validateAndLoad (command, file, name) { + let error = this._validateCommand(command); + + if (error) { + let errText = `Failed to load '${name}': ${error}`; + console.log(errText); + return errText; + } + + if (!command.category) { + let base = path.join(this.core.dynamicImports.base, 'commands'); + + let category = 'Uncategorized'; + if (file.indexOf(path.sep) > -1) { + category = path.dirname(path.relative(base, file)) + .replace(new RegExp(path.sep.replace('\\', '\\\\'), 'g'), '/'); + } + + command.info.category = category; + + if (this._categories.indexOf(category) === -1) { + this._categories.push(category); + } + } + + if (typeof command.init === 'function') { + try { + command.init(this.core); + } catch (err) { + let errText = `Failed to initialize '${name}': ${err}`; + console.log(errText); + return errText; + } + } + + this._commands.push(command); + + return ''; + } + + /** + * Checks the module after having been `require()`ed in and reports errors + * + * @param {Object} object reference to the newly loaded object + */ + _validateCommand (object) { + if (typeof object !== 'object') + return 'command setup is invalid'; + + if (typeof object.run !== 'function') + return 'run function is missing'; + + if (typeof object.info !== 'object') + return 'info object is missing'; + + if (typeof object.info.name !== 'string') + return 'info object is missing a valid name field'; + + return null; + } + + /** + * Pulls all command names from a passed `category` + * + * @param {String} category [Optional] filter return results by this category + */ + all (category) { + return !category ? this._commands : this._commands.filter(c => c.info.category.toLowerCase() === category.toLowerCase()); + } + + /** + * Pulls all category names + * + */ + categories () { + return this._categories; + } + + /** + * Pulls command by name or alia(s) + * + * @param {String} name name or alias of command + */ + get (name) { + return this.findBy('name', name) + || this._commands.find(command => command.info.aliases instanceof Array && command.info.aliases.indexOf(name) > -1); + } + + /** + * Pulls command by arbitrary search of the `module.info` attribute + * + * @param {String} key name or alias of command + * @param {String} value name or alias of command + */ + findBy (key, value) { + return this._commands.find(c => c.info[key] === value); + } + + /** + * Runs `initHooks` function on any modules that utilize the event + * + * @param {Object} server main server object + */ + initCommandHooks (server) { + this._commands.filter(c => typeof c.initHooks !== 'undefined').forEach(c => c.initHooks(server)); + } + + /** + * Finds and executes the requested command, or fails with semi-intelligent error + * + * @param {Object} server main server reference + * @param {Object} socket calling socket reference + * @param {Object} data command structure passed by socket (client) + */ + handleCommand (server, socket, data) { + // Try to find command first + let command = this.get(data.cmd); + + if (command) { + return this.execute(command, server, socket, data); + } else { + // Then fail with helpful (sorta) message + return this._handleFail(server, socket, data); + } + } + + /** + * Requested command failure handler, attempts to find command and reports back + * + * @param {Object} server main server reference + * @param {Object} socket calling socket reference + * @param {Object} data command structure passed by socket (client) + */ + _handleFail(server, socket, data) { + const maybe = didYouMean(data.cmd, this.all().map(c => c.info.name), { + threshold: 5, + thresholdType: 'edit-distance' + }); + + if (maybe) { + // Found a suggestion, pass it on to their dyslexic self + return this.handleCommand(server, socket, { + cmd: 'socketreply', + cmdKey: server._cmdKey, + text: `Command not found, did you mean: \`${maybe}\`?` + }); + } + + // Request so mangled that I don't even, silently fail + return; + } + + /** + * Attempt to execute the requested command, fail if err or bad params + * + * @param {Object} command target command module + * @param {Object} server main server reference + * @param {Object} socket calling socket reference + * @param {Object} data command structure passed by socket (client) + */ + async execute(command, server, socket, data) { + if (typeof command.requiredData !== 'undefined') { + let missing = []; + for (let i = 0, len = command.requiredData.length; i < len; i++) { + if (typeof data[command.requiredData[i]] === 'undefined') + missing.push(command.requiredData[i]); + } + + if (missing.length > 0) { + console.log(`Failed to execute '${command.info.name}': missing required ${missing.join(', ')}\n\n`); + this.handleCommand(server, socket, { + cmd: 'socketreply', + cmdKey: server._cmdKey, + text: `Failed to execute '${command.info.name}': missing required ${missing.join(', ')}\n\n` + }); + + return null; + } + } + + try { + return await command.run(this.core, server, socket, data); + } catch (err) { + let errText = `Failed to execute '${command.info.name}': ${err}`; + console.log(errText); + + this.handleCommand(server, socket, { + cmd: 'socketreply', + cmdKey: server._cmdKey, + text: errText + }); + + return null; + } + } +} + +module.exports = CommandManager; diff --git a/server/src/serverLib/ConfigManager.js b/server/src/serverLib/ConfigManager.js new file mode 100644 index 0000000..ebec050 --- /dev/null +++ b/server/src/serverLib/ConfigManager.js @@ -0,0 +1,89 @@ +/** + * Server configuration manager, handling loading, creation, parsing and saving + * of the main config.json file + * + * Version: v2.0.0 + * Developer: Marzavec ( https://github.com/marzavec ) + * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) + * + */ +const dateFormat = require('dateformat'); +const fse = require('fs-extra'); +const path = require('path'); + +class ConfigManager { + /** + * Create a `ConfigManager` instance for managing application settings + * + * @param {String} base executing directory name; __dirname + */ + constructor (base = __dirname) { + this.configPath = path.resolve(base, 'config/config.json'); + + if (!fse.existsSync(this.configPath)){ + fse.ensureFileSync(this.configPath); + } + } + + /** + * (Re)builds the config.json (main server config), or loads the config into mem + * if rebuilding, process will exit- this is to allow a process manager to take over + * + * @param {Boolean} reconfiguring set to true by `scripts/configure.js`, will exit if true + */ + async load () { + try { + this.config = fse.readJsonSync(this.configPath); + } catch (e) { + return false; + } + + return this.config; + } + + /** + * Creates backup of current config into configPath + * + */ + async backup () { + const backupPath = `${this.configPath}.${dateFormat('dd-mm-yy-HH-MM-ss')}.bak`; + fse.copySync(this.configPath, backupPath); + + return backupPath; + } + + /** + * First makes a backup of the current `config.json`, then writes current config + * to disk + * + */ + async save () { + const backupPath = await this.backup(); + + try { + fse.writeJSONSync(this.configPath, this.config); + fse.removeSync(backupPath); + + return true; + } catch (err) { + console.log(`Failed to save config file: ${err}`); + + return false; + } + } + + /** + * Updates current config[`key`] with `value` then writes changes to disk + * + * @param {*} key arbitrary configuration key + * @param {*} value new value to change `key` to + */ + async set (key, value) { + const realKey = `${key}`; + this.config[realKey] = value; + + return await this.save(); + } +} + +module.exports = ConfigManager; diff --git a/server/src/serverLib/CoreApp.js b/server/src/serverLib/CoreApp.js new file mode 100644 index 0000000..012ae44 --- /dev/null +++ b/server/src/serverLib/CoreApp.js @@ -0,0 +1,66 @@ +/** + * The core / global reference object + * + * Version: v2.0.0 + * Developer: Marzavec ( https://github.com/marzavec ) + * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) + * + */ + +const path = require('path'); +const { + CommandManager, + ConfigManager, + ImportsManager, + MainServer, + StatsManager +} = require('./'); + +class CoreApp { + /** + * Create the main core instance. + */ + constructor () { + + } + + async init () { + await this.buildConfigManager(); + + this.buildImportManager(); + this.buildCommandsManager(); + this.buildStatsManager(); + this.buildMainServer(); + } + + async buildConfigManager () { + this.configManager = new ConfigManager(path.join(__dirname, '../..')); + this.config = await this.configManager.load(); + + if (this.config === false) { + console.error('Missing config.json, have you run: npm run config'); + process.exit(0); + } + } + + buildImportManager () { + this.dynamicImports = new ImportsManager(path.join(__dirname, '../..')); + this.dynamicImports.init(); + } + + buildCommandsManager () { + this.commands = new CommandManager(this); + this.commands.loadCommands(); + } + + buildStatsManager () { + this.stats = new StatsManager(this); + this.stats.set('start-time', process.hrtime()); + } + + buildMainServer () { + this.server = new MainServer(this); + } +} + +module.exports = CoreApp; diff --git a/server/src/serverLib/ImportsManager.js b/server/src/serverLib/ImportsManager.js new file mode 100644 index 0000000..a049d5c --- /dev/null +++ b/server/src/serverLib/ImportsManager.js @@ -0,0 +1,121 @@ +/** + * Import managment base, used to load commands/protocol and configuration objects + * + * Version: v2.0.0 + * Developer: Marzavec ( https://github.com/marzavec ) + * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) + * + */ + +const read = require('readdir-recursive'); +const path = require('path'); + +class ImportsManager { + /** + * Create a `ImportsManager` instance for (re)loading classes and config + * + * @param {String} base executing directory name; __dirname + */ + constructor (base) { + this._base = base; + + this._imports = {}; + } + + /** + * Pull base path that all imports are required in from + * + * @type {String} readonly + */ + get base () { + return this._base; + } + + /** + * Initialize this class and start loading target directories + * + */ + init () { + let errorText = ''; + ImportsManager.load_dirs.forEach(dir => { + errorText += this.loadDir(dir); + }); + + return errorText; + } + + /** + * Gather all js files from target directory, then verify and load + * + * @param {String} dirName The name of the dir to load, relative to the _base path. + */ + loadDir (dirName) { + const dir = path.resolve(this._base, dirName); + + let errorText = ''; + try { + read.fileSync(dir).forEach(file => { + const basename = path.basename(file); + if (basename.startsWith('_') || !basename.endsWith('.js')) return; + + let imported; + try { + imported = require(file); + } catch (e) { + let err = `Unable to load modules from ${dirName} (${path.relative(dir, file)})\n${e}`; + errorText += err; + console.error(err); + return errorText; + } + + if (!this._imports[dirName]) { + this._imports[dirName] = {}; + } + + this._imports[dirName][file] = imported; + }); + } catch (e) { + let err = `Unable to load modules from ${dirName}\n${e}`; + errorText += err; + console.error(err); + return errorText; + } + + return errorText; + } + + /** + * Unlink references to each loaded module, pray to google that gc knows it's job, + * then reinitialize this class to start the reload + * + * @param {String} dirName The name of the dir to load, relative to the _base path. + */ + reloadDirCache (dirName) { + Object.keys(this._imports[dirName]).forEach((mod) => { + delete require.cache[require.resolve(mod)]; + }); + + return this.init(); + } + + /** + * Pull reference to imported modules that were imported from dirName, or + * load required directory if not found + * + * @param {String} dirName The name of the dir to load, relative to the _base path. + */ + getImport (dirName) { + let imported = this._imports[dirName]; + + if (!imported) { + this.loadDir(dirName); + } + + return Object.assign({}, this._imports[dirName]); + } +} + +// automagically loaded directorys on instantiation +ImportsManager.load_dirs = ['src/commands']; + +module.exports = ImportsManager; diff --git a/server/src/serverLib/MainServer.js b/server/src/serverLib/MainServer.js new file mode 100644 index 0000000..628d8ab --- /dev/null +++ b/server/src/serverLib/MainServer.js @@ -0,0 +1,434 @@ +/** + * Main websocket server handling communications and connection events + * + * Version: v2.0.0 + * Developer: Marzavec ( https://github.com/marzavec ) + * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) + * + */ + +const wsServer = require('ws').Server; +const socketReady = require('ws').OPEN; +const crypto = require('crypto'); +const ipSalt = [...Array(Math.floor(Math.random()*128)+128)].map(i=>(~~(Math.random()*36)).toString(36)).join(''); +const internalCmdKey = [...Array(Math.floor(Math.random()*128)+128)].map(i=>(~~(Math.random()*36)).toString(36)).join(''); +const RateLimiter = require('./RateLimiter'); +const pulseSpeed = 16000; // ping all clients every X ms + +class MainServer extends wsServer { + /** + * Create a HackChat server instance. + * + * @param {Object} core Reference to the global core object + */ + constructor (core) { + super({ port: core.config.websocketPort }); + + this._core = core; + this._hooks = {}; + this._police = new RateLimiter(); + this._cmdBlacklist = {}; + this._cmdKey = internalCmdKey; + + this._heartBeat = setInterval(() => this.beatHeart(), pulseSpeed); + + this.on('error', (err) => { + this.handleError('server', err); + }); + + this.on('connection', (socket, request) => { + this.newConnection(socket, request); + }); + + this.loadHooks(); + } + + /** + * Send empty `ping` frame to each client + * + */ + beatHeart () { + let targetSockets = this.findSockets({}); + + if (targetSockets.length === 0) { + return; + } + + for (let i = 0, l = targetSockets.length; i < l; i++) { + try { + if (targetSockets[i].readyState === socketReady) { + targetSockets[i].ping(); + } + } catch (e) { } + } + } + + /** + * Bind listeners for the new socket created on connection to this class + * + * @param {Object} socket New socket object + * @param {Object} request Initial headers of the new connection + */ + newConnection (socket, request) { + socket.remoteAddress = request.headers['x-forwarded-for'] || request.connection.remoteAddress; + + socket.on('message', (data) => { + this.handleData(socket, data); + }); + + socket.on('close', () => { + this.handleClose(socket); + }); + + socket.on('error', (err) => { + this.handleError(socket, err); + }); + } + + /** + * Handle incoming messages from clients, parse and check command, then hand-off + * + * @param {Object} socket Calling socket object + * @param {String} data Message sent from client + */ + handleData (socket, data) { + // Don't penalize yet, but check whether IP is rate-limited + if (this._police.frisk(socket.remoteAddress, 0)) { + this._core.commands.handleCommand(this, socket, { + cmd: 'socketreply', + cmdKey: this._cmdKey, + text: 'Your IP is being rate-limited or blocked.' + }); + + return; + } + + // Penalize here, but don't do anything about it + this._police.frisk(socket.remoteAddress, 1); + + // Ignore ridiculously large packets + if (data.length > 65536) { + return; + } + + // Start sent data verification + var payload = null; + try { + payload = JSON.parse(data); + } catch (e) { + // Client sent malformed json, gtfo + socket.close(); + } + + if (payload === null) { + return; + } + + if (typeof payload.cmd === 'undefined') { + return; + } + + if (typeof payload.cmd !== 'string') { + return; + } + + if (typeof socket.channel === 'undefined' && (payload.cmd !== 'join' && payload.cmd !== 'chat')) { + return; + } + + if (typeof this._cmdBlacklist[payload.cmd] === 'function') { + return; + } + + // Execute `in` (incoming data) hooks and process results + payload = this.executeHooks('in', socket, payload); + + if (typeof payload === 'string') { + // A hook malfunctioned, reply with error + this._core.commands.handleCommand(this, socket, { + cmd: 'socketreply', + cmdKey: this._cmdKey, + text: payload + }); + + return; + } else if (payload === false) { + // A hook requested this data be dropped + return; + } + + // Finished verification & hooks, pass to command modules + this._core.commands.handleCommand(this, socket, payload); + } + + /** + * Handle socket close from clients + * + * @param {Object} socket Closing socket object + */ + handleClose (socket) { + this._core.commands.handleCommand(this, socket, { + cmd: 'disconnect', + cmdKey: this._cmdKey + }); + } + + /** + * "Handle" server or socket errors + * + * @param {Object||String} socket Calling socket object, or 'server' + * @param {String} err The sad stuff + */ + handleError (socket, err) { + console.log(`Server error: ${err}`); + } + + /** + * Send data payload to specific socket/client + * + * @param {Object} payload Object to convert to json for transmission + * @param {Object} socket The target client + */ + send (payload, socket) { + // Add timestamp to command + payload.time = Date.now(); + + // Execute `in` (incoming data) hooks and process results + payload = this.executeHooks('out', socket, payload); + + if (typeof payload === 'string') { + // A hook malfunctioned, reply with error + this._core.commands.handleCommand(this, socket, { + cmd: 'socketreply', + cmdKey: this._cmdKey, + text: payload + }); + + return; + } else if (payload === false) { + // A hook requested this data be dropped + return; + } + + try { + if (socket.readyState === socketReady) { + socket.send(JSON.stringify(payload)); + } + } catch (e) { } + } + + /** + * Overload function for `this.send()` + * + * @param {Object} payload Object to convert to json for transmission + * @param {Object} socket The target client + */ + reply (payload, socket) { + this.send(payload, socket); + } + + /** + * Finds sockets/clients that meet the filter requirements, then passes the data to them + * + * @param {Object} payload Object to convert to json for transmission + * @param {Object} filter see `this.findSockets()` + */ + broadcast (payload, filter) { + let targetSockets = this.findSockets(filter); + + if (targetSockets.length === 0) { + return false; + } + + for (let i = 0, l = targetSockets.length; i < l; i++) { + this.send(payload, targetSockets[i]); + } + + return true; + } + + /** + * Finds sockets/clients that meet the filter requirements, returns result as array + * + * @param {Object} data Object to convert to json for transmission + * @param {Object} filter The socket must of equal or greater attribs matching `filter` + * = {} // matches all + * = { channel: 'programming' } // matches any socket where (`socket.channel` === 'programming') + * = { channel: 'programming', nick: 'Marzavec' } // matches any socket where (`socket.channel` === 'programming' && `socket.nick` === 'Marzavec') + */ + findSockets (filter) { + let filterAttribs = Object.keys(filter); + let reqCount = filterAttribs.length; + let curMatch; + let matches = []; + for ( let socket of this.clients ) { + curMatch = 0; + + for (let i = 0; i < reqCount; i++) { + if (typeof socket[filterAttribs[i]] !== 'undefined') { + switch(typeof filter[filterAttribs[i]]) { + case 'object': { + if (Array.isArray(filter[filterAttribs[i]])) { + if (filter[filterAttribs[i]].indexOf(socket[filterAttribs[i]]) !== -1) { + curMatch++; + } + } else { + if (socket[filterAttribs[i]] === filter[filterAttribs[i]]) { + curMatch++; + } + } + break; + } + + case 'function': { + if (filter[filterAttribs[i]](socket[filterAttribs[i]])) { + curMatch++; + } + break; + } + + default: { + if (socket[filterAttribs[i]] === filter[filterAttribs[i]]) { + curMatch++; + } + break; + } + } + } + } + + if (curMatch === reqCount) { + matches.push(socket); + } + } + + return matches; + } + + /** + * Hashes target socket's remote address using non-static variable length salt + * encodes and shortens the output, returns that value + * + * @param {Object||String} target Either the target socket or ip as string + */ + getSocketHash (target) { + let sha = crypto.createHash('sha256'); + + if (typeof target === 'string') { + sha.update(target + ipSalt); + } else { + sha.update(target.remoteAddress + ipSalt); + } + + return sha.digest('base64').substr(0, 15); + } + + /** + * (Re)loads all command module hooks, then sorts their order of operation by + * priority, ascending (0 being highest priority) + * + */ + loadHooks () { + // clear current hooks (if any) + this.clearHooks(); + // notify each module to register their hooks (if any) + this._core.commands.initCommandHooks(this); + + if (typeof this._hooks['in'] !== 'undefined') { + // start sorting, with incoming first + let curHooks = [ ...this._hooks['in'].keys() ]; + let hookObj = []; + for (let i = 0, j = curHooks.length; i < j; i++) { + hookObj = this._hooks['in'].get(curHooks[i]); + hookObj.sort( (h1, h2) => h1.priority - h2.priority ); + this._hooks['in'].set(hookObj); + } + } + + if (typeof this._hooks['out'] !== 'undefined') { + // then outgoing + curHooks = [ ...this._hooks['out'].keys() ]; + for (let i = 0, j = curHooks.length; i < j; i++) { + hookObj = this._hooks['out'].get(curHooks[i]); + hookObj.sort( (h1, h2) => h1.priority - h2.priority ); + this._hooks['out'].set(hookObj); + } + } + } + + /** + * Adds a target function to an array of hooks. Hooks are executed either before + * processing user input (`in`) or before sending data back to the client (`out`) + * and allows a module to modify each payload before moving forward + * + * @param {String} type The type of event, typically `in` (incoming) or `out` (outgoing) + * @param {String} command Should match the desired `cmd` attrib of the payload + * @param {Function} hookFunction Target function to execute, should accept `server`, `socket` and `payload` as parameters + * @param {Number} priority Execution priority, hooks with priority 1 will be executed before hooks with priority 200 for example + */ + registerHook (type, command, hookFunction, priority) { + if (typeof priority === 'undefined') { + priority = 25; + } + + if (typeof this._hooks[type] === 'undefined') { + this._hooks[type] = new Map(); + } + + if (!this._hooks[type].has(command)) { + this._hooks[type].set(command, []); + } + + this._hooks[type].get(command).push({ + run: hookFunction, + priority: priority + }); + } + + /** + * Loops through registered hooks & processes the results. Returned data will + * be one of three possiblities: + * A payload (modified or not) that will continue through the data flow + * A boolean false to indicate halting the data through flow + * A string which indicates an error occured in executing the hook + * + * @param {String} type The type of event, typically `in` (incoming) or `out` (outgoing) + * @param {Object} socket Either the target client or the client triggering the hook (depending on `type`) + * @param {Object} payload Either incoming data from client or outgoing data (depending on `type`) + */ + executeHooks (type, socket, payload) { + let command = payload.cmd; + + if (typeof this._hooks[type] !== 'undefined') { + if (this._hooks[type].has(command)) { + let hooks = this._hooks[type].get(command); + + for (let i = 0, j = hooks.length; i < j; i++) { + try { + payload = hooks[i].run(this._core, this, socket, payload); + } catch (err) { + let errText = `Hook failure, '${type}', '${command}': ${err}`; + console.log(errText); + return errText; + } + + // A hook function may choose to return false to prevent all further processing + if (payload === false) { + return false; + } + } + } + } + + return payload; + } + + /** + * Wipe server hooks to make ready for module reload calls + */ + clearHooks () { + this._hooks = {}; + } +} + +module.exports = MainServer; diff --git a/server/src/serverLib/RateLimiter.js b/server/src/serverLib/RateLimiter.js new file mode 100644 index 0000000..87a1f3a --- /dev/null +++ b/server/src/serverLib/RateLimiter.js @@ -0,0 +1,103 @@ +/** + * Tracks frequency of occurances based on `id` (remote address), then allows or + * denies command execution based on comparison with `threshold` + * + * Version: v2.0.0 + * Developer: Marzavec ( https://github.com/marzavec ) + * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) + * + */ + +class RateLimiter { + /** + * Create a ratelimiter instance. + */ + constructor () { + this._records = {}; + this._halflife = 30 * 1000; // milliseconds + this._threshold = 25; + this._hashes = []; + } + + /** + * Finds current score by `id` + * + * @param {String} id target id / address + * @public + * + * @memberof Police + */ + search (id) { + let record = this._records[id]; + + if (!record) { + record = this._records[id] = { + time: Date.now(), + score: 0 + } + } + + return record; + } + + /** + * Adjusts the current ratelimit score by `deltaScore` + * + * @param {String} id target id / address + * @param {Number} deltaScore amount to adjust current score by + * @public + * + * @memberof Police + */ + frisk (id, deltaScore) { + let record = this.search(id); + + if (record.arrested) { + return true; + } + + record.score *= Math.pow(2, -(Date.now() - record.time ) / this._halflife); + record.score += deltaScore; + record.time = Date.now(); + + if (record.score >= this._threshold) { + return true; + } + + return false; + } + + /** + * Statically set server to no longer accept traffic from `id` + * + * @param {String} id target id / address + * @public + * + * @memberof Police + */ + arrest (id, hash) { + let record = this.search(id); + + record.arrested = true; + this._hashes[hash] = id; + } + + /** + * Remove statically assigned limit from `id` + * + * @param {String} id target id / address + * @public + * + * @memberof Police + */ + pardon (id) { + if (typeof this._hashes[id] !== 'undefined') { + id = this._hashes[id]; + } + + let record = this.search(id); + record.arrested = false; + } +} + +module.exports = RateLimiter; diff --git a/server/src/serverLib/StatsManager.js b/server/src/serverLib/StatsManager.js new file mode 100644 index 0000000..4ec7ddf --- /dev/null +++ b/server/src/serverLib/StatsManager.js @@ -0,0 +1,59 @@ +/** + * Simple generic stats collection script for events occurances (etc) + * + * Version: v2.0.0 + * Developer: Marzavec ( https://github.com/marzavec ) + * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) + * + */ + +class StatsManager { + /** + * Create a stats instance. + * + */ + constructor () { + this.data = {}; + } + + /** + * Retrieve value of arbitrary `key` reference + * + * @param {String} key Reference to the arbitrary store name + */ + get (key) { + return this.data[key]; + } + + /** + * Set value of arbitrary `key` reference + * + * @param {String} key Reference to the arbitrary store name + * @param {Number} value New value for `key` + */ + set (key, value) { + this.data[key] = value; + } + + /** + * Increase value of arbitrary `key` reference, by 1 or `amount` + * + * @param {String} key Reference to the arbitrary store name + * @param {Number} amount Value to increase `key` by, or 1 if omitted + */ + increment (key, amount) { + this.set(key, (this.get(key) || 0) + (amount || 1)); + } + + /** + * Reduce value of arbitrary `key` reference, by 1 or `amount` + * + * @param {String} key Reference to the arbitrary store name + * @param {Number} amount Value to decrease `key` by, or 1 if omitted + */ + decrement (key, amount) { + this.set(key, (this.get(key) || 0) - (amount || 1)); + } +} + +module.exports = StatsManager; diff --git a/server/src/serverLib/index.js b/server/src/serverLib/index.js new file mode 100644 index 0000000..4583de6 --- /dev/null +++ b/server/src/serverLib/index.js @@ -0,0 +1,8 @@ +module.exports = { + CommandManager: require('./CommandManager'), + ConfigManager: require('./ConfigManager'), + ImportsManager: require('./ImportsManager'), + MainServer: require('./MainServer'), + RateLimiter: require('./RateLimiter'), + StatsManager: require('./StatsManager') +}; -- cgit v1.2.1