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

cleaned up and commented modules

This commit is contained in:
marzavec 2018-06-04 00:07:24 -07:00
parent 62daa4893f
commit e35fff59ba
23 changed files with 185 additions and 89 deletions

View File

@ -1,6 +1,6 @@
{
"name": "hack.chat-v2",
"version": "2.0.1",
"version": "2.0.3",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

2
package-lock.json generated
View File

@ -1,6 +1,6 @@
{
"name": "hack.chat-v2",
"version": "2.0.2",
"version": "2.0.3",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

View File

@ -1,6 +1,6 @@
{
"name": "hack.chat-v2",
"version": "2.0.1",
"version": "2.0.3",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

View File

@ -3,19 +3,18 @@
*/
exports.run = async (core, server, socket, data) => {
// increase rate limit chance and ignore if not admin
if (socket.uType != 'admin') {
// ignore if not admin
server._police.frisk(socket.remoteAddress, 20);
return;
}
let mod = {
trip: data.trip
}
core.config.mods.push(mod); // purposely not using `config.set()` to avoid auto-save
// add new trip to config
core.config.mods.push({ trip: data.trip }); // purposely not using `config.set()` to avoid auto-save
// upgarde existing connections & notify user
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';
@ -27,11 +26,13 @@ exports.run = async (core, server, socket, data) => {
}
}
// return success message
server.reply({
cmd: 'info',
text: `Added mod trip: ${data.trip}`
}, socket);
// notify all mods
server.broadcast({
cmd: 'info',
text: `Added mod trip: ${data.trip}`

View File

@ -3,32 +3,37 @@
*/
exports.run = async (core, server, socket, data) => {
// increase rate limit chance and ignore if not admin
if (socket.uType != 'admin') {
// ignore if not admin
server._police.frisk(socket.remoteAddress, 20);
return;
}
// find all users currently in a channel
let currentUsers = server.findSockets({
channel: (channel) => true
});
// compile channel and user list
let channels = {};
for (var client of server.clients) {
if (client.channel) {
if (!channels[client.channel]) {
channels[client.channel] = [];
}
channels[client.channel].push(client.nick);
for (let i = 0, j = currentUsers.length; i < j; i++) {
if (typeof channels[currentUsers[i].channel] === 'undefined') {
channels[currentUsers[i].channel] = [];
}
channels[currentUsers[i].channel].push(currentUsers[i].nick);
}
// build output
let lines = [];
for (let channel in channels) {
lines.push(`?${channel} ${channels[channel].join(", ")}`);
}
let text = '';
text += lines.join("\n");
// send reply
server.reply({
cmd: 'info',
text: text
text: lines.join("\n")
}, socket);
};

View File

@ -3,25 +3,31 @@
*/
exports.run = async (core, server, socket, data) => {
// increase rate limit chance and ignore if not admin
if (socket.uType != 'admin') {
// ignore if not admin
server._police.frisk(socket.remoteAddress, 20);
return;
}
// do command reloads and store results
let loadResult = core.managers.dynamicImports.reloadDirCache('src/commands');
loadResult += core.commands.loadCommands();
// build reply based on reload results
if (loadResult == '') {
loadResult = `Loaded ${core.commands._commands.length} commands, 0 errors`;
} else {
loadResult = `Loaded ${core.commands._commands.length} commands, error(s): ${loadResult}`;
}
// reply with results
server.reply({
cmd: 'info',
text: loadResult
}, socket);
// notify mods of reload #transparency
server.broadcast({
cmd: 'info',
text: loadResult
@ -32,4 +38,3 @@ exports.info = {
name: 'reload',
description: '(Re)loads any new commands into memory, outputs errors if any'
};

View File

@ -1,16 +1,17 @@
/*
Description: Writes any changes to the config to the disk
Description: Writes the current config to disk
*/
exports.run = async (core, server, socket, data) => {
// increase rate limit chance and ignore if not admin
if (socket.uType != 'admin') {
// ignore if not admin
server._police.frisk(socket.remoteAddress, 20);
return;
}
let saveResult = core.managers.config.save();
if (!saveResult) {
// attempt save, notify of failure
if (!core.managers.config.save()) {
server.reply({
cmd: 'warn',
text: 'Failed to save config, check logs.'
@ -19,11 +20,13 @@ exports.run = async (core, server, socket, data) => {
return;
}
// return success message
server.reply({
cmd: 'info',
text: 'Config saved!'
}, socket);
// notify mods #transparency
server.broadcast({
cmd: 'info',
text: 'Config saved!'
@ -32,5 +35,5 @@ exports.run = async (core, server, socket, data) => {
exports.info = {
name: 'saveconfig',
description: 'Saves current config'
description: 'Writes the current config to disk'
};

View File

@ -3,12 +3,15 @@
*/
exports.run = async (core, server, socket, data) => {
// increase rate limit chance and ignore if not admin
if (socket.uType != 'admin') {
// ignore if not admin
server._police.frisk(socket.remoteAddress, 20);
return;
}
server.broadcast( {
// send text to all channels
server.broadcast({
cmd: 'info',
text: `Server Notice: ${data.text}`
}, {});

View File

@ -2,9 +2,7 @@
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);
};
const verifyNickname = (nick) => /^[a-zA-Z0-9_]{1,24}$/.test(nick);
exports.run = async (core, server, socket, data) => {
if (server._police.frisk(socket.remoteAddress, 6)) {
@ -16,12 +14,13 @@ exports.run = async (core, server, socket, data) => {
return;
}
// verify user data is string
if (typeof data.nick !== 'string') {
return;
}
// make sure requested nickname meets standards
let newNick = data.nick.trim();
if (!verifyNickname(newNick)) {
server.reply({
cmd: 'warn',
@ -31,6 +30,8 @@ exports.run = async (core, server, socket, data) => {
return;
}
// prevent admin impersonation
// TODO: prevent mod impersonation
if (newNick.toLowerCase() == core.config.adminName.toLowerCase()) {
server._police.frisk(socket.remoteAddress, 4);
@ -42,11 +43,13 @@ exports.run = async (core, server, socket, data) => {
return;
}
// find any sockets that have the same nickname
let userExists = server.findSockets({
channel: socket.channel,
nick: (targetNick) => targetNick.toLowerCase() === newNick.toLowerCase()
});
// return error if found
if (userExists.length > 0) {
// That nickname is already in that channel
server.reply({
@ -57,7 +60,7 @@ exports.run = async (core, server, socket, data) => {
return;
}
let peerList = server.findSockets({ channel: socket.channel });
// build join and leave notices
let leaveNotice = {
cmd: 'onlineRemove',
nick: socket.nick
@ -66,16 +69,20 @@ exports.run = async (core, server, socket, data) => {
cmd: 'onlineAdd',
nick: newNick,
trip: socket.trip || 'null',
hash: server.getSocketHash(socket)
hash: socket.hash
};
// broadcast remove event and join event with new name, this is to support legacy clients and bots
server.broadcast( leaveNotice, { channel: socket.channel });
server.broadcast( joinNotice, { channel: socket.channel });
// notify channel that the user has changed their name
server.broadcast( {
cmd: 'info',
text: `${socket.nick} is now ${newNick}`
}, { channel: socket.channel });
// commit change to nickname
socket.nick = newNick;
};

View File

@ -3,6 +3,7 @@
*/
const parseText = (text) => {
// verifies user input is text
if (typeof text !== 'string') {
return false;
}
@ -16,12 +17,16 @@ const parseText = (text) => {
};
exports.run = async (core, server, socket, data) => {
// check user input
let text = parseText(data.text);
if (!text) {
// lets not send objects or empty text, yea?
server._police.frisk(socket.remoteAddress, 6);
return;
}
// check for spam
let score = text.length / 83 / 4;
if (server._police.frisk(socket.remoteAddress, score)) {
server.reply({
@ -32,6 +37,7 @@ exports.run = async (core, server, socket, data) => {
return;
}
// build chat payload
let payload = {
cmd: 'chat',
nick: socket.nick,
@ -48,6 +54,7 @@ exports.run = async (core, server, socket, data) => {
payload.trip = socket.trip;
}
// check if the users connection is muted
// TODO: Add a more contained way for modules to interact, event hooks or something?
if(core.muzzledHashes && core.muzzledHashes[socket.hash]){
server.broadcast( payload, { channel: socket.channel, hash: socket.hash });
@ -59,6 +66,7 @@ exports.run = async (core, server, socket, data) => {
server.broadcast( payload, { channel: socket.channel});
}
// stats are fun
core.managers.stats.increment('messages-sent');
};

View File

@ -5,6 +5,8 @@
const stripIndents = require('common-tags').stripIndents;
exports.run = async (core, server, socket, data) => {
// TODO: this module needs to be clean up badly :(
// verify passed arguments
let typeDt = typeof data.type;
let catDt = typeof data.category;
@ -23,6 +25,7 @@ exports.run = async (core, server, socket, data) => {
Show all commands in category -> { cmd: 'help', category: '<category name>' }
Show specific command -> { cmd: 'help', command: '<command name>' }`;
// change reply based on query
if (typeDt !== 'undefined') {
let categories = core.commands.categories().sort();
reply = `Command Categories:\n${categories.map(c => `- ${c.replace('../src/commands/', '')}`).join('\n')}`;
@ -36,6 +39,7 @@ exports.run = async (core, server, socket, data) => {
Description: ${command.info.description || '¯\_(ツ)_/¯'}`;
}
// output reply
server.reply({
cmd: 'info',
text: reply

View File

@ -2,11 +2,10 @@
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);
};
const verifyNickname = (nick) => /^[a-zA-Z0-9_]{1,24}$/.test(nick);
exports.run = async (core, server, socket, data) => {
// check for spam
if (server._police.frisk(socket.remoteAddress, 2)) {
server.reply({
cmd: 'warn',
@ -16,22 +15,20 @@ exports.run = async (core, server, socket, data) => {
return;
}
if (typeof data.nick !== 'string') {
return;
}
if (!verifyNickname(data.nick)) {
// Not a valid nickname? Chances are we won't find them
// verify user input
if (typeof data.nick !== 'string' || !verifyNickname(data.nick)) {
return;
}
// why would you invite yourself?
if (data.nick == socket.nick) {
// They invited themself
return;
}
// generate common channel
let channel = Math.random().toString(36).substr(2, 8);
// build and send invite
let payload = {
cmd: 'info',
invite: channel,
@ -39,6 +36,7 @@ exports.run = async (core, server, socket, data) => {
};
let inviteSent = server.broadcast( payload, { channel: socket.channel, nick: data.nick });
// server indicates the user was not found
if (!inviteSent) {
server.reply({
cmd: 'warn',
@ -48,11 +46,13 @@ exports.run = async (core, server, socket, data) => {
return;
}
// reply with common channel
server.reply({
cmd: 'info',
text: `You invited ${data.nick} to ?${channel}`
}, socket);
// stats are fun
core.managers.stats.increment('invites-sent');
};

View File

@ -10,11 +10,10 @@ const hash = (password) => {
return sha.digest('base64').substr(0, 6);
};
const verifyNickname = (nick) => {
return /^[a-zA-Z0-9_]{1,24}$/.test(nick);
};
const verifyNickname = (nick) => /^[a-zA-Z0-9_]{1,24}$/.test(nick);
exports.run = async (core, server, socket, data) => {
// check for spam
if (server._police.frisk(socket.remoteAddress, 3)) {
server.reply({
cmd: 'warn',
@ -24,22 +23,23 @@ exports.run = async (core, server, socket, data) => {
return;
}
// calling socket already in a channel
if (typeof socket.channel !== 'undefined') {
// Calling socket already in a channel
return;
}
// check user input
if (typeof data.channel !== 'string' || typeof data.nick !== 'string') {
return;
}
let channel = data.channel.trim();
if (!channel) {
// Must join a non-blank channel
// must join a non-blank channel
return;
}
// Process nickname
// process nickname
let nick = data.nick;
let nickArray = nick.split('#', 2);
nick = nickArray[0].trim();
@ -53,13 +53,14 @@ exports.run = async (core, server, socket, data) => {
return;
}
// check if the nickname already exists in the channel
let userExists = server.findSockets({
channel: data.channel,
nick: (targetNick) => targetNick.toLowerCase() === nick.toLowerCase()
});
if (userExists.length > 0) {
// That nickname is already in that channel
// that nickname is already in that channel
server.reply({
cmd: 'warn',
text: 'Nickname taken'
@ -68,7 +69,7 @@ exports.run = async (core, server, socket, data) => {
return;
}
// TODO: Should we check for mod status first to prevent overwriting of admin status somehow? Meh, w/e, cba.
// 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];
@ -90,40 +91,47 @@ exports.run = async (core, server, socket, data) => {
trip = hash(password + core.config.tripSalt);
}
// TODO: Disallow moderator impersonation
// TODO: disallow moderator impersonation
for (let mod of core.config.mods) {
if (trip === mod.trip) {
uType = 'mod';
}
}
// Reply with online user list
// prepare to notify channel peers
let newPeerList = server.findSockets({ channel: data.channel });
let userHash = server.getSocketHash(socket);
let nicks = [];
let joinAnnouncement = {
cmd: 'onlineAdd',
nick: nick,
trip: trip || 'null',
hash: server.getSocketHash(socket)
hash: userHash
};
let nicks = [];
// send join announcement and prep online set
for (let i = 0, l = newPeerList.length; i < l; i++) {
server.reply(joinAnnouncement, newPeerList[i]);
nicks.push(newPeerList[i].nick);
}
// store user info
socket.uType = uType;
socket.nick = nick;
socket.channel = channel;
socket.hash = server.getSocketHash(socket);
socket.hash = userHash;
if (trip !== null) socket.trip = trip;
nicks.push(socket.nick);
// reply with channel peer list
server.reply({
cmd: 'onlineSet',
nicks: nicks
}, socket);
// stats are fun
core.managers.stats.increment('users-joined');
};

View File

@ -12,10 +12,15 @@ const formatTime = (time) => {
let hours = Math.floor(minutes / 60);
minutes = minutes % 60;
return `${hours.toFixed(0)}h ${minutes.toFixed(0)}m ${seconds.toFixed(0)}s`;
let days = Math.floor(hours / 24);
hours = hours % 24;
return `${days.toFixed(0)}d ${hours.toFixed(0)}h ${minutes.toFixed(0)}m ${seconds.toFixed(0)}s`;
};
exports.run = async (core, server, socket, data) => {
// gather connection and channel count
let ips = {};
let channels = {};
for (let client of server.clients) {
@ -31,6 +36,7 @@ exports.run = async (core, server, socket, data) => {
ips = null;
channels = null;
// dispatch info
server.reply({
cmd: 'info',
text: stripIndents`current-connections: ${uniqueClientCount}
@ -44,6 +50,7 @@ exports.run = async (core, server, socket, data) => {
server-uptime: ${formatTime(process.hrtime(core.managers.stats.get('start-time')))}`
}, socket);
// stats are fun
core.managers.stats.increment('stats-requested');
};

View File

@ -1,8 +1,9 @@
/*
Description: Generates a semi-unique channel name then broadcasts it to each client
Description: Changes the current channel of the calling socket
*/
exports.run = async (core, server, socket, data) => {
// check for spam
if (server._police.frisk(socket.remoteAddress, 6)) {
server.reply({
cmd: 'warn',
@ -12,15 +13,17 @@ exports.run = async (core, server, socket, data) => {
return;
}
// check user input
if (typeof data.channel !== 'string') {
return;
}
if (data.channel === socket.channel) {
// They are trying to rejoin the channel
// they are trying to rejoin the channel
return;
}
// check that the nickname isn't already in target channel
const currentNick = socket.nick.toLowerCase();
let userExists = server.findSockets({
channel: data.channel,
@ -32,6 +35,7 @@ exports.run = async (core, server, socket, data) => {
return;
}
// broadcast leave notice to peers
let peerList = server.findSockets({ channel: socket.channel });
if (peerList.length > 1) {
@ -50,12 +54,13 @@ exports.run = async (core, server, socket, data) => {
}
}
// broadcast join notice to new peers
let newPeerList = server.findSockets({ channel: data.channel });
let moveAnnouncement = {
cmd: 'onlineAdd',
nick: socket.nick,
trip: socket.trip || 'null',
hash: server.getSocketHash(socket)
hash: socket.hash
};
let nicks = [];
@ -66,11 +71,13 @@ exports.run = async (core, server, socket, data) => {
nicks.push(socket.nick);
// reply with new user list
server.reply({
cmd: 'onlineSet',
nicks: nicks
}, socket);
// commit change
socket.channel = data.channel;
};

View File

@ -3,6 +3,7 @@
*/
exports.run = async (core, server, socket, data) => {
// gather connection and channel count
let ips = {};
let channels = {};
for (let client of server.clients) {
@ -18,11 +19,13 @@ exports.run = async (core, server, socket, data) => {
ips = null;
channels = null;
// dispatch info
server.reply({
cmd: 'info',
text: `${uniqueClientCount} unique IPs in ${uniqueChannels} channels`
}, socket);
// stats are fun
core.managers.stats.increment('stats-requested');
};

View File

@ -11,6 +11,7 @@ exports.run = async (core, server, socket, data) => {
return;
}
// send leave notice to client peers
if (socket.channel) {
server.broadcast({
cmd: 'onlineRemove',
@ -18,6 +19,7 @@ exports.run = async (core, server, socket, data) => {
}, { channel: socket.channel });
}
// commit close just in case
socket.terminate();
};

View File

@ -10,6 +10,7 @@ exports.run = async (core, server, socket, data) => {
return;
}
// send warning to target socket
server.reply({ cmd: 'warn', text: data.text }, socket);
};

View File

@ -3,15 +3,19 @@
*/
exports.run = async (core, server, socket, data) => {
// increase rate limit chance and ignore if not admin or mod
if (socket.uType == 'user') {
// ignore if not mod or admin
server._police.frisk(socket.remoteAddress, 10);
return;
}
// check user input
if (typeof data.nick !== 'string') {
return;
}
// find target user
let targetNick = data.nick;
let badClient = server.findSockets({ channel: socket.channel, nick: targetNick });
@ -26,6 +30,7 @@ exports.run = async (core, server, socket, data) => {
badClient = badClient[0];
// i guess banning mods or admins isn't the best idea?
if (badClient.uType !== 'user') {
server.reply({
cmd: 'warn',
@ -35,23 +40,27 @@ exports.run = async (core, server, socket, data) => {
return;
}
let clientHash = server.getSocketHash(badClient);
server._police.arrest(badClient.remoteAddress, clientHash);
// commit arrest record
server._police.arrest(badClient.remoteAddress, badClient.hash);
console.log(`${socket.nick} [${socket.trip}] banned ${targetNick} in ${socket.channel}`);
// notify normal users
server.broadcast({
cmd: 'info',
text: `Banned ${targetNick}`
}, { channel: socket.channel, uType: 'user' });
// notify mods
server.broadcast({
cmd: 'info',
text: `${socket.nick} banned ${targetNick} in ${socket.channel}, userhash: ${clientHash}`
text: `${socket.nick} banned ${targetNick} in ${socket.channel}, userhash: ${badClient.hash}`
}, { uType: 'mod' });
badClient.close();
// force connection closed
badClient.terminate();
// stats are fun
core.managers.stats.increment('users-banned');
};

View File

@ -8,15 +8,19 @@ exports.init = (core) => {
}
exports.run = async (core, server, socket, data) => {
// increase rate limit chance and ignore if not admin or mod
if (socket.uType == 'user') {
// ignore if not mod or admin
server._police.frisk(socket.remoteAddress, 10);
return;
}
// check user input
if (typeof data.nick !== 'string') {
return;
}
// find target user
let badClient = server.findSockets({ channel: socket.channel, nick: data.nick });
if (badClient.length === 0) {
@ -30,6 +34,7 @@ exports.run = async (core, server, socket, data) => {
badClient = badClient[0];
// likely dont need this, muting mods and admins is fine
if (badClient.uType !== 'user') {
server.reply({
cmd: 'warn',
@ -39,19 +44,21 @@ exports.run = async (core, server, socket, data) => {
return;
}
// store hash in mute list
let record = core.muzzledHashes[badClient.hash] = {
dumb:true
}
// store allies if needed
if(data.allies && Array.isArray(data.allies)){
record.allies = data.allies;
}
// notify mods
server.broadcast({
cmd: 'info',
text: `${socket.nick} muzzled ${data.nick} in ${socket.channel}, userhash: ${badClient.hash}`
}, { uType: 'mod' });
}
exports.requiredData = ['nick'];

View File

@ -1,19 +1,23 @@
/*
Description: Forces a change on the target socket's channel, then broadcasts event
Description: Forces a change on the target(s) socket's channel, then broadcasts event
*/
exports.run = async (core, server, socket, data) => {
if (socket.uType === 'user') {
// ignore if not mod or admin
// increase rate limit chance and ignore if not admin or mod
if (socket.uType == 'user') {
server._police.frisk(socket.remoteAddress, 10);
return;
}
// check user input
if (typeof data.nick !== 'string') {
if (typeof data.nick !== 'object' && !Array.isArray(data.nick)) {
return;
}
}
// find target user(s)
let badClients = server.findSockets({ channel: socket.channel, nick: data.nick });
if (badClients.length === 0) {
@ -25,6 +29,7 @@ exports.run = async (core, server, socket, data) => {
return;
}
// check if found targets are kickable, commit kick
let newChannel = '';
let kicked = [];
for (let i = 0, j = badClients.length; i < j; i++) {
@ -66,6 +71,7 @@ exports.run = async (core, server, socket, data) => {
text: `Kicked ${kicked.join(', ')}`
}, { channel: socket.channel, uType: 'user' });
// stats are fun
core.managers.stats.increment('users-kicked', kicked.length);
};

View File

@ -4,11 +4,14 @@
*/
exports.run = async (core, server, socket, data) => {
// increase rate limit chance and ignore if not admin or mod
if (socket.uType == 'user') {
// ignore if not mod or admin
server._police.frisk(socket.remoteAddress, 10);
return;
}
// check user input
if (typeof data.ip !== 'string' && typeof data.hash !== 'string') {
server.reply({
cmd: 'warn',
@ -18,8 +21,8 @@ exports.run = async (core, server, socket, data) => {
return;
}
// find target & remove mute status
let target;
if (typeof data.ip === 'string') {
target = getSocketHash(data.ip);
} else {
@ -28,11 +31,11 @@ exports.run = async (core, server, socket, data) => {
delete core.muzzledHashes[target];
// notify mods
server.broadcast({
cmd: 'info',
text: `${socket.nick} unmuzzled : ${target}`
}, { uType: 'mod' });
}
exports.info = {

View File

@ -3,11 +3,14 @@
*/
exports.run = async (core, server, socket, data) => {
// increase rate limit chance and ignore if not admin or mod
if (socket.uType == 'user') {
// ignore if not mod or admin
server._police.frisk(socket.remoteAddress, 10);
return;
}
// check user input
if (typeof data.ip !== 'string' && typeof data.hash !== 'string') {
server.reply({
cmd: 'warn',
@ -17,8 +20,8 @@ exports.run = async (core, server, socket, data) => {
return;
}
// find target
let mode, target;
if (typeof data.ip === 'string') {
mode = 'ip';
target = data.ip;
@ -27,24 +30,28 @@ exports.run = async (core, server, socket, data) => {
target = data.hash;
}
// remove arrest record
server._police.pardon(target);
// mask ip if used
if (mode === 'ip') {
target = server.getSocketHash(target);
}
console.log(`${socket.nick} [${socket.trip}] unbanned ${target} in ${socket.channel}`);
// reply with success
server.reply({
cmd: 'info',
text: `Unbanned ${target}`
}, socket);
// notify mods
server.broadcast({
cmd: 'info',
text: `${socket.nick} unbanned: ${target}`
}, { uType: 'mod' });
// stats are fun
core.managers.stats.decrement('users-banned');
};