aboutsummaryrefslogtreecommitdiffstats
path: root/server/src
diff options
context:
space:
mode:
Diffstat (limited to 'server/src')
-rw-r--r--server/src/commands/admin/addmod.js47
-rw-r--r--server/src/commands/admin/listusers.js38
-rw-r--r--server/src/commands/admin/reload.js35
-rw-r--r--server/src/commands/admin/saveconfig.js36
-rw-r--r--server/src/commands/admin/shout.js23
-rw-r--r--server/src/commands/core/changenick.js88
-rw-r--r--server/src/commands/core/chat.js62
-rw-r--r--server/src/commands/core/disconnect.js21
-rw-r--r--server/src/commands/core/help.js49
-rw-r--r--server/src/commands/core/invite.js65
-rw-r--r--server/src/commands/core/join.js135
-rw-r--r--server/src/commands/core/morestats.js53
-rw-r--r--server/src/commands/core/move.js83
-rw-r--r--server/src/commands/core/stats.js32
-rw-r--r--server/src/commands/mod/ban.js64
-rw-r--r--server/src/commands/mod/kick.js78
-rw-r--r--server/src/commands/mod/unban.js55
-rw-r--r--server/src/core/rateLimiter.js103
-rw-r--r--server/src/core/server.js282
-rw-r--r--server/src/managers/commands.js239
-rw-r--r--server/src/managers/config.js224
-rw-r--r--server/src/managers/imports-manager.js148
-rw-r--r--server/src/managers/index.js6
-rw-r--r--server/src/managers/stats.js59
-rw-r--r--server/src/scripts/configure.js23
-rw-r--r--server/src/scripts/debug.js18
-rw-r--r--server/src/scripts/dev.js17
27 files changed, 2083 insertions, 0 deletions
diff --git a/server/src/commands/admin/addmod.js b/server/src/commands/admin/addmod.js
new file mode 100644
index 0000000..4c13b22
--- /dev/null
+++ b/server/src/commands/admin/addmod.js
@@ -0,0 +1,47 @@
+/*
+ Description: Adds the target trip to the mod list then elevates the uType
+*/
+
+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
+
+ let newMod = server.findSockets({ trip: data.trip });
+
+ if (newMod.length !== 0) {
+ for (let i = 0, l = newMod.length; i < l; i++) {
+ newMod[i].uType = 'mod';
+
+ server.send({
+ cmd: 'info',
+ text: 'You are now a mod.'
+ }, newMod[i]);
+ }
+ }
+
+ 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..a539a3c
--- /dev/null
+++ b/server/src/commands/admin/listusers.js
@@ -0,0 +1,38 @@
+/*
+ Description: Outputs all current channels and their user nicks
+*/
+
+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',
+ 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..e2cfbe6
--- /dev/null
+++ b/server/src/commands/admin/reload.js
@@ -0,0 +1,35 @@
+/*
+ Description: Clears and resets the command modules, outputting any errors
+*/
+
+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 = `Loaded ${core.commands._commands.length} commands, 0 errors`;
+ } else {
+ loadResult = `Loaded ${core.commands._commands.length} commands, error(s): ${loadResult}`;
+ }
+
+ server.reply({
+ cmd: 'info',
+ text: loadResult
+ }, socket);
+
+ server.broadcast({
+ cmd: 'info',
+ text: loadResult
+ }, { uType: 'mod' });
+};
+
+exports.info = {
+ name: '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..ed3a312
--- /dev/null
+++ b/server/src/commands/admin/saveconfig.js
@@ -0,0 +1,36 @@
+/*
+ Description: Writes any changes to the config to the disk
+*/
+
+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.reply({
+ cmd: 'info',
+ text: 'Config saved!'
+ }, socket);
+
+ server.broadcast({
+ cmd: 'info',
+ text: 'Config saved!'
+ }, { uType: 'mod' });
+};
+
+exports.info = {
+ name: '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..1358dd9
--- /dev/null
+++ b/server/src/commands/admin/shout.js
@@ -0,0 +1,23 @@
+/*
+ Description: Emmits a server-wide message as `info`
+*/
+
+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'
+}; \ No newline at end of file
diff --git a/server/src/commands/core/changenick.js b/server/src/commands/core/changenick.js
new file mode 100644
index 0000000..4041bb0
--- /dev/null
+++ b/server/src/commands/core/changenick.js
@@ -0,0 +1,88 @@
+/*
+ Description: Generates a semi-unique channel name then broadcasts it to each client
+*/
+
+const verifyNickname = (nick) => {
+ return /^[a-zA-Z0-9_]{1,24}$/.test(nick);
+};
+
+exports.run = async (core, server, socket, data) => {
+ if (server._police.frisk(socket.remoteAddress, 6)) {
+ server.reply({
+ cmd: 'warn',
+ text: 'You are changing nicknames too fast. Wait a moment before trying again.'
+ }, socket);
+
+ return;
+ }
+
+ if (typeof data.nick !== 'string') {
+ return;
+ }
+
+ let newNick = data.nick.trim();
+
+ if (!verifyNickname(newNick)) {
+ server.reply({
+ cmd: 'warn',
+ text: 'Nickname must consist of up to 24 letters, numbers, and underscores'
+ }, socket);
+
+ return;
+ }
+
+ if (newNick.toLowerCase() == core.config.adminName.toLowerCase()) {
+ server._police.frisk(socket.remoteAddress, 4);
+
+ server.reply({
+ cmd: 'warn',
+ text: 'Gtfo'
+ }, socket);
+
+ return;
+ }
+
+ let userExists = server.findSockets({
+ channel: socket.channel,
+ nick: (targetNick) => targetNick.toLowerCase() === newNick.toLowerCase()
+ });
+
+ if (userExists.length > 0) {
+ // That nickname is already in that channel
+ server.reply({
+ cmd: 'warn',
+ text: 'Nickname taken'
+ }, socket);
+
+ return;
+ }
+
+ let peerList = server.findSockets({ channel: socket.channel });
+ let leaveNotice = {
+ cmd: 'onlineRemove',
+ nick: socket.nick
+ };
+ let joinNotice = {
+ cmd: 'onlineAdd',
+ nick: newNick,
+ trip: socket.trip || 'null',
+ hash: server.getSocketHash(socket)
+ };
+
+ server.broadcast( leaveNotice, { channel: socket.channel });
+ server.broadcast( joinNotice, { channel: socket.channel });
+ server.broadcast( {
+ cmd: 'info',
+ text: `${socket.nick} is now ${newNick}`
+ }, { channel: socket.channel });
+
+ socket.nick = newNick;
+};
+
+exports.requiredData = ['nick'];
+
+exports.info = {
+ name: 'changenick',
+ usage: 'changenick {nick}',
+ description: 'This will change your current connections nickname'
+};
diff --git a/server/src/commands/core/chat.js b/server/src/commands/core/chat.js
new file mode 100644
index 0000000..bce6adb
--- /dev/null
+++ b/server/src/commands/core/chat.js
@@ -0,0 +1,62 @@
+/*
+ Description: Rebroadcasts any `text` to all clients in a `channel`
+*/
+
+const parseText = (text) => {
+ if (typeof text !== 'string') {
+ return false;
+ }
+
+ // 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");
+
+ return text;
+};
+
+exports.run = async (core, server, socket, data) => {
+ let text = parseText(data.text);
+ if (!text) {
+ // lets not send objects or empty text, yea?
+ 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'
+}; \ No newline at end of file
diff --git a/server/src/commands/core/disconnect.js b/server/src/commands/core/disconnect.js
new file mode 100644
index 0000000..9b54214
--- /dev/null
+++ b/server/src/commands/core/disconnect.js
@@ -0,0 +1,21 @@
+/*
+ Description: This module will be directly called by the server event handler
+ when a socket connection is closed or lost. It can calso be called
+ by a client to have the connection severed.
+*/
+
+exports.run = async (core, server, socket, data) => {
+ if (socket.channel) {
+ server.broadcast({
+ cmd: 'onlineRemove',
+ nick: socket.nick
+ }, { channel: socket.channel });
+ }
+
+ socket.terminate();
+};
+
+exports.info = {
+ name: 'disconnect',
+ description: 'Event handler or force disconnect (if your into that kind of thing)'
+}; \ No newline at end of file
diff --git a/server/src/commands/core/help.js b/server/src/commands/core/help.js
new file mode 100644
index 0000000..7f63d3d
--- /dev/null
+++ b/server/src/commands/core/help.js
@@ -0,0 +1,49 @@
+/*
+ Description: Outputs the current command module list or command categories
+*/
+
+const stripIndents = require('common-tags').stripIndents;
+
+exports.run = async (core, server, socket, data) => {
+ // verify passed arguments
+ let typeDt = typeof data.type;
+ let catDt = typeof data.category;
+ let cmdDt = typeof data.command;
+ if (typeDt !== 'undefined' && typeDt !== 'string' ) {
+ return;
+ } else if (catDt !== 'undefined' && catDt !== 'string' ) {
+ return;
+ } else if (cmdDt !== 'undefined' && cmdDt !== 'string' ) {
+ return;
+ }
+
+ // set default reply
+ let reply = stripIndents`Help usage:
+ Show all categories -> { cmd: 'help', type: 'categories' }
+ Show all commands in category -> { cmd: 'help', category: '<category name>' }
+ Show specific command -> { cmd: 'help', command: '<command name>' }`;
+
+ if (typeDt !== 'undefined') {
+ let categories = core.commands.categories().sort();
+ reply = `Command Categories:\n${categories.map(c => `- ${c.replace('../src/commands/', '')}`).join('\n')}`;
+ } else if (catDt !== 'undefined') {
+ let catCommands = core.commands.all('../src/commands/' + data.category).sort((a, b) => a.info.name.localeCompare(b.info.name));
+ reply = `${data.category} commands:\n${catCommands.map(c => `- ${c.info.name}`).join('\n')}`;
+ } else if (cmdDt !== 'undefined') {
+ let command = core.commands.get(data.command);
+ reply = stripIndents`
+ Usage: ${command.info.usage || command.info.name}
+ Description: ${command.info.description || '¯\_(ツ)_/¯'}`;
+ }
+
+ server.reply({
+ cmd: 'info',
+ text: reply
+ }, socket);
+};
+
+exports.info = {
+ name: 'help',
+ usage: 'help ([ type:categories] | [category:<category name> | command:<command name> ])',
+ description: 'Outputs information about the servers current protocol'
+}; \ No newline at end of file
diff --git a/server/src/commands/core/invite.js b/server/src/commands/core/invite.js
new file mode 100644
index 0000000..bcf9097
--- /dev/null
+++ b/server/src/commands/core/invite.js
@@ -0,0 +1,65 @@
+/*
+ Description: Generates a semi-unique channel name then broadcasts it to each client
+*/
+
+const verifyNickname = (nick) => {
+ return /^[a-zA-Z0-9_]{1,24}$/.test(nick);
+};
+
+exports.run = async (core, server, socket, data) => {
+ 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;
+ }
+
+ if (typeof data.nick !== 'string') {
+ return;
+ }
+
+ if (!verifyNickname(data.nick)) {
+ // Not a valid nickname? Chances are we won't find them
+ return;
+ }
+
+ if (data.nick == socket.nick) {
+ // They invited themself
+ return;
+ }
+
+ let channel = Math.random().toString(36).substr(2, 8);
+
+ let payload = {
+ cmd: 'info',
+ invite: channel,
+ text: `${socket.nick} invited you to ?${channel}`
+ };
+ let inviteSent = server.broadcast( payload, { channel: socket.channel, nick: data.nick });
+
+ if (!inviteSent) {
+ server.reply({
+ cmd: 'warn',
+ text: 'Could not find user in channel'
+ }, socket);
+
+ return;
+ }
+
+ server.reply({
+ cmd: 'info',
+ text: `You invited ${data.nick} 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'
+}; \ No newline at end of file
diff --git a/server/src/commands/core/join.js b/server/src/commands/core/join.js
new file mode 100644
index 0000000..f2b2c9d
--- /dev/null
+++ b/server/src/commands/core/join.js
@@ -0,0 +1,135 @@
+/*
+ Description: Initial entry point, applies `channel` and `nick` to the calling socket
+*/
+
+const crypto = require('crypto');
+
+const hash = (password) => {
+ let sha = crypto.createHash('sha256');
+ sha.update(password);
+ return sha.digest('base64').substr(0, 6);
+};
+
+const 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
+ return;
+ }
+
+ if (typeof data.channel !== 'string' || typeof data.nick !== 'string') {
+ return;
+ }
+
+ let channel = data.channel.trim();
+ if (!channel) {
+ // Must join a non-blank channel
+ return;
+ }
+
+ // Process nickname
+ let nick = 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;
+ }
+
+ let userExists = server.findSockets({
+ channel: data.channel,
+ nick: (targetNick) => targetNick.toLowerCase() === nick.toLowerCase()
+ });
+
+ if (userExists.length > 0) {
+ // That nickname is already in that channel
+ 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._police.frisk(socket.remoteAddress, 4);
+
+ server.reply({
+ cmd: 'warn',
+ text: 'Gtfo'
+ }, socket);
+
+ return;
+ } else {
+ uType = 'admin';
+ trip = 'Admin';
+ }
+ } 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';
+ }
+ }
+
+ // Reply with online user list
+ let newPeerList = server.findSockets({ channel: data.channel });
+ let joinAnnouncement = {
+ cmd: 'onlineAdd',
+ nick: nick,
+ trip: trip || 'null',
+ hash: server.getSocketHash(socket)
+ };
+ let nicks = [];
+
+ for (let i = 0, l = newPeerList.length; i < l; i++) {
+ server.reply(joinAnnouncement, newPeerList[i]);
+ nicks.push(newPeerList[i].nick);
+ }
+
+ socket.uType = uType;
+ socket.nick = nick;
+ socket.channel = channel;
+ if (trip !== null) socket.trip = trip;
+ nicks.push(socket.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'
+}; \ No newline at end of file
diff --git a/server/src/commands/core/morestats.js b/server/src/commands/core/morestats.js
new file mode 100644
index 0000000..5510cb1
--- /dev/null
+++ b/server/src/commands/core/morestats.js
@@ -0,0 +1,53 @@
+/*
+ Description: Outputs more info than the legacy stats command
+*/
+
+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)}
+ 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')))}`
+ }, socket);
+
+ core.managers.stats.increment('stats-requested');
+};
+
+exports.info = {
+ name: 'morestats',
+ description: 'Sends back current server stats to the calling client'
+}; \ No newline at end of file
diff --git a/server/src/commands/core/move.js b/server/src/commands/core/move.js
new file mode 100644
index 0000000..c5efafd
--- /dev/null
+++ b/server/src/commands/core/move.js
@@ -0,0 +1,83 @@
+/*
+ Description: Generates a semi-unique channel name then broadcasts it to each client
+*/
+
+exports.run = async (core, server, socket, data) => {
+ if (server._police.frisk(socket.remoteAddress, 6)) {
+ server.reply({
+ cmd: 'warn',
+ text: 'You are changing channels too fast. Wait a moment before trying again.'
+ }, socket);
+
+ return;
+ }
+
+ if (typeof data.channel !== 'string') {
+ return;
+ }
+
+ if (data.channel === socket.channel) {
+ // They are trying to rejoin the channel
+ return;
+ }
+
+ const currentNick = socket.nick.toLowerCase();
+ let userExists = server.findSockets({
+ channel: data.channel,
+ nick: (targetNick) => targetNick.toLowerCase() === currentNick
+ });
+
+ if (userExists.length > 0) {
+ // That nickname is already in that channel
+ return;
+ }
+
+ let peerList = server.findSockets({ channel: socket.channel });
+
+ if (peerList.length > 1) {
+ for (let i = 0, l = peerList.length; i < l; i++) {
+ server.reply({
+ cmd: 'onlineRemove',
+ nick: peerList[i].nick
+ }, socket);
+
+ if (socket.nick !== peerList[i].nick){
+ server.reply({
+ cmd: 'onlineRemove',
+ nick: socket.nick
+ }, peerList[i]);
+ }
+ }
+ }
+
+ let newPeerList = server.findSockets({ channel: data.channel });
+ let moveAnnouncement = {
+ cmd: 'onlineAdd',
+ nick: socket.nick,
+ trip: socket.trip || 'null',
+ hash: server.getSocketHash(socket)
+ };
+ let nicks = [];
+
+ for (let i = 0, l = newPeerList.length; i < l; i++) {
+ server.reply(moveAnnouncement, newPeerList[i]);
+ nicks.push(newPeerList[i].nick);
+ }
+
+ nicks.push(socket.nick);
+
+ server.reply({
+ cmd: 'onlineSet',
+ nicks: nicks
+ }, socket);
+
+ socket.channel = data.channel;
+};
+
+exports.requiredData = ['channel'];
+
+exports.info = {
+ name: 'move',
+ usage: 'move {channel}',
+ description: 'This will change the current channel to the new one provided'
+}; \ No newline at end of file
diff --git a/server/src/commands/core/stats.js b/server/src/commands/core/stats.js
new file mode 100644
index 0000000..b9dc002
--- /dev/null
+++ b/server/src/commands/core/stats.js
@@ -0,0 +1,32 @@
+/*
+ Description: Legacy stats output, kept for compatibility, outputs user and channel count
+*/
+
+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: `${uniqueClientCount} unique IPs in ${uniqueChannels} channels`
+ }, socket);
+
+ core.managers.stats.increment('stats-requested');
+};
+
+exports.info = {
+ name: 'stats',
+ description: 'Sends back legacy server stats to the calling client'
+}; \ No newline at end of file
diff --git a/server/src/commands/mod/ban.js b/server/src/commands/mod/ban.js
new file mode 100644
index 0000000..e19efc2
--- /dev/null
+++ b/server/src/commands/mod/ban.js
@@ -0,0 +1,64 @@
+/*
+ Description: Adds the target socket's ip to the ratelimiter
+*/
+
+exports.run = async (core, server, socket, data) => {
+ if (socket.uType == 'user') {
+ // ignore if not mod or admin
+ return;
+ }
+
+ if (typeof data.nick !== 'string') {
+ return;
+ }
+
+ let targetNick = data.nick;
+ let badClient = server.findSockets({ channel: socket.channel, nick: targetNick });
+
+ if (badClient.length === 0) {
+ server.reply({
+ cmd: 'warn',
+ text: 'Could not find user in channel'
+ }, socket);
+
+ return;
+ }
+
+ badClient = badClient[0];
+
+ if (badClient.uType !== 'user') {
+ server.reply({
+ cmd: 'warn',
+ text: 'Cannot ban other mods, how rude'
+ }, socket);
+
+ return;
+ }
+
+ let clientHash = server.getSocketHash(badClient);
+ server._police.arrest(badClient.remoteAddress, clientHash);
+
+ console.log(`${socket.nick} [${socket.trip}] banned ${targetNick} in ${socket.channel}`);
+
+ server.broadcast({
+ cmd: 'info',
+ text: `Banned ${targetNick}`
+ }, { channel: socket.channel, uType: 'user' });
+
+ server.broadcast({
+ cmd: 'info',
+ text: `${socket.nick} banned ${targetNick} in ${socket.channel}, userhash: ${clientHash}`
+ }, { uType: 'mod' });
+
+ 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..157592d
--- /dev/null
+++ b/server/src/commands/mod/kick.js
@@ -0,0 +1,78 @@
+/*
+ Description: Forces a change on the target socket's channel, then broadcasts event
+*/
+
+exports.run = async (core, server, socket, data) => {
+ if (socket.uType === 'user') {
+ // ignore if not mod or admin
+ return;
+ }
+
+ if (typeof data.nick !== 'string') {
+ if (typeof data.nick !== 'object' && !Array.isArray(data.nick)) {
+ return;
+ }
+ }
+
+ let badClients = server.findSockets({ channel: socket.channel, nick: data.nick });
+
+ if (badClients.length === 0) {
+ server.reply({
+ cmd: 'warn',
+ text: 'Could not find user(s) in channel'
+ }, socket);
+
+ return;
+ }
+
+ let newChannel = '';
+ let kicked = [];
+ for (let i = 0, j = badClients.length; i < j; i++) {
+ if (badClients[i].uType !== 'user') {
+ server.reply({
+ cmd: 'warn',
+ text: 'Cannot kick other mods, how rude'
+ }, socket);
+ } else {
+ newChannel = Math.random().toString(36).substr(2, 8);
+ badClients[i].channel = newChannel;
+
+ // inform mods with where they were sent
+ server.broadcast({
+ cmd: 'info',
+ text: `${badClients[i].nick} was banished to ?${newChannel}`
+ }, { channel: socket.channel, uType: 'mod' });
+
+ kicked.push(badClients[i].nick);
+ console.log(`${socket.nick} [${socket.trip}] kicked ${badClients[i].nick} in ${socket.channel}`);
+ }
+ }
+
+ if (kicked.length === 0) {
+ return;
+ }
+
+ // broadcast client leave event
+ for (let i = 0, j = kicked.length; i < j; i++) {
+ server.broadcast({
+ cmd: 'onlineRemove',
+ nick: kicked[i]
+ }, { channel: socket.channel });
+ }
+
+ // publicly broadcast kick event
+ server.broadcast({
+ cmd: 'info',
+ text: `Kicked ${kicked.join(', ')}`
+ }, { channel: socket.channel, uType: 'user' });
+
+ core.managers.stats.increment('users-kicked', kicked.length);
+};
+
+exports.requiredData = ['nick'];
+
+exports.info = {
+ name: 'kick',
+ usage: 'kick {nick}',
+ description: 'Silently forces target client(s) into another channel. `nick` may be string or array of strings'
+}; \ No newline at end of file
diff --git a/server/src/commands/mod/unban.js b/server/src/commands/mod/unban.js
new file mode 100644
index 0000000..e82f0b9
--- /dev/null
+++ b/server/src/commands/mod/unban.js
@@ -0,0 +1,55 @@
+/*
+ Description: Removes a target ip from the ratelimiter
+*/
+
+exports.run = async (core, server, socket, data) => {
+ if (socket.uType == 'user') {
+ // ignore if not mod or admin
+ return;
+ }
+
+ if (typeof data.ip !== 'string' && typeof data.hash !== 'string') {
+ server.reply({
+ cmd: 'warn',
+ text: "hash:'targethash' or ip:'1.2.3.4' is required"
+ }, socket);
+
+ return;
+ }
+
+ let mode, target;
+
+ if (typeof data.ip === 'string') {
+ mode = 'ip';
+ target = data.ip;
+ } else {
+ mode = 'hash';
+ target = data.hash;
+ }
+
+ server._police.pardon(target);
+
+ if (mode === 'ip') {
+ target = server.getSocketHash(target);
+ }
+
+ console.log(`${socket.nick} [${socket.trip}] unbanned ${target} in ${socket.channel}`);
+
+ server.reply({
+ cmd: 'info',
+ text: `Unbanned ${target}`
+ }, socket);
+
+ server.broadcast({
+ cmd: 'info',
+ text: `${socket.nick} unbanned: ${target}`
+ }, { uType: 'mod' });
+
+ core.managers.stats.decrement('users-banned');
+};
+
+exports.info = {
+ name: 'unban',
+ usage: 'unban {[ip || hash]}',
+ description: 'Removes target ip from the ratelimiter'
+}; \ No newline at end of file
diff --git a/server/src/core/rateLimiter.js b/server/src/core/rateLimiter.js
new file mode 100644
index 0000000..0c2a384
--- /dev/null
+++ b/server/src/core/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 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
new file mode 100644
index 0000000..855aeba
--- /dev/null
+++ b/server/src/core/server.js
@@ -0,0 +1,282 @@
+/**
+ * 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 = (Math.random().toString(36).substring(2, 16) + Math.random().toString(36).substring(2, (Math.random() * 16))).repeat(16);
+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._police = new Police();
+ this._cmdBlacklist = {};
+ this._heartBeat = setInterval(((data) => {
+ this.beatHeart();
+ }).bind(this), pulseSpeed);
+
+ this.on('error', (err) => {
+ this.handleError('server', err);
+ });
+
+ this.on('connection', (socket, request) => {
+ this.newConnection(socket, request);
+ });
+ }
+
+ /**
+ * 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);
+ }).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) {
+ // 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;
+ }
+
+ // Start sent data verification
+ 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;
+ }
+
+ if (typeof args.cmd !== 'string') {
+ return;
+ }
+
+ if (typeof socket.channel === 'undefined' && args.cmd !== 'join') {
+ return;
+ }
+
+ if (typeof this._cmdBlacklist[args.cmd] === 'function') {
+ return;
+ }
+
+ // Finished verification, pass to command modules
+ this._core.commands.handleCommand(this, socket, args);
+ }
+
+ /**
+ * Handle socket close from clients
+ *
+ * @param {Object} socket Closing socket object
+ */
+ handleClose (socket) {
+ this._core.commands.handleCommand(this, socket, { cmd: 'disconnect' });
+ }
+
+ /**
+ * "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} 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 === socketReady) {
+ 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 see `this.findSockets()`
+ */
+ broadcast (data, filter) {
+ let targetSockets = this.findSockets(filter);
+
+ if (targetSockets.length === 0) {
+ return false;
+ }
+
+ for (let i = 0, l = targetSockets.length; i < l; i++) {
+ this.send(data, 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;
+ }
+
+ /**
+ * Encrypts 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);
+ }
+}
+
+module.exports = server;
diff --git a/server/src/managers/commands.js b/server/src/managers/commands.js
new file mode 100644
index 0000000..c38fb4d
--- /dev/null
+++ b/server/src/managers/commands.js
@@ -0,0 +1,239 @@
+/**
+ * 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');
+
+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 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) {
+ let errText = `Failed to execute '${command.info.name}': ${err}`;
+ 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..2865d00
--- /dev/null
+++ b/server/src/managers/config.js
@@ -0,0 +1,224 @@
+/**
+ * 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');
+
+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 (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
new file mode 100644
index 0000000..d8b2144
--- /dev/null
+++ b/server/src/managers/imports-manager.js
@@ -0,0 +1,148 @@
+/**
+ * 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
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..20f1ae3
--- /dev/null
+++ b/server/src/managers/stats.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 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