diff options
author | marzavec <admin@marzavec.com> | 2018-03-10 08:47:00 +0100 |
---|---|---|
committer | marzavec <admin@marzavec.com> | 2018-03-10 08:47:00 +0100 |
commit | fde6895720a4f417283b9e375583967b504de2f3 (patch) | |
tree | f5c8d9a188572d759456831d574bef9881d5c0be /server | |
download | hackchat-fde6895720a4f417283b9e375583967b504de2f3.tar.gz hackchat-fde6895720a4f417283b9e375583967b504de2f3.zip |
initial commit
Diffstat (limited to 'server')
28 files changed, 2239 insertions, 0 deletions
diff --git a/server/README.md b/server/README.md new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/server/README.md diff --git a/server/main.js b/server/main.js new file mode 100644 index 0000000..2e66cc1 --- /dev/null +++ b/server/main.js @@ -0,0 +1,34 @@ +/** + * HackChat main server entry point + * + * Version: v2.0.0 + * Developer: Marzavec ( https://github.com/marzavec ) + * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) + * + */ + +'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); diff --git a/server/package-lock.json b/server/package-lock.json new file mode 100644 index 0000000..32a861d --- /dev/null +++ b/server/package-lock.json @@ -0,0 +1,396 @@ +{ + "name": "hack.chat-v2", + "version": "2.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "1.9.1" + } + }, + "async": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz", + "integrity": "sha1-rqdNXmHB+JlhO/ZL2mbUx48v0X0=" + }, + "async-limiter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", + "integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==" + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "requires": { + "core-js": "2.5.3", + "regenerator-runtime": "0.11.1" + } + }, + "balanced-match": { + "version": "1.0.0", + "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", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "requires": { + "balanced-match": "1.0.0", + "concat-map": "0.0.1" + } + }, + "chalk": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.3.2.tgz", + "integrity": "sha512-ZM4j2/ld/YZDc3Ma8PgN7gyAk+kHMMMyzLNryCPGhWrsfAuDVeuid5bpRFTDgMH9JBK2lA4dyyAkkZYF/WcqDQ==", + "requires": { + "ansi-styles": "3.2.1", + "escape-string-regexp": "1.0.5", + "supports-color": "5.3.0" + } + }, + "color-convert": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.1.tgz", + "integrity": "sha512-mjGanIiwQJskCC18rPR6OmrZ6fm2Lc7PeGFYwCmy5J34wC6F1PzdGL6xeMfmgicfYcNLGuVFA3WzXtIDCQSZxQ==", + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + }, + "colors": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.1.2.tgz", + "integrity": "sha1-FopHAXVran9RoSzgyXv6KMCE7WM=" + }, + "common-tags": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/common-tags/-/common-tags-1.7.2.tgz", + "integrity": "sha512-joj9ZlUOjCrwdbmiLqafeUSgkUM74NqhLsZtSqDmhKudaIY197zTrb8JMl31fMnCUuxwFT23eC/oWvrZzDLRJQ==", + "requires": { + "babel-runtime": "6.26.0" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "core-js": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz", + "integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4=" + }, + "cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha1-IegLK+hYD5i0aPN5QwZisEbDStI=" + }, + "dateformat": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-3.0.3.tgz", + "integrity": "sha512-jyCETtSl3VMZMWeRo7iY1FL19ges1t55hMo5yaam4Jrsm5EPL89UQkoQRyiI+Yf4k8r2ZpdngkV8hr1lIdjb3Q==" + }, + "deasync": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/deasync/-/deasync-0.1.12.tgz", + "integrity": "sha512-gpacYo8FBZh3INBp2KOtrQp9kCO5faHvOmEZx3/cZTr3Mm8/kAYs7/Ws3E3OAH0ApBNK6Y6N+7+Dka2Zn2Fldw==", + "requires": { + "bindings": "1.2.1", + "nan": "2.9.2" + } + }, + "deep-equal": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-0.2.2.tgz", + "integrity": "sha1-hLdFiW80xoTpjyzg5Cq69Du6AX0=" + }, + "didyoumean2": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/didyoumean2/-/didyoumean2-1.3.0.tgz", + "integrity": "sha1-bjT0AUM1HJIGlulyO7oB/8C5ZAI=", + "requires": { + "leven": "2.1.0", + "lodash": "4.17.5" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=" + }, + "fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==", + "requires": { + "graceful-fs": "4.1.11", + "jsonfile": "4.0.0", + "universalify": "0.1.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "requires": { + "fs.realpath": "1.0.0", + "inflight": "1.0.6", + "inherits": "2.0.3", + "minimatch": "3.0.4", + "once": "1.4.0", + "path-is-absolute": "1.0.1" + } + }, + "graceful-fs": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", + "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=" + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + }, + "i": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/i/-/i-0.3.6.tgz", + "integrity": "sha1-2WyScyB28HJxG2sQ/X1PZa2O4j0=" + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "requires": { + "once": "1.4.0", + "wrappy": "1.0.2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "requires": { + "graceful-fs": "4.1.11" + } + }, + "leven": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-2.1.0.tgz", + "integrity": "sha1-wuep93IJTe6dNCAq6KzORoeHVYA=" + }, + "lodash": { + "version": "4.17.5", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", + "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==" + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "requires": { + "brace-expansion": "1.1.11" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=" + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "requires": { + "minimist": "0.0.8" + } + }, + "mute-stream": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz", + "integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=" + }, + "nan": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.9.2.tgz", + "integrity": "sha512-ltW65co7f3PQWBDbqVvaU1WtFJUsNW7sWWm4HINhbMQIyVyzIeyZ8toX5TC5eeooE6piZoaEh4cZkueSKG3KYw==" + }, + "ncp": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ncp/-/ncp-1.0.1.tgz", + "integrity": "sha1-0VNn5cuHQyuhF9K/gP30Wuz7QkY=" + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "requires": { + "wrappy": "1.0.2" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" + }, + "pkginfo": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/pkginfo/-/pkginfo-0.4.1.tgz", + "integrity": "sha1-tUGO8EOd5UJfxJlQQtztFPsqhP8=" + }, + "prompt": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/prompt/-/prompt-1.0.0.tgz", + "integrity": "sha1-jlcSPDlquYiJf7Mn/Trtw+c15P4=", + "requires": { + "colors": "1.1.2", + "pkginfo": "0.4.1", + "read": "1.0.7", + "revalidator": "0.1.8", + "utile": "0.3.0", + "winston": "2.1.1" + } + }, + "read": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/read/-/read-1.0.7.tgz", + "integrity": "sha1-s9oZvQUkMal2cdRKQmNK33ELQMQ=", + "requires": { + "mute-stream": "0.0.7" + } + }, + "readdir-recursive": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/readdir-recursive/-/readdir-recursive-0.0.4.tgz", + "integrity": "sha1-mvQ1q6nFi9gNvclIi025up8SMB8=" + }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==" + }, + "revalidator": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/revalidator/-/revalidator-0.1.8.tgz", + "integrity": "sha1-/s5hv6DBtSoga9axgZgYS91SOjs=" + }, + "rimraf": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.2.tgz", + "integrity": "sha512-lreewLK/BlghmxtfH36YYVg1i8IAce4TI7oao75I1g245+6BctqTVQiBP3YUJ9C6DQOXJmkYR9X9fCLtCOJc5w==", + "requires": { + "glob": "7.1.2" + } + }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=" + }, + "supports-color": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.3.0.tgz", + "integrity": "sha512-0aP01LLIskjKs3lq52EC0aGBAJhLq7B2Rd8HC/DR/PtNNpcLilNmHC12O+hu0usQpo7wtHNRqtrhBwtDb0+dNg==", + "requires": { + "has-flag": "3.0.0" + } + }, + "universalify": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.1.tgz", + "integrity": "sha1-+nG63UQ3r0wUiEHjs7Fl+enlkLc=" + }, + "utile": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/utile/-/utile-0.3.0.tgz", + "integrity": "sha1-E1LDQOuCDk2N26A5pPv6oy7U7zo=", + "requires": { + "async": "0.9.2", + "deep-equal": "0.2.2", + "i": "0.3.6", + "mkdirp": "0.5.1", + "ncp": "1.0.1", + "rimraf": "2.6.2" + } + }, + "winston": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/winston/-/winston-2.1.1.tgz", + "integrity": "sha1-PJNJ0ZYgf9G9/51LxD73JRDjoS4=", + "requires": { + "async": "1.0.0", + "colors": "1.0.3", + "cycle": "1.0.3", + "eyes": "0.1.8", + "isstream": "0.1.2", + "pkginfo": "0.3.1", + "stack-trace": "0.0.10" + }, + "dependencies": { + "async": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async/-/async-1.0.0.tgz", + "integrity": "sha1-+PwEyjoTeErenhZBr5hXjPvWR6k=" + }, + "colors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=" + }, + "pkginfo": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/pkginfo/-/pkginfo-0.3.1.tgz", + "integrity": "sha1-Wyn2qB9wcXFC4J52W76rl7T4HiE=" + } + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "ws": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-5.0.0.tgz", + "integrity": "sha512-XXG4S0b771C68AeTHebBsJJBZMguxj7Em+D657RViuj6ppRd3tfuOhIK8eGwZGNb76C8MjQfCTfH2NN50rJN4w==", + "requires": { + "async-limiter": "1.0.0" + } + } + } +} diff --git a/server/package.json b/server/package.json new file mode 100644 index 0000000..db47e43 --- /dev/null +++ b/server/package.json @@ -0,0 +1,29 @@ +{ + "name": "hack.chat-v2", + "version": "2.0.0", + "description": "a minimal distraction free chat application", + "main": "main.js", + "engines": { + "node": ">= 8.10.0", + "npm": ">= 5.7.1" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "config": "node src/scripts/configure.js", + "debug": "node src/scripts/debug.js", + "dev": "node src/scripts/debug.js" + }, + "author": "Marzavec", + "license": "WTFPL", + "dependencies": { + "chalk": "^2.3.2", + "common-tags": "^1.7.2", + "dateformat": "^3.0.3", + "deasync": "^0.1.12", + "didyoumean2": "^1.3.0", + "fs-extra": "^5.0.0", + "prompt": "^1.0.0", + "readdir-recursive": "0.0.4", + "ws": "^5.0.0" + } +} diff --git a/server/src/commands/admin/addmod.js b/server/src/commands/admin/addmod.js new file mode 100644 index 0000000..dba5aba --- /dev/null +++ b/server/src/commands/admin/addmod.js @@ -0,0 +1,47 @@ +/* + +*/ + +'use strict'; + +exports.run = async (core, server, socket, data) => { + if (socket.uType != 'admin') { + // ignore if not admin + return; + } + + let mod = { + trip: data.trip + } + + core.config.mods.push(mod); // purposely not using `config.set()` to avoid auto-save + + for (let client of server.clients) { + if (typeof client.trip !== 'undefined' && client.trip === data.trip) { + client.uType = 'mod'; + + server.reply({ + cmd: 'info', + text: 'You are now a mod.' + }, client); + } + } + + server.reply({ + cmd: 'info', + text: `Added mod trip: ${data.trip}` + }, socket); + + server.broadcast({ + cmd: 'info', + text: `Added mod trip: ${data.trip}` + }, { uType: 'mod' }); +}; + +exports.requiredData = ['trip']; + +exports.info = { + name: 'addmod', + usage: 'addmod {trip}', + description: 'Adds target trip to the config as a mod and upgrades the socket type' +}; diff --git a/server/src/commands/admin/listusers.js b/server/src/commands/admin/listusers.js new file mode 100644 index 0000000..a853518 --- /dev/null +++ b/server/src/commands/admin/listusers.js @@ -0,0 +1,41 @@ +/* + +*/ + +'use strict'; + +exports.run = async (core, server, socket, data) => { + if (socket.uType != 'admin') { + // ignore if not admin + return; + } + + let channels = {}; + for (var client of server.clients) { + if (client.channel) { + if (!channels[client.channel]) { + channels[client.channel] = []; + } + channels[client.channel].push(client.nick); + } + } + + let lines = []; + for (let channel in channels) { + lines.push(`?${channel} ${channels[channel].join(", ")}`); + } + + let text = ''; + text += lines.join("\n"); + + server.reply({ + cmd: 'info', + text: text + }, socket); +}; + +exports.info = { + name: 'listusers', + usage: 'listusers', + description: 'Outputs all current channels and sockets in those channels' +}; diff --git a/server/src/commands/admin/reload.js b/server/src/commands/admin/reload.js new file mode 100644 index 0000000..7aefbcf --- /dev/null +++ b/server/src/commands/admin/reload.js @@ -0,0 +1,34 @@ +/* + +*/ + +'use strict'; + +exports.run = async (core, server, socket, data) => { + if (socket.uType != 'admin') { + // ignore if not admin + return; + } + + let loadResult = core.managers.dynamicImports.reloadDirCache('src/commands'); + loadResult += core.commands.loadCommands(); + + if (loadResult == '') + loadResult = 'Commands reloaded without errors!'; + + server.reply({ + cmd: 'info', + text: loadResult + }, socket); + + server.broadcast({ + cmd: 'info', + text: loadResult + }, { uType: 'mod' }); +}; + +exports.info = { + name: 'reload', + usage: 'reload', + description: '(Re)loads any new commands into memory, outputs errors if any' +}; diff --git a/server/src/commands/admin/saveconfig.js b/server/src/commands/admin/saveconfig.js new file mode 100644 index 0000000..e1a3ebe --- /dev/null +++ b/server/src/commands/admin/saveconfig.js @@ -0,0 +1,34 @@ +/* + +*/ + +'use strict'; + +exports.run = async (core, server, socket, data) => { + if (socket.uType != 'admin') { + // ignore if not admin + return; + } + + let saveResult = core.managers.config.save(); + + if (!saveResult) { + server.reply({ + cmd: 'warn', + text: 'Failed to save config, check logs.' + }, client); + + return; + } + + server.broadcast({ + cmd: 'info', + text: 'Config saved!' + }, { uType: 'mod' }); +}; + +exports.info = { + name: 'saveconfig', + usage: 'saveconfig', + description: 'Saves current config' +}; diff --git a/server/src/commands/admin/shout.js b/server/src/commands/admin/shout.js new file mode 100644 index 0000000..c3cfded --- /dev/null +++ b/server/src/commands/admin/shout.js @@ -0,0 +1,25 @@ +/* + +*/ + +'use strict'; + +exports.run = async (core, server, socket, data) => { + if (socket.uType != 'admin') { + // ignore if not admin + return; + } + + server.broadcast( { + cmd: 'info', + text: `Server Notice: ${data.text}` + }, {}); +}; + +exports.requiredData = ['text']; + +exports.info = { + name: 'shout', + usage: 'shout {text}', + description: 'Displays passed text to every client connected' +}; diff --git a/server/src/commands/core/chat.js b/server/src/commands/core/chat.js new file mode 100644 index 0000000..4fe3b80 --- /dev/null +++ b/server/src/commands/core/chat.js @@ -0,0 +1,56 @@ +/* + +*/ + +'use strict'; + +exports.run = async (core, server, socket, data) => { + // process text + let text = String(data.text); + // strip newlines from beginning and end + text = text.replace(/^\s*\n|^\s+$|\n\s*$/g, ''); + // replace 3+ newlines with just 2 newlines + text = text.replace(/\n{3,}/g, "\n\n"); + if (!text) { + // lets not send empty text? + return; + } + + let score = text.length / 83 / 4; + if (server._police.frisk(socket.remoteAddress, score)) { + server.reply({ + cmd: 'warn', + text: 'You are sending too much text. Wait a moment and try again.\nPress the up arrow key to restore your last message.' + }, socket); + + return; + } + + let payload = { + cmd: 'chat', + nick: socket.nick, + text: text + }; + + if (socket.uType == 'admin') { + payload.admin = true; + } else if (socket.uType == 'mod') { + payload.mod = true; + } + + if (socket.trip) { + payload.trip = socket.trip; + } + + server.broadcast( payload, { channel: socket.channel }); + + core.managers.stats.increment('messages-sent'); +}; + +exports.requiredData = ['text']; + +exports.info = { + name: 'chat', + usage: 'chat {text}', + description: 'Broadcasts passed `text` field to the calling users channel' +}; diff --git a/server/src/commands/core/help.js b/server/src/commands/core/help.js new file mode 100644 index 0000000..17478d0 --- /dev/null +++ b/server/src/commands/core/help.js @@ -0,0 +1,33 @@ +/* + +*/ + +'use strict'; + +exports.run = async (core, server, socket, data) => { + let reply = `Help usage: { cmd: 'help', type: 'categories'} or { cmd: 'help', type: 'commandname'}`; + + if (typeof data.type === 'undefined') { + // + } else { + if (data.type == 'categories') { + let categories = core.commands.categories(); + // TODO: bad output, fix this + reply = `Command Categories:\n${categories}`; + } else { + // TODO: finish this module later + } + } + + server.reply({ + cmd: 'info', + text: reply + }, socket); +}; + +// optional parameters are marked, all others are required +exports.info = { + name: 'help', // actual command name + usage: 'help ([type:categories] | [type:command])', + description: 'Outputs information about the servers current protocol' +}; diff --git a/server/src/commands/core/invite.js b/server/src/commands/core/invite.js new file mode 100644 index 0000000..1c70ac1 --- /dev/null +++ b/server/src/commands/core/invite.js @@ -0,0 +1,64 @@ +/* + +*/ + +'use strict'; + +function verifyNickname(nick) { + return /^[a-zA-Z0-9_]{1,24}$/.test(nick); +} + +exports.run = async (core, server, socket, data) => { + let targetNick = String(data.nick); + + if (!verifyNickname(targetNick)) { + // Not a valid nickname? Chances are we won't find them + return; + } + + if (targetNick == socket.nick) { + // TODO: reply with something witty? They invited themself + return; + } + + if (server._police.frisk(socket.remoteAddress, 2)) { + server.reply({ + cmd: 'warn', + text: 'You are sending invites too fast. Wait a moment before trying again.' + }, socket); + + return; + } + + let channel = Math.random().toString(36).substr(2, 8); + + let payload = { + cmd: 'info', + text: `${socket.nick} invited you to ?${channel}` + }; + let inviteSent = server.broadcast( payload, { channel: socket.channel, nick: targetNick }); + + if (!inviteSent) { + server.reply({ + cmd: 'warn', + text: 'Could not find user in channel' + }, socket); + + return; + } + + server.reply({ + cmd: 'info', + text: `You invited ${targetNick} to ?${channel}` + }, socket); + + core.managers.stats.increment('invites-sent'); +}; + +exports.requiredData = ['nick']; + +exports.info = { + name: 'invite', + usage: 'invite {nick}', + description: 'Generates a unique (more or less) room name and passes it to two clients' +}; diff --git a/server/src/commands/core/join.js b/server/src/commands/core/join.js new file mode 100644 index 0000000..6a65851 --- /dev/null +++ b/server/src/commands/core/join.js @@ -0,0 +1,128 @@ +/* + +*/ + +'use strict'; + +const crypto = require('crypto'); + +function hash(password) { + var sha = crypto.createHash('sha256'); + sha.update(password); + return sha.digest('base64').substr(0, 6); +} + +function verifyNickname(nick) { + return /^[a-zA-Z0-9_]{1,24}$/.test(nick); +} + +exports.run = async (core, server, socket, data) => { + if (server._police.frisk(socket.remoteAddress, 3)) { + server.reply({ + cmd: 'warn', + text: 'You are joining channels too fast. Wait a moment and try again.' + }, socket); + + return; + } + + if (typeof socket.channel !== 'undefined') { + // Calling socket already in a channel + // TODO: allow changing of channel without reconnection + return; + } + + let channel = String(data.channel).trim(); + if (!channel) { + // Must join a non-blank channel + return; + } + + // Process nickname + let nick = String(data.nick); + let nickArray = nick.split('#', 2); + nick = nickArray[0].trim(); + + if (!verifyNickname(nick)) { + server.reply({ + cmd: 'warn', + text: 'Nickname must consist of up to 24 letters, numbers, and underscores' + }, socket); + + return + } + + for (let client of server.clients) { + if (client.channel === channel) { + if (client.nick.toLowerCase() === nick.toLowerCase()) { + server.reply({ + cmd: 'warn', + text: 'Nickname taken' + }, socket); + + return; + } + } + } + + // TODO: Should we check for mod status first to prevent overwriting of admin status somehow? Meh, w/e, cba. + let uType = 'user'; + let trip = null; + let password = nickArray[1]; + if (nick.toLowerCase() == core.config.adminName.toLowerCase()) { + if (password != core.config.adminPass) { + server.reply({ + cmd: 'warn', + text: 'Gtfo' + }, socket); + + return; + } else { + uType = 'admin'; + trip = hash(password + core.config.tripSalt); + } + } else if (password) { + trip = hash(password + core.config.tripSalt); + } + + // TODO: Disallow moderator impersonation + for (let mod of core.config.mods) { + if (trip === mod.trip) + uType = 'mod'; + } + + // Announce the new user + server.broadcast({ + cmd: 'onlineAdd', + nick: nick, + trip: trip || 'null' + }, { channel: channel }); + + socket.uType = uType; + socket.nick = nick; + socket.channel = channel; + if (trip !== null) socket.trip = trip; + + // Reply with online user list + let nicks = []; + for (let client of server.clients) { + if (client.channel === channel) { + nicks.push(client.nick); + } + } + + server.reply({ + cmd: 'onlineSet', + nicks: nicks + }, socket); + + core.managers.stats.increment('users-joined'); +}; + +exports.requiredData = ['channel', 'nick']; + +exports.info = { + name: 'join', + usage: 'join {channel} {nick}', + description: 'Place calling socket into target channel with target nick & broadcast event to channel' +}; diff --git a/server/src/commands/core/showcase.js b/server/src/commands/core/showcase.js new file mode 100644 index 0000000..aaa474c --- /dev/null +++ b/server/src/commands/core/showcase.js @@ -0,0 +1,46 @@ +/* + +*/ + +'use strict'; + +// you can require() modules here + +// this function will only be only in the scope of the module +const createReply = (echoInput) => { + if (echoInput.length > 100) + echoInput = 'HOW ABOUT NO?'; + + return `You want me to echo: ${echoInput}?` +}; + +// `exports.run()` is required and will always be passed (core, server, socket, data) +// be sure it's asyn too +exports.run = async (core, server, socket, data) => { + + server.reply({ + cmd: 'info', + text: `SHOWCASE MODULE: ${core.showcase} - ${this.createReply(data.echo)}` + }, socket); + +}; + +// `exports.init()` is optional, and will only be run when the module is loaded into memory +// it will always be passed a reference to the global core class +// note: this will fire again if a reload is issued, keep that in mind +exports.init = (core) => { + if (typeof core.showcase === 'undefined') { + core.showcase = 'init is a handy place to put global data by assigning it to `core`'; + } +} + +// optional, if `data.echo` is missing `exports.run()` will never be called & the user will be alerted +exports.requiredData = ['echo']; + +// optional parameters are marked, all others are required +exports.info = { + name: 'showcase', // actual command name + aliases: ['templateModule'], // optional, an array of other names this module can be executed by + usage: 'showcase {echo}', // used for help output + description: 'Simple command module template & info' // used for help output +}; diff --git a/server/src/commands/core/stats.js b/server/src/commands/core/stats.js new file mode 100644 index 0000000..841675f --- /dev/null +++ b/server/src/commands/core/stats.js @@ -0,0 +1,55 @@ +/* + +*/ + +'use strict'; + +const stripIndents = require('common-tags').stripIndents; + +const formatTime = (time) => { + let seconds = time[0] + time[1] / 1e9; + + let minutes = Math.floor(seconds / 60); + seconds = seconds % 60; + + let hours = Math.floor(minutes / 60); + minutes = minutes % 60; + return `${hours.toFixed(0)}h ${minutes.toFixed(0)}m ${seconds.toFixed(0)}s`; +}; + +exports.run = async (core, server, socket, data) => { + let ips = {}; + let channels = {}; + for (let client of server.clients) { + if (client.channel) { + channels[client.channel] = true; + ips[client.remoteAddress] = true; + } + } + + let uniqueClientCount = Object.keys(ips).length; + let uniqueChannels = Object.keys(channels).length; + + ips = null; + channels = null; + + server.reply({ + 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)} + stats-requested: ${(core.managers.stats.get('stats-requested') || 0)} + server-uptime: ${formatTime(process.hrtime(core.managers.stats.get('start-time')))}` + }, socket); + + core.managers.stats.increment('stats-requested'); +}; + +exports.info = { + name: 'stats', + usage: 'stats', + description: 'Sends back current server stats to the calling client' +}; diff --git a/server/src/commands/mod/ban.js b/server/src/commands/mod/ban.js new file mode 100644 index 0000000..fde1ad8 --- /dev/null +++ b/server/src/commands/mod/ban.js @@ -0,0 +1,61 @@ +/* + +*/ + +'use strict'; + +exports.run = async (core, server, socket, data) => { + if (socket.uType == 'user') { + // ignore if not mod or admin + return; + } + + let targetNick = String(data.nick); + let badClient = null; + for (let client of server.clients) { + // Find badClient's socket + if (client.channel == socket.channel && client.nick == targetNick) { + badClient = client; + break; + } + } + + if (!badClient) { + server.reply({ + cmd: 'warn', + text: 'Could not find user in channel' + }, socket); + + return; + } + + if (badClient.uType !== 'user') { + server.reply({ + cmd: 'warn', + text: 'Cannot ban other mods, how rude' + }, socket); + + return; + } + + // TODO: ratelimiting here + // TODO: add reference to banned users nick or unban by nick cmd + //POLICE.arrest(getAddress(badClient)) + // TODO: add event to log? + console.log(`${socket.nick} [${socket.trip}] banned ${targetNick} in ${socket.channel}`); + server.broadcast({ + cmd: 'info', + text: `Banned ${targetNick}` + }, { channel: socket.channel }); + badClient.close(); + + core.managers.stats.increment('users-banned'); +}; + +exports.requiredData = ['nick']; + +exports.info = { + name: 'ban', + usage: 'ban {nick}', + description: 'Disconnects the target nickname in the same channel as calling socket & adds to ratelimiter' +}; diff --git a/server/src/commands/mod/kick.js b/server/src/commands/mod/kick.js new file mode 100644 index 0000000..5cd524d --- /dev/null +++ b/server/src/commands/mod/kick.js @@ -0,0 +1,74 @@ +/* + +*/ + +'use strict'; + +exports.run = async (core, server, socket, data) => { + if (socket.uType == 'user') { + // ignore if not mod or admin + return; + } + + let targetNick = String(data.nick); + let badClient = null; + for (let client of server.clients) { + // Find badClient's socket + if (client.channel == socket.channel && client.nick == targetNick) { + badClient = client; + break; + } + } + + if (!badClient) { + server.reply({ + cmd: 'warn', + text: 'Could not find user in channel' + }, socket); + + return; + } + + if (badClient.uType !== 'user') { + server.reply({ + cmd: 'warn', + text: 'Cannot kick other mods, how rude' + }, socket); + + return; + } + + // TODO: add event to log? + let newChannel = Math.random().toString(36).substr(2, 8); + badClient.channel = newChannel; + + console.log(`${socket.nick} [${socket.trip}] kicked ${targetNick} in ${socket.channel}`); + + // remove socket from same-channel client + server.broadcast({ + cmd: 'onlineRemove', + nick: targetNick + }, { channel: socket.channel }); + + // publicly broadcast event (TODO: should this be supressed?) + server.broadcast({ + cmd: 'info', + text: `Kicked ${targetNick}` + }, { channel: socket.channel }); + + // inform mods with where they were sent + server.broadcast({ + cmd: 'info', + text: `${targetNick} was banished to ?${newChannel}` + }, { channel: socket.channel, uType: 'mod' }); + + core.managers.stats.increment('users-banned'); +}; + +exports.requiredData = ['nick']; + +exports.info = { + name: 'kick', + usage: 'kick {nick}', + description: 'Forces target client into another channel without announcing change' +}; diff --git a/server/src/commands/mod/unban.js b/server/src/commands/mod/unban.js new file mode 100644 index 0000000..cc1016a --- /dev/null +++ b/server/src/commands/mod/unban.js @@ -0,0 +1,34 @@ +/* + +*/ + +'use strict'; + +exports.run = async (core, server, socket, data) => { + if (socket.uType == 'user') { + // ignore if not mod or admin + return; + } + + let ip = String(data.ip); + let nick = String(data.nick); // for future upgrade + + // TODO: remove ip from ratelimiter + // POLICE.pardon(ip) + console.log(`${socket.nick} [${socket.trip}] unbanned ${/*nick || */ip} in ${socket.channel}`); + + server.reply({ + cmd: 'info', + text: `Unbanned ${/*nick || */ip}` + }, socket); + + core.managers.stats.decrement('users-banned'); +}; + +exports.requiredData = ['ip']; + +exports.info = { + name: 'unban', + usage: 'unban {ip}', + description: 'Removes target ip from the ratelimiter' +}; diff --git a/server/src/core/rateLimiter.js b/server/src/core/rateLimiter.js new file mode 100644 index 0000000..0f45239 --- /dev/null +++ b/server/src/core/rateLimiter.js @@ -0,0 +1,104 @@ +/** + * 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/ ) + * + */ + +'use strict'; + +class Police { + /** + * Create a ratelimiter instance. + */ + constructor () { + this._records = {}; + this._halflife = 30000; // ms + this._threshold = 25; + } + + /** + * 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) { + var record = this.search(id); + + if (record) { + record.arrested = true; + } + } + + /** + * Remove statically assigned limit from `id` + * + * @param {String} id target id / address + * @public + * + * @memberof Police + */ + pardon (id) { + var record = this.search(id); + + if (record) { + record.arrested = false; + } + } +} + +module.exports = Police; diff --git a/server/src/core/server.js b/server/src/core/server.js new file mode 100644 index 0000000..c16aec8 --- /dev/null +++ b/server/src/core/server.js @@ -0,0 +1,197 @@ +/** + * 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/ ) + * + */ + +'use strict'; + +const wsServer = require('ws').Server; +const Police = require('./rateLimiter'); + +class server extends wsServer { + /** + * Create a HackChat server instance. + * + * @param {Object} core Reference to the core server object + */ + constructor (core) { + super({ port: core.config.websocketPort }); + + this._core = core; + this._police = new Police(); + this._cmdBlacklist = {}; + + this.on('error', (err) => { + this.handleError('server', err); + }); + + this.on('connection', (socket, request) => { + this.newConnection(socket, request); + }); + } + + /** + * 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); + }).bind(this)); + + socket.on('close', (() => { + this.handleClose(socket); + }).bind(this)); + + socket.on('error', ((err) => { + this.handleError(socket, err); + }).bind(this)); + } + + /** + * 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) { + // TODO: Rate limit here + // Don't penalize yet, but check whether IP is rate-limited + if (this._police.frisk(socket.remoteAddress, 0)) { + this.reply({ cmd: 'warn', text: "Your IP is being rate-limited or blocked." }, socket); + + 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; + } + + var args = null; + try { + args = JSON.parse(data); + } catch (e) { + // Client sent malformed json, gtfo + socket.close(); + } + + if (args === null) + return; + + if (typeof args.cmd === 'undefined' || args.cmd == 'ping') + return; + + var cmd = args.cmd; + + if (typeof socket.channel === 'undefined' && cmd !== 'join') + return; + + if (typeof this._cmdBlacklist[cmd] === 'function') { + return; + } + + this._core.commands.handleCommand(this, socket, args); + } + + /** + * Handle socket close from clients + * + * @param {Object} socket Closing socket object + */ + handleClose (socket) { + try { + if (socket.channel) { + this.broadcast({ + cmd: 'onlineRemove', + nick: socket.nick + }, { channel: socket.channel }); + } + } catch (e) { + // TODO: Should this be added to the error log? + } + } + + /** + * "Handle" server or socket errors + * + * @param {Object||String} socket Calling socket object, or 'server' + * @param {String} err The sad stuff + */ + handleError (socket, err) { + // Meh, yolo + // I mean; + // TODO: Should this be added to the error log? + } + + /** + * Send data payload to specific socket/client + * + * @param {Object} data Object to convert to json for transmission + * @param {Object} socket The target client + */ + send (data, socket) { + // Add timestamp to command + data.time = Date.now(); + + try { + if (socket.readyState == 1) { // Who says statically checking port status is bad practice? Everyone? Damnit. #TODO + socket.send(JSON.stringify(data)); + } + } catch (e) { } + } + + /** + * Overload function for `this.send()` + * + * @param {Object} data Object to convert to json for transmission + * @param {Object} socket The target client + */ + reply (data, socket) { + this.send(data, socket); + } + + /** + * Finds sockets/clients that meet the filter requirements, then passes the data to them + * + * @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') + */ + broadcast (data, filter) { + let filterAttribs = Object.keys(filter); + let reqCount = filterAttribs.length; + let curMatch; + let sent = false; + for ( let socket of this.clients ) { + curMatch = 0; + + for( let i = 0; i < reqCount; i++ ) { + if (typeof socket[filterAttribs[i]] !== 'undefined' && socket[filterAttribs[i]] === filter[filterAttribs[i]]) + curMatch++; + } + + if (curMatch === reqCount) { + this.send(data, socket); + sent = true; + } + } + + return sent; + } +} + +module.exports = server; diff --git a/server/src/managers/commands.js b/server/src/managers/commands.js new file mode 100644 index 0000000..95d0f1b --- /dev/null +++ b/server/src/managers/commands.js @@ -0,0 +1,244 @@ +/** + * 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/ ) + * + */ + +'use strict'; + +const path = require('path'); +const chalk = require('chalk'); +const didYouMean = require('didyoumean2'); + +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) { + // TODO: Add to logger? + let errText = `Failed to load '${name}': ${error}\n\n`; + 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) { + // TODO: Add to logger? + let errText = `Failed to initialize '${name}': ${err}\n\n`; + 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 reference to the newly loaded object + */ + 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); + } + + /** + * 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 server.reply({ + cmd: 'warn', + text: `Command not found, did you mean: \`${maybe}\`?` + }, socket); + } + + // 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) { + let errText = `Failed to execute '${command.info.name}': missing required ${missing.join(', ')}\n\n`; + + server.reply({ + cmd: 'warn', + text: errText + }, socket); + + return null; + } + } + + try { + return await command.run(this.core, server, socket, data); + } catch (err) { + // TODO: Add to logger? + let errText = `Failed to execute '${command.info.name}': ${err}\n\n`; + console.log(errText); + + server.reply({ + cmd: 'warn', + text: errText + }, socket); + + return null; + } + } +} + +module.exports = CommandManager; diff --git a/server/src/managers/config.js b/server/src/managers/config.js new file mode 100644 index 0000000..2ff4a88 --- /dev/null +++ b/server/src/managers/config.js @@ -0,0 +1,228 @@ +/** + * 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/ ) + * + */ + +'use strict'; + +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'); + +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) { + // core server setup questions + const questions = { + properties: { + 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, '') + }, + adminPass: { + type: 'string', + required: !currentConfig.adminPass, + default: currentConfig.adminPass, + hidden: true, + replace: '*', + }, + websocketPort: { + type: 'number', + required: !currentConfig.websocketPort, + default: currentConfig.websocketPort || 6060 + }, + tripSalt: { + type: 'string', + required: !currentConfig.tripSalt, + default: currentConfig.tripSalt, + hidden: true, + replace: '*', + } + } + }; + + // 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(); + + // trip salt is the last core config question, wait until it's been populated + // TODO: update this to work with new plugin support + while(conf === null || typeof conf.tripSalt === '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 HackChat wiki at: + ${chalk.green('https://github.com/')} + + ${chalk.white('Note:')} ${chalk.green('npm/yarn run config')} will re-run this utility. + + You will now be asked for the following: + - ${chalk.magenta('Admin Name')}, the initial admin username + - ${chalk.magenta('Admin Pass')}, the initial admin password + - ${chalk.magenta(' Port')}, the port for the websocket + - ${chalk.magenta(' Salt')}, the salt for username trip + \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 (e) { + // TODO: restore backup + // TODO: output to logging engine? + console.log('Failed to save config file!'); + + 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 new file mode 100644 index 0000000..f4096b7 --- /dev/null +++ b/server/src/managers/imports-manager.js @@ -0,0 +1,150 @@ +/** + * 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/ ) + * + */ + +'use strict'; + +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 new file mode 100644 index 0000000..2fac8fb --- /dev/null +++ b/server/src/managers/index.js @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000..c3b6f9f --- /dev/null +++ b/server/src/managers/stats.js @@ -0,0 +1,61 @@ +/** + * 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/ ) + * + */ + +'use strict'; + +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/configure.js b/server/src/scripts/configure.js new file mode 100644 index 0000000..0ecd858 --- /dev/null +++ b/server/src/scripts/configure.js @@ -0,0 +1,23 @@ +/** + * Server configuration script, used reconfiguring server options + * + * Version: v2.0.0 + * Developer: Marzavec ( https://github.com/marzavec ) + * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) + * + */ + +'use strict'; + +// import required classes +const path = require('path'); +const ImportsManager = require('../managers/imports-manager'); +const ConfigManager = require('../managers/config'); + +// import and initialize configManager & dependencies +const importManager = new ImportsManager(null, path.join(__dirname, '../..')); +importManager.init(); +const configManager = new ConfigManager(null, path.join(__dirname, '../..'), importManager); + +// execute config load with `reconfiguring` flag set to true +configManager.load(true); diff --git a/server/src/scripts/debug.js b/server/src/scripts/debug.js new file mode 100644 index 0000000..3a97d9f --- /dev/null +++ b/server/src/scripts/debug.js @@ -0,0 +1,18 @@ +/** + * Server debug test script + * + * Version: v2.0.0 + * Developer: Marzavec ( https://github.com/marzavec ) + * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) + * + */ + +'use strict'; + +// import required classes +const path = require('path'); +const ConfigManager = require('../managers/config'); + +// begin tests +// TODO: TODO +// TODO diff --git a/server/src/scripts/dev.js b/server/src/scripts/dev.js new file mode 100644 index 0000000..5049b84 --- /dev/null +++ b/server/src/scripts/dev.js @@ -0,0 +1,17 @@ +/** + * Server development script + * + * Version: v2.0.0 + * Developer: Marzavec ( https://github.com/marzavec ) + * License: WTFPL ( http://www.wtfpl.net/txt/copying/ ) + * + */ + +'use strict'; + +// import required classes + + +// begin tests +// TODO: TODO +// TODO |