From 7014be3e25fcffea3dee83ae96deb393d0f45168 Mon Sep 17 00:00:00 2001 From: Holly Date: Sat, 20 Apr 2024 17:20:13 +0100 Subject: [PATCH] cap the amount of pings users are allowed to send per second --- server/index.ts | 24 ++++++++++++++++++------ server/objects/User.ts | 8 +++++++- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/server/index.ts b/server/index.ts index 69b3192..1f6ff65 100644 --- a/server/index.ts +++ b/server/index.ts @@ -54,7 +54,8 @@ server.on("connection", (socket) => { return; } const username = reader.readShortString(); - let page = reader.readString().toLowerCase().replace(".htm", "").replace(".html", ""); + const rawURL = reader.readString(); + let page = rawURL.toLowerCase().replace(".htm", "").replace(".html", ""); if (page === "index") { page = ""; } @@ -70,7 +71,7 @@ server.on("connection", (socket) => { for (const otherUser of usersOnPage) { usersToSend.writeUInt(otherUser.id).writeShortString(otherUser.username).writeFloat(otherUser.cursorX).writeInt(otherUser.cursorY); } - user = users.set(myUUID, new User(socket, username, page)); + user = users.set(myUUID, new User(socket, username, page, rawURL)); sendToAllButSelf(user, createWriter(Endian.LE, 6 + username.length).writeByte(MessageType.ClientJoined).writeUInt(user.id).writeShortString(username).toBuffer()); user.send(usersToSend.toBuffer()); break; @@ -86,10 +87,21 @@ server.on("connection", (socket) => { } case MessageType.Ping: { - const cursorX = reader.readFloat(); - const cursorY = reader.readInt(); - const packet = createWriter(Endian.LE, 9).writeByte(MessageType.Ping).writeFloat(cursorX).writeInt(cursorY).toBuffer(); - sendToAll(user, packet); + if (user === undefined) { + return; + } + + if ((Date.now() - user.lastPingReset) >= 1000) { + user.allowedPings = 10; + } + + if (user.allowedPings > 0) { + user.allowedPings--; + const cursorX = reader.readFloat(); + const cursorY = reader.readInt(); + const packet = createWriter(Endian.LE, 9).writeByte(MessageType.Ping).writeFloat(cursorX).writeInt(cursorY).toBuffer(); + sendToAll(user, packet); + } break; } } diff --git a/server/objects/User.ts b/server/objects/User.ts index 49132d9..d1372a3 100644 --- a/server/objects/User.ts +++ b/server/objects/User.ts @@ -7,14 +7,20 @@ export default class User { public readonly id:number; public readonly username:string; public readonly currentURL:string; + public readonly rawURL:string = ""; public cursorX:number = 0; public cursorY:number = 0; + public allowedPings:number; + public lastPingReset:number; - constructor(socket:WebSocket, username:string, currentURL:string) { + constructor(socket:WebSocket, username:string, currentURL:string, rawURL:string) { this.socket = socket; this.id = User.USER_IDS++; this.username = username; this.currentURL = currentURL; + this.rawURL = rawURL; + this.allowedPings = 10; + this.lastPingReset = Date.now(); } send(data:Buffer) {