Skip to content

Commit

Permalink
Merge pull request #26 from codergautam/adtest
Browse files Browse the repository at this point in the history
Basic ban system
  • Loading branch information
codergautam authored Jan 23, 2024
2 parents 337f930 + 0825596 commit 919e94f
Show file tree
Hide file tree
Showing 7 changed files with 134 additions and 9 deletions.
5 changes: 4 additions & 1 deletion server/src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ module.exports = {
// Secret key for the server, defaulting to 'server-secret' if not specified in the environment
serverSecret: process.env.SERVER_SECRET || 'server-secret',

// Moderation secret
moderationSecret: process.env.MODERATION_SECRET || 'moderation-secret',

// API endpoint URL, defaulting to 'http://localhost:8080' if not provided in the environment
apiEndpoint: process.env.API_ENDPOINT || 'http://localhost:8080',

Expand All @@ -31,7 +34,7 @@ module.exports = {
player: {
speed: 700,
radius: 100,
maxHealth: 120,
maxHealth: 80,
regeneration: 2,

// Player's viewport configuration
Expand Down
6 changes: 6 additions & 0 deletions server/src/game/Game.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const helpers = require('../helpers');
const config = require('../config');
const filter = require('leo-profanity');
const Types = require('./Types');
const { getBannedIps } = require('../moderation');
class Game {
constructor() {
this.entities = new Set();
Expand Down Expand Up @@ -86,6 +87,11 @@ class Game {

let { player } = client;
if (data.play && (!player || player.removed)) {
if(getBannedIps().includes(client.ip)) {
// close connection
client.socket.close();
return;
}
player = this.addPlayer(client, data);
}

Expand Down
2 changes: 1 addition & 1 deletion server/src/game/components/LevelSystem.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class LevelSystem {
},
[Types.Buff.Health]: {
level: 0,
step: 0.2,
step: 0.25,
max: 10,
buyable: true,
},
Expand Down
2 changes: 2 additions & 0 deletions server/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const Game = require('./game/Game');
const Loop = require('./utilities/Loop');
const Server = require('./network/Server');
const config = require('./config');
const {initModeration} = require('./moderation');

let app;
if (config.useSSL) {
Expand Down Expand Up @@ -55,6 +56,7 @@ function start() {
realPlayersCnt: [...game.players.values()].filter(p => !p.isBot).length,
}));
});
initModeration(game, app);

// Gameloop
const frameTime = 1000 / config.tickRate;
Expand Down
103 changes: 103 additions & 0 deletions server/src/moderation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
const config = require('./config');

const secret = config.moderationSecret;
let bannedIps = [];

async function listCommand(game) {
// list all users in game and their ip
const players = [];
for (const player of game.players.values()) {
if (player.isBot || !player.client) continue;
players.push({
id: player.id,
name: player.name,
ip: player.client.ip,
});
}

return {
players,
};
}

async function banIp(game, params) {
if(!params.ip) throw new Error('Missing ip param');
bannedIps.push(params.ip);
bannedIps = [...new Set(bannedIps)];

// ban ip
let playersKicked = 0;

for (const player of game.players.values()) {
if (player.isBot || !player.client) continue;
if (player.client.ip === params.ip) {
player.client.socket.close();
playersKicked++;
}
}

return {
playersKicked,
bannedIps
};
}



module.exports = {
initModeration: function (game, app) {
app.get('/moderation/:secret/:command', (res, req) => {
try {
const fullUrl = req.getUrl();
// split url into parts
const parts = fullUrl.split('/');

req.params = {
secret: parts[2],
command: parts[3],
}

// get query params
const query = req.getQuery();
if (query) {
const params = query.split('&');
for (const param of params) {
const [key, value] = param.split('=');
req.params[key] = value;
}
}

if (req.params.secret !== secret) {
res.writeStatus('403 Forbidden');
res.end();
return;
}

const command = req.params.command;
const cmds = [['list', listCommand], ['banip', banIp]];

if (!cmds.find(c => c[0] === command)) {
res.writeStatus('400 Bad Request');
res.end();
return;
}

cmds.find(c => c[0] === command)[1](game, req.params, app).then((json) => {
res.writeHeader('Content-Type', 'application/json');
res.writeStatus('200 OK');
res.end(JSON.stringify(json));
}).catch((e) => {
res.writeStatus('500 Internal Server Error');
res.end('Internal Server Error+<br><br>' + e?.message);
});
} catch (err) {
console.error(err);
res.writeStatus('500 Internal Server Error');
res.end('Internal Server Error+<br><br>' + err?.message);
}
});
},
getBannedIps: function () {
return bannedIps;
},
}
3 changes: 3 additions & 0 deletions server/src/network/Client.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ class Client {
this.game = game;
this.socket = socket;
this.id = socket.id;
this.ip = String.fromCharCode.apply(null, new Uint8Array(socket.getRemoteAddressAsText()));

console.log(`Client ${this.id} connected from ${this.ip}.`);
this.token = '';

this.spectator = new Spectator(this.game, this);
Expand Down
22 changes: 15 additions & 7 deletions server/src/network/Server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const uws = require('uWebSockets.js');
const { v4: uuidv4 } = require('uuid');
const Protocol = require('./protocol/Protocol');
const Client = require('./Client');
const { getBannedIps } = require('../moderation');

class Server {
constructor(game) {
Expand All @@ -19,7 +20,7 @@ class Server {
compression: uws.SHARED_COMPRESSOR,
idleTimeout: 32,
maxPayloadLength: 512,
upgrade:(res, req, context) => {
upgrade: (res, req, context) => {
res.upgrade({ id: uuidv4() },
req.getHeader('sec-websocket-key'),
req.getHeader('sec-websocket-protocol'),
Expand All @@ -29,6 +30,10 @@ class Server {
open: (socket) => {
console.log(`Client ${socket.id} connected.`);
const client = new Client(this.game, socket);
if (getBannedIps().includes(client.ip)) {
client.socket.close();
return;
}
this.addClient(client);
},
message: (socket, message) => {
Expand All @@ -39,13 +44,16 @@ class Server {
}
},
close: (socket, code) => {
const client = this.clients.get(socket.id);
client.isSocketClosed = true;
if (client.player && !client.player.removed) {
client.player.remove()
try {
const client = this.clients.get(socket.id);
client.isSocketClosed = true;
if (client.player && !client.player.removed) {
client.player.remove()
}
this.removeClient(client);
console.log(`Client disconnected with code ${code}.`);
} catch (e) {
}
this.removeClient(client);
console.log(`Client disconnected with code ${code}.`);
}
});
}
Expand Down

0 comments on commit 919e94f

Please sign in to comment.