mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-07-17 21:59:20 +00:00
Merge branch 'v30'
This commit is contained in:
+25
-1
@@ -3,6 +3,7 @@ import express, { NextFunction, Request, Response } from "express";
|
||||
import rateLimit from "express-rate-limit";
|
||||
import http from "http";
|
||||
import ipAnonymize from "ip-anonymize";
|
||||
import { RateLimiter } from "limiter";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { WebSocket, WebSocketServer } from "ws";
|
||||
@@ -50,7 +51,7 @@ export async function startWorker() {
|
||||
const server = http.createServer(app);
|
||||
const wss = new WebSocketServer({
|
||||
noServer: true,
|
||||
maxPayload: 2 * 1024 * 1024,
|
||||
maxPayload: 1024 * 1024, // 1MB
|
||||
});
|
||||
|
||||
const gm = new GameManager(config, log);
|
||||
@@ -289,6 +290,11 @@ export async function startWorker() {
|
||||
: // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
||||
forwarded || req.socket.remoteAddress || "unknown";
|
||||
|
||||
if (!getWsIpLimiter(ip).tryRemoveTokens(1)) {
|
||||
ws.close(1008, "Rate limit exceeded");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Parse and handle client messages
|
||||
const parsed = ClientMessageSchema.safeParse(
|
||||
@@ -610,3 +616,21 @@ function generateGameIdForWorker(): GameID | null {
|
||||
log.warn(`Failed to generate game ID for worker ${workerId}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Per-IP rate limiter for pre-join WebSocket messages.
|
||||
// Prevents unauthenticated connections from spamming messages
|
||||
// (e.g. pings) before joining a game.
|
||||
const wsIpLimiters = new Map<string, RateLimiter>();
|
||||
function getWsIpLimiter(ip: string): RateLimiter {
|
||||
let limiter = wsIpLimiters.get(ip);
|
||||
if (!limiter) {
|
||||
limiter = new RateLimiter({
|
||||
tokensPerInterval: 5,
|
||||
interval: "second",
|
||||
});
|
||||
wsIpLimiters.set(ip, limiter);
|
||||
}
|
||||
return limiter;
|
||||
}
|
||||
// Clean up stale IP limiters every 10 minutes
|
||||
setInterval(() => wsIpLimiters.clear(), 10 * 60 * 1000);
|
||||
|
||||
Reference in New Issue
Block a user