1
0
mirror of https://github.com/hack-chat/main.git synced 2024-03-22 13:20:33 +08:00

Streamlined modules, server tweaks, better feedback

This commit is contained in:
marzavec 2018-03-13 22:26:53 -07:00
parent 7d8220d838
commit 39ec02d3c4
19 changed files with 204 additions and 114 deletions

View File

@ -1,5 +1,5 @@
/* /*
Description: Adds the target trip to the mod list then elevates the uType
*/ */
'use strict'; 'use strict';
@ -16,14 +16,16 @@ exports.run = async (core, server, socket, data) => {
core.config.mods.push(mod); // purposely not using `config.set()` to avoid auto-save core.config.mods.push(mod); // purposely not using `config.set()` to avoid auto-save
for (let client of server.clients) { let newMod = server.findSockets({ trip: data.trip });
if (typeof client.trip !== 'undefined' && client.trip === data.trip) {
client.uType = 'mod';
server.reply({ if (newMod.length !== 0) {
for (let i = 0, l = newMod.length; i < l; i++) {
newMod[i].uType = 'mod';
server.send({
cmd: 'info', cmd: 'info',
text: 'You are now a mod.' text: 'You are now a mod.'
}, client); }, newMod[i]);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
Description: Outputs all current channels and their user nicks
*/ */
'use strict'; 'use strict';

View File

@ -1,5 +1,5 @@
/* /*
Description: Clears and resets the command modules, outputting any errors
*/ */
'use strict'; 'use strict';
@ -14,7 +14,9 @@ exports.run = async (core, server, socket, data) => {
loadResult += core.commands.loadCommands(); loadResult += core.commands.loadCommands();
if (loadResult == '') { if (loadResult == '') {
loadResult = 'Commands reloaded without errors!'; loadResult = `Loaded ${core.commands._commands.length} commands, 0 errors`;
} else {
loadResult = `Loaded ${core.commands._commands.length} commands, error(s): ${loadResult}`;
} }
server.reply({ server.reply({

View File

@ -1,5 +1,5 @@
/* /*
Description: Writes any changes to the config to the disk
*/ */
'use strict'; 'use strict';

View File

@ -1,5 +1,5 @@
/* /*
Description: Emmits a server-wide message as `info`
*/ */
'use strict'; 'use strict';

View File

@ -1,10 +1,10 @@
/* /*
Description: Rebroadcasts any `text` to all clients in a `channel`
*/ */
'use strict'; 'use strict';
function parseText(text) { const parseText = (text) => {
if (typeof text !== 'string') { if (typeof text !== 'string') {
return false; return false;
} }
@ -15,7 +15,7 @@ function parseText(text) {
text = text.replace(/\n{3,}/g, "\n\n"); text = text.replace(/\n{3,}/g, "\n\n");
return text; return text;
} };
exports.run = async (core, server, socket, data) => { exports.run = async (core, server, socket, data) => {
let text = parseText(data.text); let text = parseText(data.text);

View File

@ -1,5 +1,5 @@
/* /*
Description: Outputs the current command module list or command categories
*/ */
'use strict'; 'use strict';
@ -44,9 +44,8 @@ exports.run = async (core, server, socket, data) => {
}, socket); }, socket);
}; };
// optional parameters are marked, all others are required
exports.info = { exports.info = {
name: 'help', // actual command name name: 'help',
usage: 'help ([ type:categories] | [category:<category name> | command:<command name> ])', usage: 'help ([ type:categories] | [category:<category name> | command:<command name> ])',
description: 'Outputs information about the servers current protocol' description: 'Outputs information about the servers current protocol'
}; };

View File

@ -1,12 +1,12 @@
/* /*
Description: Generates a semi-unique channel name then broadcasts it to each client
*/ */
'use strict'; 'use strict';
function verifyNickname(nick) { const verifyNickname = (nick) => {
return /^[a-zA-Z0-9_]{1,24}$/.test(nick); return /^[a-zA-Z0-9_]{1,24}$/.test(nick);
} };
exports.run = async (core, server, socket, data) => { exports.run = async (core, server, socket, data) => {
if (typeof data.nick !== 'string') { if (typeof data.nick !== 'string') {
@ -19,7 +19,7 @@ exports.run = async (core, server, socket, data) => {
} }
if (data.nick == socket.nick) { if (data.nick == socket.nick) {
// TODO: reply with something witty? They invited themself // They invited themself
return; return;
} }

View File

@ -1,20 +1,20 @@
/* /*
Description: Initial entry point, applies `channel` and `nick` to the calling socket
*/ */
'use strict'; 'use strict';
const crypto = require('crypto'); const crypto = require('crypto');
function hash(password) { const hash = (password) => {
var sha = crypto.createHash('sha256'); let sha = crypto.createHash('sha256');
sha.update(password); sha.update(password);
return sha.digest('base64').substr(0, 6); return sha.digest('base64').substr(0, 6);
} };
function verifyNickname(nick) { const verifyNickname = (nick) => {
return /^[a-zA-Z0-9_]{1,24}$/.test(nick); return /^[a-zA-Z0-9_]{1,24}$/.test(nick);
} };
exports.run = async (core, server, socket, data) => { exports.run = async (core, server, socket, data) => {
if (server._police.frisk(socket.remoteAddress, 3)) { if (server._police.frisk(socket.remoteAddress, 3)) {
@ -53,7 +53,7 @@ exports.run = async (core, server, socket, data) => {
text: 'Nickname must consist of up to 24 letters, numbers, and underscores' text: 'Nickname must consist of up to 24 letters, numbers, and underscores'
}, socket); }, socket);
return return;
} }
for (let client of server.clients) { for (let client of server.clients) {
@ -99,7 +99,8 @@ exports.run = async (core, server, socket, data) => {
server.broadcast({ server.broadcast({
cmd: 'onlineAdd', cmd: 'onlineAdd',
nick: nick, nick: nick,
trip: trip || 'null' trip: trip || 'null',
hash: server.getSocketHash(socket)
}, { channel: channel }); }, { channel: channel });
socket.uType = uType; socket.uType = uType;

View File

@ -0,0 +1,54 @@
/*
Description: Outputs more info than the legacy stats command
*/
'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: 'morestats',
description: 'Sends back current server stats to the calling client'
};

View File

@ -1,5 +1,5 @@
/* /*
Description: This is a template module that should not be on prod
*/ */
'use strict'; 'use strict';
@ -14,21 +14,26 @@ const createReply = (echoInput) => {
return `You want me to echo: ${echoInput}?` 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()` is required and will always be passed (core, server, socket, data)
// this is the main function
be sure it's async too
this is the main function that will run when called
*/
exports.run = async (core, server, socket, data) => { exports.run = async (core, server, socket, data) => {
server.reply({ server.reply({
cmd: 'info', cmd: 'info',
text: `SHOWCASE MODULE: ${core.showcase} - ${this.createReply(data.echo)}` text: `SHOWCASE MODULE: ${core.showcase} - ${createReply(data.echo)}`
}, socket); }, 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 `exports.init()` is optional, and will only be run when the module is loaded into memory
// note: this will fire again if a reload is issued, keep that in mind 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) => { exports.init = (core) => {
if (typeof core.showcase === 'undefined') { if (typeof core.showcase === 'undefined') {
core.showcase = 'init is a handy place to put global data by assigning it to `core`'; core.showcase = 'init is a handy place to put global data by assigning it to `core`';

View File

@ -1,22 +1,9 @@
/* /*
Description: Legacy stats output, kept for compatibility, outputs user and channel count
*/ */
'use strict'; '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) => { exports.run = async (core, server, socket, data) => {
let ips = {}; let ips = {};
let channels = {}; let channels = {};
@ -35,14 +22,7 @@ exports.run = async (core, server, socket, data) => {
server.reply({ server.reply({
cmd: 'info', cmd: 'info',
text: stripIndents`current-connections: ${uniqueClientCount} text: `${uniqueClientCount} unique IPs in ${uniqueChannels} channels`
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); }, socket);
core.managers.stats.increment('stats-requested'); core.managers.stats.increment('stats-requested');
@ -50,5 +30,5 @@ exports.run = async (core, server, socket, data) => {
exports.info = { exports.info = {
name: 'stats', name: 'stats',
description: 'Sends back current server stats to the calling client' description: 'Sends back legacy server stats to the calling client'
}; };

View File

@ -1,5 +1,5 @@
/* /*
Description: Adds the target socket's ip to the ratelimiter
*/ */
'use strict'; 'use strict';
@ -15,16 +15,9 @@ exports.run = async (core, server, socket, data) => {
} }
let targetNick = data.nick; let targetNick = data.nick;
let badClient = null; let badClient = server.findSockets({ channel: socket.channel, nick: targetNick });
for (let client of server.clients) {
// Find badClient's socket
if (client.channel == socket.channel && client.nick == targetNick) {
badClient = client;
break;
}
}
if (!badClient) { if (badClient.length === 0) {
server.reply({ server.reply({
cmd: 'warn', cmd: 'warn',
text: 'Could not find user in channel' text: 'Could not find user in channel'
@ -33,6 +26,8 @@ exports.run = async (core, server, socket, data) => {
return; return;
} }
badClient = badClient[0];
if (badClient.uType !== 'user') { if (badClient.uType !== 'user') {
server.reply({ server.reply({
cmd: 'warn', cmd: 'warn',
@ -42,16 +37,21 @@ exports.run = async (core, server, socket, data) => {
return; return;
} }
// TODO: add reference to banned users nick or unban by nick cmd // TODO unban by hash
server._police.arrest(badClient.remoteAddress); server._police.arrest(badClient.remoteAddress);
// TODO: add event to log?
console.log(`${socket.nick} [${socket.trip}] banned ${targetNick} in ${socket.channel}`); console.log(`${socket.nick} [${socket.trip}] banned ${targetNick} in ${socket.channel}`);
server.broadcast({ server.broadcast({
cmd: 'info', cmd: 'info',
text: `Banned ${targetNick}` text: `Banned ${targetNick}`
}, { channel: socket.channel }); }, { channel: socket.channel, uType: 'user' });
server.broadcast({
cmd: 'info',
text: `${socket.nick} banned ${targetNick} in ${socket.channel}, userhash: ${server.getSocketHash(badClient)}`
}, { uType: 'mod' });
badClient.close(); badClient.close();
core.managers.stats.increment('users-banned'); core.managers.stats.increment('users-banned');

View File

@ -1,5 +1,5 @@
/* /*
Description: Forces a change on the target socket's channel, then broadcasts event
*/ */
'use strict'; 'use strict';
@ -15,16 +15,9 @@ exports.run = async (core, server, socket, data) => {
} }
let targetNick = data.nick; let targetNick = data.nick;
let badClient = null; let badClient = server.findSockets({ channel: socket.channel, nick: targetNick });
for (let client of server.clients) {
// Find badClient's socket
if (client.channel == socket.channel && client.nick == targetNick) {
badClient = client;
break;
}
}
if (!badClient) { if (badClient.length === 0) {
server.reply({ server.reply({
cmd: 'warn', cmd: 'warn',
text: 'Could not find user in channel' text: 'Could not find user in channel'
@ -33,6 +26,8 @@ exports.run = async (core, server, socket, data) => {
return; return;
} }
badClient = badClient[0];
if (badClient.uType !== 'user') { if (badClient.uType !== 'user') {
server.reply({ server.reply({
cmd: 'warn', cmd: 'warn',
@ -42,7 +37,6 @@ exports.run = async (core, server, socket, data) => {
return; return;
} }
// TODO: add event to log?
let newChannel = Math.random().toString(36).substr(2, 8); let newChannel = Math.random().toString(36).substr(2, 8);
badClient.channel = newChannel; badClient.channel = newChannel;
@ -54,7 +48,7 @@ exports.run = async (core, server, socket, data) => {
nick: targetNick nick: targetNick
}, { channel: socket.channel }); }, { channel: socket.channel });
// publicly broadcast event (TODO: should this be supressed?) // publicly broadcast event
server.broadcast({ server.broadcast({
cmd: 'info', cmd: 'info',
text: `Kicked ${targetNick}` text: `Kicked ${targetNick}`

View File

@ -1,5 +1,5 @@
/* /*
Description: Removes a target ip from the ratelimiter
*/ */
'use strict'; 'use strict';
@ -15,17 +15,32 @@ exports.run = async (core, server, socket, data) => {
} }
let ip = data.ip; let ip = data.ip;
let nick = data.nick; // for future upgrade let hash = data.hash; // TODO unban by hash
// TODO: support remove by nick future upgrade // TODO unban by hash
server._police.pardon(badClient.remoteAddress); let recordFound = server._police.pardon(data.ip);
console.log(`${socket.nick} [${socket.trip}] unbanned ${/*nick || */ip} in ${socket.channel}`);
if (!recordFound) {
server.reply({
cmd: 'warn',
text: 'Could not find target in records'
}, socket);
return;
}
console.log(`${socket.nick} [${socket.trip}] unbanned ${/*hash || */ip} in ${socket.channel}`);
server.reply({ server.reply({
cmd: 'info', cmd: 'info',
text: `Unbanned ${/*nick || */ip}` text: `${socket.nick} unbanned a userhash: ${server.getSocketHash(ip)}`
}, socket); }, socket);
server.broadcast({
cmd: 'info',
text: `${socket.nick} unbanned a userhash: ${server.getSocketHash(ip)}`
}, { uType: 'mod' });
core.managers.stats.decrement('users-banned'); core.managers.stats.decrement('users-banned');
}; };

View File

@ -97,7 +97,10 @@ class Police {
if (record) { if (record) {
record.arrested = false; record.arrested = false;
return true;
} }
return false;
} }
} }

View File

@ -10,13 +10,16 @@
'use strict'; 'use strict';
const wsServer = require('ws').Server; 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 Police = require('./rateLimiter');
class server extends wsServer { class server extends wsServer {
/** /**
* Create a HackChat server instance. * Create a HackChat server instance.
* *
* @param {Object} core Reference to the core server object * @param {Object} core Reference to the global core object
*/ */
constructor (core) { constructor (core) {
super({ port: core.config.websocketPort }); super({ port: core.config.websocketPort });
@ -78,6 +81,7 @@ class server extends wsServer {
return; return;
} }
// Start sent data verification
var args = null; var args = null;
try { try {
args = JSON.parse(data); args = JSON.parse(data);
@ -106,6 +110,7 @@ class server extends wsServer {
return; return;
} }
// Finished verification, pass to command modules
this._core.commands.handleCommand(this, socket, args); this._core.commands.handleCommand(this, socket, args);
} }
@ -122,8 +127,8 @@ class server extends wsServer {
nick: socket.nick nick: socket.nick
}, { channel: socket.channel }); }, { channel: socket.channel });
} }
} catch (e) { } catch (err) {
// TODO: Should this be added to the error log? console.log(`Server, handle close event error: ${err}`);
} }
} }
@ -134,9 +139,7 @@ class server extends wsServer {
* @param {String} err The sad stuff * @param {String} err The sad stuff
*/ */
handleError (socket, err) { handleError (socket, err) {
// Meh, yolo console.log(`Server error: ${err}`);
// I mean;
// TODO: Should this be added to the error log?
} }
/** /**
@ -150,7 +153,7 @@ class server extends wsServer {
data.time = Date.now(); data.time = Date.now();
try { try {
if (socket.readyState == 1) { // Who says statically checking port status is bad practice? Everyone? Damnit. #TODO if (socket.readyState === socketReady) {
socket.send(JSON.stringify(data)); socket.send(JSON.stringify(data));
} }
} catch (e) { } } catch (e) { }
@ -170,16 +173,36 @@ class server extends wsServer {
* Finds sockets/clients that meet the filter requirements, then passes the data to them * 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} 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` * @param {Object} filter The socket must of equal or greater attribs matching `filter`
* = {} // matches all * = {} // matches all
* = { channel: 'programming' } // matches any socket where (`socket.channel` === 'programming') * = { channel: 'programming' } // matches any socket where (`socket.channel` === 'programming')
* = { channel: 'programming', nick: 'Marzavec' } // matches any socket where (`socket.channel` === 'programming' && `socket.nick` === 'Marzavec') * = { channel: 'programming', nick: 'Marzavec' } // matches any socket where (`socket.channel` === 'programming' && `socket.nick` === 'Marzavec')
*/ */
broadcast (data, filter) { findSockets (filter) {
let filterAttribs = Object.keys(filter); let filterAttribs = Object.keys(filter);
let reqCount = filterAttribs.length; let reqCount = filterAttribs.length;
let curMatch; let curMatch;
let sent = false; let matches = [];
for ( let socket of this.clients ) { for ( let socket of this.clients ) {
curMatch = 0; curMatch = 0;
@ -189,12 +212,29 @@ class server extends wsServer {
} }
if (curMatch === reqCount) { if (curMatch === reqCount) {
this.send(data, socket); matches.push(socket);
sent = true;
} }
} }
return sent; 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);
} }
} }

View File

@ -17,7 +17,7 @@ class CommandManager {
/** /**
* Create a `CommandManager` instance for handling commands/protocol * Create a `CommandManager` instance for handling commands/protocol
* *
* @param {Object} core reference to the global core object * @param {Object} core Reference to the global core object
*/ */
constructor (core) { constructor (core) {
this.core = core; this.core = core;
@ -57,8 +57,7 @@ class CommandManager {
let error = this._validateCommand(command); let error = this._validateCommand(command);
if (error) { if (error) {
// TODO: Add to logger? let errText = `Failed to load '${name}': ${error}`;
let errText = `Failed to load '${name}': ${error}\n\n`;
console.log(errText); console.log(errText);
return errText; return errText;
} }
@ -82,8 +81,7 @@ class CommandManager {
try { try {
command.init(this.core); command.init(this.core);
} catch (err) { } catch (err) {
// TODO: Add to logger? let errText = `Failed to initialize '${name}': ${err}`;
let errText = `Failed to initialize '${name}': ${err}\n\n`;
console.log(errText); console.log(errText);
return errText; return errText;
} }
@ -227,8 +225,7 @@ class CommandManager {
try { try {
return await command.run(this.core, server, socket, data); return await command.run(this.core, server, socket, data);
} catch (err) { } catch (err) {
// TODO: Add to logger? let errText = `Failed to execute '${command.info.name}': ${err}`;
let errText = `Failed to execute '${command.info.name}': ${err}\n\n`;
console.log(errText); console.log(errText);
server.reply({ server.reply({

View File

@ -202,10 +202,8 @@ class ConfigManager {
fse.removeSync(backupPath); fse.removeSync(backupPath);
return true; return true;
} catch (e) { } catch (err) {
// TODO: restore backup console.log(`Failed to save config file: ${err}`);
// TODO: output to logging engine?
console.log('Failed to save config file!');
return false; return false;
} }