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 --- 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 + 8 files changed, 1130 insertions(+) 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 (limited to 'server/src/serverLib') 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