Compare commits

..

No commits in common. "71c2f1b3d67d7125a2d5b77c68ae3a64fe100db2" and "409de19e76957e69b80bc37cc620ee127c84ae49" have entirely different histories.

29 changed files with 139 additions and 382 deletions

9
.gitignore vendored
View File

@ -13,12 +13,3 @@ prisma/*.sqlite
# JWT token keypair
mppkey
mppkey.pub
# Logs
/logs
# VSCode
/.vscode
# MacOS
/.DS_Store

View File

@ -66,7 +66,9 @@ This has always been the future intention of this project.
## TODO
- Change `socketsBySocketID` to `socketsByUUID`
- Fully implement and test tags
- Tags are sent to clients now
- Check if tags are sent to everyone
- Channel data saving
- Permission groups and permissions
- Probable permission groups: owner, admin, mod, trialmod, default
@ -102,12 +104,6 @@ This has always been the future intention of this project.
- Check for different messages?
- Check for URL?
- Notifications for server-generated XSS?
- Migrate to PostgreSQL instead of SQLite
- Likely a low priority, we use prisma anyway, but it would be nice to have a server
- Implement user caching
- Skip redis due to the infamous licensing issues
- Probably use a simple in-memory cache
- Likely store with leveldb or JSON
## How to run

BIN
bun.lockb

Binary file not shown.

View File

@ -1,11 +1,8 @@
# Channel config file
# Which channels to keep loaded on startup
forceLoad:
- lobby
- test/awkward
# Default settings for lobbies
lobbySettings:
lobby: true
chat: true
@ -13,35 +10,19 @@ lobbySettings:
visible: true
color: "#73b3cc"
color2: "#273546"
# Default settings for regular channels
defaultSettings:
chat: true
crownsolo: false
color: "#3b5054"
color2: "#001014"
visible: true
# Regexes to match against channel names to determine whether they are lobbies or not
# This doesn't affect the `isRealLobby` function, which is used to determine "classic" lobbies
lobbyRegexes:
- ^lobby[0-9][0-9]$
- ^lobby[0-9]$
- ^lobby$
- ^lobbyNaN$
- ^test/.+$
# Backdoor channel ID for bypassing the lobby limit
lobbyBackdoor: lolwutsecretlobbybackdoor
# Channel ID for where you get sent when you join a channel that is full/you get banned/etc
fullChannel: test/awkward
# Whether to send the channel limit to the client
sendLimit: false
# Whether to give the crown to the user who had it when they rejoin
chownOnRejoin: true
# Time in milliseconds to wait before destroying an empty channel
channelDestroyTimeout: 1000

View File

@ -10,8 +10,6 @@ maxDuration: 60000
# The default duration of a notification in milliseconds, if not specified.
defaultDuration: 7000
# The target ID to use to send notifications to every socket on the server.
# The target used to send notifications to every socket on the server.
# This is not used for the "target" parameter, instead this is for "targetChannel"/"targetUser".
# This will allow notifications to be sent to every socket on the server.
# This is configurable because it's potentially dangerous to allow every
allTarget: all

View File

@ -1,12 +0,0 @@
global:
scrape_interval: 15s
scrape_configs:
- job_name: prometheus
scrape_interval: "5s"
static_configs:
- targets: ["localhost:9090"]
- job_name: mpp
static_configs:
- targets: ["192.168.1.24:9100"]

View File

@ -37,15 +37,14 @@ enableAdminEval: true
# The token validation scheme. Valid values are "none", "jwt" and "uuid".
# This server will still validate existing tokens generated with other schemes if not set to "none", mimicking MPP.net's server.
# This is set to "none" by default because MPP.com does not have a token system.
tokenAuth: jwt
tokenAuth: none
# The browser challenge scheme. Valid options are "none", "obf" and "basic".
# This is to change what is sent in the "b" message.
# "none" will disable the browser challenge,
# "obf" will sent an obfuscated function to the client,
# and "basic" will just send a simple function that expects a boolean.
# FIXME Note that "obf" is not implemented yet, and has undefined behavior.
browserChallenge: basic
browserChallenge: none
# Scheme for generating user IDs.
# Valid options are "random", "sha256", "mpp" and "uuid".

View File

@ -1 +0,0 @@
enableLogFiles: true

View File

@ -6,10 +6,6 @@
"keywords": [],
"author": "Hri7566",
"license": "ISC",
"scripts": {
"start": "bun run src/index.ts",
"dev": "bun run src/index.ts --watch"
},
"dependencies": {
"@prisma/client": "5.17.0",
"@t3-oss/env-core": "^0.6.1",
@ -21,7 +17,6 @@
"jsonwebtoken": "^9.0.2",
"keccak": "^2.1.0",
"nunjucks": "^3.2.4",
"prom-client": "^15.1.3",
"unique-names-generator": "^4.7.1",
"yaml": "^2.5.0",
"zod": "^3.23.8"

View File

@ -1,2 +0,0 @@
#!/usr/bin/env bash
bun .

View File

@ -68,7 +68,7 @@ export class Channel extends EventEmitter {
}
private async save() {
//this.logger.debug("Saving channel data");
this.logger.debug("Saving channel data");
try {
const info = this.getInfo();
@ -78,16 +78,16 @@ export class Channel extends EventEmitter {
flags: JSON.stringify(this.flags)
};
//this.logger.debug("Channel data to save:", data);
this.logger.debug("Channel data to save:", data);
await saveChannel(this.getID(), data);
} catch (err) {
this.logger.warn("Error saving channel data:", err);
this.logger.debug("Error saving cannel:", err);
}
}
private async load() {
//this.logger.debug("Loading saved data");
this.logger.debug("Loading saved data");
try {
const data = await getSavedChannel(this.getID());
if (data) {
@ -100,11 +100,9 @@ export class Channel extends EventEmitter {
forceloadChannel(this.getID());
}
//this.logger.debug("Loaded channel data:", data);
this.emit("update", this);
this.logger.debug("Loaded channel data:", data);
} catch (err) {
this.logger.error("Error loading channel data:", err);
this.logger.debug("Error loading channel data:", err);
}
}
} catch (err) { }
@ -127,7 +125,7 @@ export class Channel extends EventEmitter {
) {
super();
this.logger = new Logger("Channel - " + _id, "logs/channel");
this.logger = new Logger("Channel - " + _id);
this.settings = {};
// Copy default settings
@ -211,13 +209,7 @@ export class Channel extends EventEmitter {
}
if (this.ppl.length == 0 && !this.stays) {
if (config.channelDestroyTimeout) {
setTimeout(() => {
this.destroy();
}, config.channelDestroyTimeout);
} else {
this.destroy();
}
}
});
@ -254,21 +246,17 @@ export class Channel extends EventEmitter {
.replace(/(\p{Mc}{5})\p{Mc}+/gu, "$1")
.trim();
const part = socket.getParticipant() as Participant;
let outgoing: ClientEvents["a"] = {
m: "a",
a: msg.message,
t: Date.now(),
p: part
p: socket.getParticipant() as Participant
};
this.sendArray([outgoing]);
this.chatHistory.push(outgoing);
await saveChatHistory(this.getID(), this.chatHistory);
this.logger.info(`${part._id} ${part.name}: ${outgoing.a}`);
if (msg.message.startsWith("/")) {
this.emit("command", msg, socket);
}
@ -385,10 +373,6 @@ export class Channel extends EventEmitter {
}
]);
});
this.on("set owner id", id => {
this.setFlag("owner_id", id);
});
}
/**
@ -466,7 +450,7 @@ export class Channel extends EventEmitter {
// Set the verified settings
for (const key of Object.keys(validatedSet)) {
//this.logger.debug(`${key}: ${(validatedSet as any)[key]}`);
this.logger.debug(`${key}: ${(validatedSet as any)[key]}`);
if ((validatedSet as any)[key] === false) continue;
(this.settings as any)[key] = (set as any)[key];
}
@ -842,17 +826,15 @@ export class Channel extends EventEmitter {
let sentSocketIDs = new Array<string>();
for (const p of this.ppl) {
socketLoop: for (const sock of socketsBySocketID.values()) {
this.logger.debug(`Socket ${sock.getUUID()}`);
if (sock.isDestroyed()) continue socketLoop;
if (!sock.socketID) continue socketLoop;
if (sock.getUUID() == socket.getUUID()) continue socketLoop;
if (sock.getParticipantID() != p.id) continue socketLoop;
//if (socket.getParticipantID() == part.id) continue socketLoop;
if (sentSocketIDs.includes(sock.socketID)) continue socketLoop;
sock.sendArray([clientMsg]);
sentSocketIDs.push(sock.socketID);
socketLoop: for (const socket of socketsBySocketID.values()) {
if (socket.isDestroyed()) continue socketLoop;
if (!socket.socketID) continue socketLoop;
if (socket.getParticipantID() != p.id) continue socketLoop;
if (socket.getParticipantID() == part.id) continue socketLoop;
if (sentSocketIDs.includes(socket.socketID))
continue socketLoop;
socket.sendArray([clientMsg]);
sentSocketIDs.push(socket.socketID);
}
}
}

View File

@ -10,7 +10,6 @@ interface ChannelConfig {
fullChannel: string;
sendLimit: boolean;
chownOnRejoin: boolean;
channelDestroyTimeout: number;
}
export const config = loadConfig<ChannelConfig>("config/channels.yml", {
@ -35,6 +34,5 @@ export const config = loadConfig<ChannelConfig>("config/channels.yml", {
lobbyBackdoor: "lolwutsecretlobbybackdoor",
fullChannel: "test/awkward",
sendLimit: false,
chownOnRejoin: true,
channelDestroyTimeout: 1000
chownOnRejoin: true
});

View File

@ -1,15 +1,9 @@
/**
* MPP Server 2
* for https://www.multiplayerpiano.dev/
* Written by Hri7566
* This code is licensed under the GNU General Public License v3.0.
* Please see `./LICENSE` for more information.
* for mpp.dev
* by Hri7566
*/
/**
* Main entry point for the server
**/
// There are a lot of unhinged bs comments in this repo
// Pay no attention to the ones that cuss you out
@ -17,22 +11,15 @@
import "./ws/server";
import { loadForcedStartupChannels } from "./channel/forceLoad";
import { Logger } from "./util/Logger";
// docker hates this next one
import { startReadline } from "./util/readline";
// wrapper for some reason
export function startServer() {
// Let's construct an entire object just for one thing to be printed
// and then keep it in memory for the entirety of runtime
const logger = new Logger("Main");
logger.info("Forceloading startup channels...");
loadForcedStartupChannels();
// Let's construct an entire object just for one thing to be printed
// and then keep it in memory for the entirety of runtime
const logger = new Logger("Main");
logger.info("Forceloading startup channels...");
loadForcedStartupChannels();
// Break the console
startReadline();
// This literally breaks editors and they stick all the imports here instead of at the top
import "./util/readline";
// Nevermind, two things are printed
logger.info("Ready");
}
startServer();
// Nevermind we use it twice
logger.info("Ready");

View File

@ -1,19 +1,8 @@
import EventEmitter from "events";
import { padNum, unimportant } from "./helpers";
import { join } from "path";
import { existsSync, mkdirSync, appendFile, writeFile } from "fs";
import { config } from "./utilConfig";
export const logEvents = new EventEmitter();
const logFolder = "./logs";
// https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python
const logRegex = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;
if (config.enableLogFiles) {
if (!existsSync(logFolder)) mkdirSync(logFolder);
}
/**
* A logger that doesn't fuck with the readline prompt
* timestamps are likely wrong because of js timezones
@ -25,7 +14,7 @@ export class Logger {
* @param method The method from `console` to use
* @param args The data to print
**/
private static log(method: string, logPath: string, ...args: any[]) {
private static log(method: string, ...args: any[]) {
// Un-fuck the readline prompt
process.stdout.write("\x1b[2K\r");
@ -44,23 +33,6 @@ export class Logger {
// Emit the log event for remote consoles
logEvents.emit("log", method, unimportant(this.getDate()), unimportant(this.getHHMMSSMS()), args);
if (config.enableLogFiles) {
// Write to file
(async () => {
const orig = unimportant(this.getDate()) + " " + unimportant(this.getHHMMSSMS()) + " " + args.join(" ") + "\n"
const text = orig.replace(logRegex, "");
if (!existsSync(logPath)) {
writeFile(logPath, text, (err) => {
if (err) console.error(err);
});
} else {
appendFile(logPath, text, (err) => {
if (err) console.error(err);
});
}
})();
}
}
/**
@ -90,19 +62,14 @@ export class Logger {
return new Date().toISOString().split("T")[0];
}
public logPath: string;
constructor(public id: string, logdir: string = logFolder) {
if (!existsSync(logdir)) mkdirSync(logdir);
this.logPath = join(logdir, `${encodeURIComponent(this.id)}.log`);
}
constructor(public id: string) { }
/**
* Print an info message
* @param args The data to print
**/
public info(...args: any[]) {
Logger.log("log", this.logPath, `[${this.id}]`, `\x1b[34m[info]\x1b[0m`, ...args);
Logger.log("log", `[${this.id}]`, `\x1b[34m[info]\x1b[0m`, ...args);
}
/**
@ -110,7 +77,7 @@ export class Logger {
* @param args The data to print
**/
public error(...args: any[]) {
Logger.log("error", this.logPath, `[${this.id}]`, `\x1b[31m[error]\x1b[0m`, ...args);
Logger.log("error", `[${this.id}]`, `\x1b[31m[error]\x1b[0m`, ...args);
}
/**
@ -118,7 +85,7 @@ export class Logger {
* @param args The data to print
**/
public warn(...args: any[]) {
Logger.log("warn", this.logPath, `[${this.id}]`, `\x1b[33m[warn]\x1b[0m`, ...args);
Logger.log("warn", `[${this.id}]`, `\x1b[33m[warn]\x1b[0m`, ...args);
}
/**
@ -126,6 +93,6 @@ export class Logger {
* @param args The data to print
**/
public debug(...args: any[]) {
Logger.log("debug", this.logPath, `[${this.id}]`, `\x1b[32m[debug]\x1b[0m`, ...args);
Logger.log("debug", `[${this.id}]`, `\x1b[32m[debug]\x1b[0m`, ...args);
}
}

View File

@ -1,5 +1,6 @@
import { existsSync, readFileSync, writeFileSync } from "fs";
import { parse, stringify } from "yaml";
import { z } from "zod";
/**
* This file uses the synchronous functions from the fs
@ -62,7 +63,6 @@ export function loadConfig<T>(configPath: string, defaultConfig: T): T {
return config as T;
} else {
// Write default config to disk and use that
//logger.warn(`Config file "${configPath}" not found, writing default config to disk`);
writeConfig(configPath, defaultConfig);
return defaultConfig as T;
}

View File

@ -35,9 +35,6 @@ export function createUserID(ip: string) {
.update("::ffff:" + ip + env.SALT)
.digest("hex")
.substring(0, 24);
} else {
// Fallback if someone typed random garbage in the config
return createID();
}
}

View File

@ -3,32 +3,23 @@ import logger from "./logger";
import Command from "./Command";
import "./commands";
export let rl: readline.Interface;
// Turned into a function so the import isn't in a weird spot
export function startReadline() {
rl = readline.createInterface({
export const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
});
rl.setPrompt("mpps> ");
rl.prompt();
rl.setPrompt("mpps> ");
rl.prompt();
rl.on("line", async line => {
rl.on("line", async line => {
const out = await Command.handleCommand(line);
logger.info(out);
rl.prompt();
});
});
rl.on("SIGINT", () => {
rl.on("SIGINT", () => {
process.exit();
});
});
// Fucking cringe but it works
(globalThis as unknown as any).rl = rl;
}
export function stopReadline() {
rl.close();
}
// Fucking cringe but it works
(globalThis as unknown as any).rl = rl;

View File

@ -1,5 +0,0 @@
import { loadConfig } from "./config";
export const config = loadConfig("config/util.yml", {
enableLogFiles: true
});

View File

@ -11,71 +11,65 @@
* or, you know, maybe I could log their user agent
* and IP address instead sometime in the future.
*/
import { Logger } from "../util/Logger";
const logger = new Logger("Socket Gateway");
export class Gateway {
// Whether we have correctly processed this socket's hi message
public hasProcessedHi = false; // implemented
public hasProcessedHi = false;
// Whether they have sent the MIDI devices message
public hasSentDevices = false; // implemented
public hasSentDevices = false;
// Whether they have sent a token
public hasSentToken = false; // implemented
public hasSentToken = false;
// Whether their token is valid
public isTokenValid = false; // implemented
public isTokenValid = false;
// Their user agent, if sent
public userAgent = ""; // TODO
public userAgent = "";
// Whether they have moved their cursor
public hasCursorMoved = false; // implemented
public hasCursorMoved = false;
// Whether they sent a cursor message that contained numbers instead of stringified numbers
public isCursorNotString = false; // implemented
public isCursorNotString = false;
// The last time they sent a ping message
public lastPing = Date.now(); // implemented
public lastPing = Date.now();
// Whether they have joined any channel
public hasJoinedAnyChannel = false; // implemented
public hasJoinedAnyChannel = false;
// Whether they have joined a lobby
public hasJoinedLobby = false; // implemented
// Whether they have joined the lobby
public hasJoinedLobby = false;
// Whether they have made a regular non-websocket request to the HTTP server
// probably useful for checking if they are actually on the site
// Maybe not useful if cloudflare is being used
// In that scenario, templating wouldn't work, either
public hasConnectedToHTTPServer = false; // implemented
public hasConnectedToHTTPServer = false;
// Various chat message flags
public hasSentChatMessage = false; // implemented
public hasSentChatMessageWithCapitalLettersOnly = false; // implemented
public hasSentChatMessageWithInvisibleCharacters = false; // implemented
public hasSentChatMessageWithEmoji = false; // implemented
public hasSentChatMessage = false;
public hasSentChatMessageWithCapitalLettersOnly = false;
public hasSentChatMessageWithInvisibleCharacters = false;
public hasSentChatMessageWithEmoji = false;
// Whehter or not the user has played the piano in this session
public hasPlayedPianoBefore = false; // implemented
public hasPlayedPianoBefore = false;
// Whether the user has sent a channel list subscription request, a.k.a. opened the channel list
public hasOpenedChannelList = false; // implemented
public hasOpenedChannelList = false;
// Whether the user has changed their name/color this session (not just changed from default)
public hasChangedName = false; // implemented
public hasChangedColor = false; // implemented
public hasChangedName = false;
public hasChangedColor = false;
// Whether the user has sent
public hasSentCustomNoteData = false;
// Whether they sent an admin message that was invalid (wrong password, etc)
public hasSentInvalidAdminMessage = false; // implemented
public hasSentInvalidAdminMessage = false;
// Whether or not they have passed the b message
public hasCompletedBrowserChallenge = false; // implemented
public dump() {
return JSON.stringify(this, undefined, 4);
}
public hasCompletedBrowserChallenge = false;
}

View File

@ -146,7 +146,7 @@ export class Socket extends EventEmitter {
// Basic function
this.sendArray([{
m: "b",
code: `~return btoa(JSON.stringify([true, navigator.userAgent]));`
code: `~return true;`
}]);
} else if (config.browserChallenge == "obf") {
// Obfuscated challenge building
@ -183,7 +183,7 @@ export class Socket extends EventEmitter {
}
/**
* Move this socket to a channel
* Move this participant to a channel
* @param _id Target channel ID
* @param set Channel settings, if the channel is instantiated
* @param force Whether to make this socket join regardless of channel properties
@ -239,17 +239,6 @@ export class Socket extends EventEmitter {
// Make them join the new channel
channel.join(this, force);
}
// Gateway stuff
this.gateway.hasJoinedAnyChannel = true;
const ch = this.getCurrentChannel();
if (ch) {
if (ch.isLobby()) {
this.gateway.hasJoinedLobby = true;
}
}
}
public admin = new EventEmitter();

View File

@ -16,8 +16,6 @@ export const plus_ls: ServerEventListener<"+ls"> = {
if (!socket.rateLimits.normal["+ls"].attempt()) return;
}
socket.gateway.hasOpenedChannelList = true;
socket.subscribeToChannelList();
}
};

View File

@ -1,28 +1,4 @@
import { Socket } from "../../../Socket";
import { ServerEventListener, ServerEvents } from "../../../../util/types";
// https://stackoverflow.com/questions/64509631/is-there-a-regex-to-match-all-unicode-emojis
const emojiRegex = /(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/g;
function populateSocketChatGatewayFlags(msg: ServerEvents["a"], socket: Socket) {
socket.gateway.hasSentChatMessage = true;
if (msg.message.toUpperCase() == msg.message) {
socket.gateway.hasSentChatMessageWithCapitalLettersOnly = true;
}
if (msg.message.includes("\u034f") || msg.message.includes("\u200b")) {
socket.gateway.hasSentChatMessageWithInvisibleCharacters = true;
}
if (msg.message.match(/[^\x00-\x7f]/gm)) {
socket.gateway.hasSentChatMessageWithInvisibleCharacters = true;
}
if (msg.message.match(emojiRegex)) {
socket.gateway.hasSentChatMessageWithEmoji = true;
}
}
import { ServerEventListener } from "../../../../util/types";
export const a: ServerEventListener<"a"> = {
id: "a",
@ -31,14 +7,9 @@ export const a: ServerEventListener<"a"> = {
const flags = socket.getUserFlags();
if (!flags) return;
if (typeof msg.message !== "string") return;
// Why did I write this statement so weird
if (!flags["no chat rate limit"] || flags["no chat rate limit"] == 0)
if (!socket.rateLimits?.normal.a.attempt()) return;
populateSocketChatGatewayFlags(msg, socket);
const ch = socket.getCurrentChannel();
if (!ch) return;

View File

@ -9,15 +9,8 @@ export const admin_message: ServerEventListener<"admin message"> = {
if (socket.rateLimits)
if (!socket.rateLimits.normal["admin message"].attempt()) return;
if (typeof msg.password !== "string") {
socket.gateway.hasSentInvalidAdminMessage = true;
return;
}
if (msg.password !== env.ADMIN_PASS) {
socket.gateway.hasSentInvalidAdminMessage = true;
return;
}
if (typeof msg.password !== "string") return;
if (msg.password !== env.ADMIN_PASS) return;
// Probably shouldn't be using password auth in 2024
// Maybe I'll setup a dashboard instead some day

View File

@ -17,20 +17,10 @@ export const hi: ServerEventListener<"hi"> = {
// Browser challenge
if (config.browserChallenge == "basic") {
try {
if (typeof msg.code !== "string") return;
const code = atob(msg.code);
const arr = JSON.parse(code);
if (typeof msg.code !== "boolean") return;
if (arr[0] === true) {
if (msg.code === true) {
socket.gateway.hasCompletedBrowserChallenge = true;
if (typeof arr[1] === "string") {
socket.gateway.userAgent = arr[1];
}
}
} catch (err) {
logger.warn("Unable to parse basic browser challenge code:", err);
}
} else if (config.browserChallenge == "obf") {
// TODO
@ -44,14 +34,11 @@ export const hi: ServerEventListener<"hi"> = {
if (config.tokenAuth !== "none") {
if (typeof msg.token !== "string") {
socket.gateway.hasSentToken = true;
// Get a saved token
token = await getToken(socket.getUserID());
if (typeof token !== "string") {
// Generate a new one
token = await createToken(socket.getUserID(), socket.gateway);
socket.gateway.isTokenValid = true;
if (typeof token !== "string") {
logger.warn(`Unable to generate token for user ${socket.getUserID()}`);
@ -67,7 +54,6 @@ export const hi: ServerEventListener<"hi"> = {
//return;
} else {
token = msg.token;
socket.gateway.isTokenValid = true;
}
}
}

View File

@ -13,21 +13,11 @@ export const m: ServerEventListener<"m"> = {
let x = msg.x;
let y = msg.y;
// Parse cursor position if it's strings
if (typeof msg.x == "string") {
x = parseFloat(msg.x);
} else {
socket.gateway.isCursorNotString = true;
}
// Make it numbers
if (typeof msg.x == "string") x = parseFloat(msg.x);
if (typeof msg.y == "string") y = parseFloat(msg.y);
if (typeof msg.y == "string") {
y = parseFloat(msg.y);
} else {
socket.gateway.isCursorNotString = true;
}
// Relocate the laggy microscopic speck
// Move the laggy piece of shit
socket.setCursorPos(x, y);
socket.gateway.hasCursorMoved = true;
}
};

View File

@ -11,8 +11,6 @@ export const n: ServerEventListener<"n"> = {
if (!Array.isArray(msg.n)) return;
if (typeof msg.t !== "number") return;
socket.gateway.hasPlayedPianoBefore = true;
// This should've been here months ago
const channel = socket.getCurrentChannel();
if (!channel) return;

View File

@ -12,8 +12,6 @@ export const t: ServerEventListener<"t"> = {
if (typeof msg.e !== "number") return;
}
socket.gateway.lastPing = Date.now();
// Pong
socket.sendArray([
{

View File

@ -1,21 +1,20 @@
import { ServerEventListener } from "../../../../util/types";
import { config } from "../../../usersConfig";
export const userset: ServerEventListener<"userset"> = {
id: "userset",
callback: async (msg, socket) => {
// Change username/color
if (!socket.rateLimits?.chains.userset.attempt()) return;
if (typeof msg.set.name !== "string" && typeof msg.set.color !== "string") return;
if (typeof msg.set.name == "string") {
socket.gateway.hasChangedName = true;
}
if (typeof msg.set.color == "string" && config.enableColorChanging) {
socket.gateway.hasChangedColor = true;
}
// You can disable color in the config because
// Brandon's/jacored's server doesn't allow color changes,
// and that's the OG server, but folks over at MPP.net
// said otherwise because they're dumb roleplayers
// or something and don't understand the unique value
// of the fishing bot and how it allows you to change colors
// without much control, giving it the feeling of value...
// Kinda reminds me of crypto.
// Also, Brandon's server had color changing on before.
if (!msg.set.name && !msg.set.color) return;
socket.userset(msg.set.name, msg.set.color);
}
};

View File

@ -7,14 +7,9 @@ import { Socket, socketsBySocketID } from "./Socket";
import env from "../util/env";
import { getMOTD } from "../util/motd";
import nunjucks from "nunjucks";
import { metrics } from "../util/metrics";
const logger = new Logger("WebSocket Server");
// ip -> timestamp
// for checking if they visited the site and are also connected to the websocket
const httpIpCache = new Map<string, number>();
/**
* Get a rendered version of the index file
* @returns Response with html in it
@ -44,15 +39,17 @@ export const app = Bun.serve<{ ip: string }>({
fetch: (req, server) => {
const reqip = server.requestIP(req);
if (!reqip) return;
const ip = req.headers.get("x-forwarded-for") || reqip.address;
// Upgrade websocket connections
if (server.upgrade(req, { data: { ip } })) {
return;
if (
server.upgrade(req, {
data: {
ip
}
httpIpCache.set(ip, Date.now());
})
) {
return;
} else {
const url = new URL(req.url).pathname;
// lol
@ -70,55 +67,37 @@ export const app = Bun.serve<{ ip: string }>({
// Time for unreadable blocks of confusion
try {
// Is it a file?
if (fs.lstatSync(file).isFile()) {
// Read the file
const data = Bun.file(file);
// Return the file
if (data) {
return new Response(data);
} else {
return getIndex();
}
} else {
// Return the index file, since it's a channel name or something
return getIndex();
}
} catch (err) {
// Return the index file as a coverup of our extreme failure
return getIndex();
}
}
},
websocket: {
open: ws => {
// swimming in the pool
// We got one!
const socket = new Socket(ws, createSocketID());
// Reel 'em in...
(ws as unknown as any).socket = socket;
// logger.debug("Connection at " + socket.getIP());
// Let's put it in the dinner bucket.
if (socket.socketID == undefined) {
socket.socketID = createSocketID();
}
socketsBySocketID.set(socket.socketID, socket);
const ip = socket.getIP();
if (httpIpCache.has(ip)) {
const date = httpIpCache.get(ip);
if (date) {
if (Date.now() - date < 1000 * 60) {
// They got the page and we were connected in under a minute
socket.gateway.hasConnectedToHTTPServer = true;
} else {
// They got the page and a long time has passed
httpIpCache.delete(ip);
}
}
}
},
message: (ws, message) => {