Restore IPRateLimit

This commit is contained in:
Oborodzuki committed 2026-10-18 09:16:07 +08:00
1 parent 8ea0dc98e9
commit fee857075c
23 files changed
+31 -397

No files matched your search

+3 -50
View File
@@ -37,7 +37,6 @@ public sealed class TokenController : ControllerBase
private readonly AuthApiConfig _authApiConfig;
private readonly PortPoolService _portPool;
private readonly IDeltaListenerManager _deltaListenerManager;
private readonly IpRateLimitService _rateLimit;
public TokenController(
ILogger<TokenController> logger,
@@ -45,8 +44,7 @@ public sealed class TokenController : ControllerBase
AuthCacheService authCache,
IOptions<AuthApiConfig> authApiConfig,
PortPoolService portPool,
IDeltaListenerManager deltaListenerManager,
IpRateLimitService rateLimit)
IDeltaListenerManager deltaListenerManager)
{
_logger = logger;
_httpClientFactory = httpClientFactory;
@@ -54,7 +52,6 @@ public sealed class TokenController : ControllerBase
_authApiConfig = authApiConfig.Value;
_portPool = portPool;
_deltaListenerManager = deltaListenerManager;
_rateLimit = rateLimit;
}
[HttpPost]
@@ -79,43 +76,9 @@ public sealed class TokenController : ControllerBase
}
var clientIp = GetClientIp();
var friendCode = await GetFriendCodeAsync(eosToken, productUserId, clientIp);
var friendCode = await GetFriendCodeAsync(eosToken, productUserId);
var matchmakerToken = GenerateMatchmakerToken(productUserId);
// Over quota: never take a pool port for a join that cannot succeed
// — one port per blocked request would let a single IP drain the
// whole delta range. The client is pointed at the shared reject
// port instead, whose listener answers with the localized hint: no
// game, no black screen, one socket. Port 0 (fixed-port mode) means
// the main port, which rejects it the same way.
if (_rateLimit.IsLimited(clientIp, out var joinRetryAfter))
{
var rejectPort = await _deltaListenerManager.GetRateLimitRejectPortAsync();
if (rejectPort > 0 || !_portPool.IsEnabled)
{
_logger.LogWarning(
"TokenUser {Puid} {Ip} over the request rate limit, sent to reject port {Port} (retry in {Seconds}s).",
productUserId, clientIp, rejectPort,
(int)Math.Ceiling(joinRetryAfter.TotalSeconds));
return Ok(Convert.ToBase64String(JsonSerializer.SerializeToUtf8Bytes(new TokenResponse
{
Content = new TokenContent
{
ProductUserId = productUserId,
FriendCode = friendCode,
},
Hash = matchmakerToken,
Port = rejectPort,
})));
}
// No reject port available (pool exhausted): fall through to
// the normal path, which has its own full/exhausted handling.
_logger.LogWarning(
"TokenUser {Puid} {Ip} over the request rate limit but no reject port available, falling back to a normal port.",
productUserId, clientIp);
}
_authCache.Store(productUserId, matchmakerToken, friendCode, clientIp);
@@ -221,7 +184,7 @@ public sealed class TokenController : ControllerBase
private static string NormalizeIpString(IPAddress? ip)
=> ip?.IsIPv4MappedToIPv6 == true ? ip.MapToIPv4().ToString() : ip?.ToString() ?? "unknown";
private async Task<string> GetFriendCodeAsync(string eosToken, string productUserId, IPAddress? clientIp)
private async Task<string> GetFriendCodeAsync(string eosToken, string productUserId)
{
var cached = TryGetFriendCodeFromCache(productUserId);
if (cached != null)
@@ -232,16 +195,6 @@ public sealed class TokenController : ControllerBase
return cached;
}
// The join request is never rejected because of the Ip rate limit (the
// player is told in-game instead), so skip the outbound auth calls
// here — otherwise an IP could keep amplifying traffic to us.
if (_rateLimit.IsLimited(clientIp, out _))
{
_logger.LogWarning(
"TokenControllerFriendCode skipped for PUID={Puid}: {Ip} is over the request rate limit, using fallback",
productUserId, clientIp);
return GenerateFallbackFriendCode(productUserId);
}
var mode = _authApiConfig.Mode;
_logger.LogDebug("TokenControllerAuthApi mode: {Mode}", mode);
+1 -2
View File
@@ -39,6 +39,5 @@
"ban.notice.reason": "Grund: {0}",
"ban.notice.unban": "Entbannungszeit: {0}",
"ban.notice.unban_permanent": "Entbannungszeit: Dauerhaft",
"ban.notice.contact": "Bei Fragen wende dich an den Administrator.",
"ratelimit.too_frequent": "Zu viele Anfragen, bitte versuche es in {0} Minute(n) erneut."
"ban.notice.contact": "Bei Fragen wende dich an den Administrator."
}
+1 -2
View File
@@ -70,6 +70,5 @@
"ban.notice.reason": "Reason: {0}",
"ban.notice.unban": "Unban time: {0}",
"ban.notice.unban_permanent": "Unban time: Permanent",
"ban.notice.contact": "If you have any questions, please contact the administrator.",
"ratelimit.too_frequent": "Too many requests, please try again in {0} minute(s)."
"ban.notice.contact": "If you have any questions, please contact the administrator."
}
+1 -2
View File
@@ -37,6 +37,5 @@
"ban.notice.reason": "Motivo: {0}",
"ban.notice.unban": "Fin del baneo: {0}",
"ban.notice.unban_permanent": "Fin del baneo: Permanente",
"ban.notice.contact": "Si tienes dudas, contacta con un administrador.",
"ratelimit.too_frequent": "Demasiadas solicitudes, inténtalo de nuevo en {0} minuto(s)."
"ban.notice.contact": "Si tienes dudas, contacta con un administrador."
}
+1 -2
View File
@@ -37,6 +37,5 @@
"ban.notice.reason": "Dahilan: {0}",
"ban.notice.unban": "Oras ng pag-unban: {0}",
"ban.notice.unban_permanent": "Oras ng pag-unban: Permanente",
"ban.notice.contact": "Kung may tanong, makipag-ugnayan sa administrator.",
"ratelimit.too_frequent": "Masyaraming request, subukan muli sa {0} minuto."
"ban.notice.contact": "Kung may tanong, makipag-ugnayan sa administrator."
}
+1 -2
View File
@@ -39,6 +39,5 @@
"ban.notice.reason": "Raison : {0}",
"ban.notice.unban": "Débannissement : {0}",
"ban.notice.unban_permanent": "Débannissement : Permanent",
"ban.notice.contact": "En cas de question, contactez un administrateur.",
"ratelimit.too_frequent": "Trop de requêtes, veuillez réessayer dans {0} minute(s)."
"ban.notice.contact": "En cas de question, contactez un administrateur."
}
+1 -2
View File
@@ -37,6 +37,5 @@
"ban.notice.reason": "Cúis: {0}",
"ban.notice.unban": "Am dí-chosc: {0}",
"ban.notice.unban_permanent": "Am dí-chosc: Buan",
"ban.notice.contact": "Má tá ceist agat, déan teagmháil le riarthóir.",
"ratelimit.too_frequent": "Iarraidh ró-mhóra, bain triail eile as i {0} nóiméad."
"ban.notice.contact": "Má tá ceist agat, déan teagmháil le riarthóir."
}
+1 -2
View File
@@ -37,6 +37,5 @@
"ban.notice.reason": "Motivo: {0}",
"ban.notice.unban": "Sbanno: {0}",
"ban.notice.unban_permanent": "Sbanno: Permanente",
"ban.notice.contact": "Per qualsiasi domanda, contatta l'amministratore.",
"ratelimit.too_frequent": "Troppe richieste, riprova tra {0} minuto/i."
"ban.notice.contact": "Per qualsiasi domanda, contatta l'amministratore."
}
+1 -2
View File
@@ -39,6 +39,5 @@
"ban.notice.reason": "理由:{0}",
"ban.notice.unban": "BAN解除日時:{0}",
"ban.notice.unban_permanent": "BAN解除日時:永久",
"ban.notice.contact": "ご不明な点があれば管理者にお問い合わせください。",
"ratelimit.too_frequent": "リクエストが多すぎます。{0}分後に再試行してください。"
"ban.notice.contact": "ご不明な点があれば管理者にお問い合わせください。"
}
+1 -2
View File
@@ -39,6 +39,5 @@
"ban.notice.reason": "사유: {0}",
"ban.notice.unban": "차단 해제 시간: {0}",
"ban.notice.unban_permanent": "차단 해제 시간: 영구",
"ban.notice.contact": "문의 사항이 있으면 관리자에게 연락해 주세요.",
"ratelimit.too_frequent": "요청이 너무 많습니다. {0}분 후에 다시 시도해 주세요."
"ban.notice.contact": "문의 사항이 있으면 관리자에게 연락해 주세요."
}
+1 -2
View File
@@ -37,6 +37,5 @@
"ban.notice.reason": "Reden: {0}",
"ban.notice.unban": "Ontbantijd: {0}",
"ban.notice.unban_permanent": "Ontbantijd: Permanent",
"ban.notice.contact": "Neem bij vragen contact op met de beheerder.",
"ratelimit.too_frequent": "Te veel verzoeken, probeer het over {0} minuut/minuten opnieuw."
"ban.notice.contact": "Neem bij vragen contact op met de beheerder."
}
+1 -2
View File
@@ -39,6 +39,5 @@
"ban.notice.reason": "Motivo: {0}",
"ban.notice.unban": "Desbanimento: {0}",
"ban.notice.unban_permanent": "Desbanimento: Permanente",
"ban.notice.contact": "Em caso de dúvidas, contacte o administrador.",
"ratelimit.too_frequent": "Muitos pedidos, tente novamente em {0} minuto(s)."
"ban.notice.contact": "Em caso de dúvidas, contacte o administrador."
}
+1 -2
View File
@@ -37,6 +37,5 @@
"ban.notice.reason": "Motivo: {0}",
"ban.notice.unban": "Desbanimento: {0}",
"ban.notice.unban_permanent": "Desbanimento: Permanente",
"ban.notice.contact": "Em caso de dúvidas, contate o administrador.",
"ratelimit.too_frequent": "Muitas solicitações, tente novamente em {0} minuto(s)."
"ban.notice.contact": "Em caso de dúvidas, contate o administrador."
}
+1 -2
View File
@@ -39,6 +39,5 @@
"ban.notice.reason": "Причина: {0}",
"ban.notice.unban": "Время разбана: {0}",
"ban.notice.unban_permanent": "Время разбана: навсегда",
"ban.notice.contact": "Если у вас есть вопросы, обратитесь к администратору.",
"ratelimit.too_frequent": "Слишком много запросов, повторите попытку через {0} мин."
"ban.notice.contact": "Если у вас есть вопросы, обратитесь к администратору."
}
+1 -2
View File
@@ -70,6 +70,5 @@
"ban.notice.reason": "理由:{0}",
"ban.notice.unban": "解封时间:{0}",
"ban.notice.unban_permanent": "解封时间:永久",
"ban.notice.contact": "如有问题请联系管理员",
"ratelimit.too_frequent": "请求过于频繁请 {0} 分钟后重试"
"ban.notice.contact": "如有问题请联系管理员"
}
+1 -2
View File
@@ -53,6 +53,5 @@
"ban.notice.reason": "理由:{0}",
"ban.notice.unban": "解封時間:{0}",
"ban.notice.unban_permanent": "解封時間:永久",
"ban.notice.contact": "如有問題請聯絡管理員",
"ratelimit.too_frequent": "請求過於頻繁請 {0} 分鐘後重試"
"ban.notice.contact": "如有問題請聯絡管理員"
}
@@ -1,5 +1,4 @@
{
"ratelimit.too_frequent":"Too many requests, please try again in {0} minute(s).",
"command.error":"An error occurred while executing #{0}.",
"command.usage":"Usage: #{0}",
"command.help.list":"=== Commands ===",
@@ -1,5 +1,4 @@
{
"ratelimit.too_frequent":"请求过于频繁请 {0} 分钟后重试",
"command.error":"执行 #{0} 时发生错误。",
"command.usage":"用法:#{0}",
"command.help.list":"=== 指令列表 ===",
@@ -18,13 +18,4 @@ public interface IDeltaListenerManager
/// Stops and disposes the UDP listener on a specific port.
/// </summary>
ValueTask StopDeltaListenerAsync(int port);
/// <summary>
/// Returns the single shared UDP port that rate-limited (over-quota) join
/// requests are pointed at, binding it on first use. Its listener never
/// creates a player, it only sends the localized "too frequent" hint, so
/// an over-quota IP cannot consume a pool port per request.
/// </summary>
/// <returns>The reject port, or 0 when the delta pool is unavailable.</returns>
ValueTask<int> GetRateLimitRejectPortAsync();
}
@@ -6,7 +6,6 @@ using System.Threading;
using System.Threading.Tasks;
using Empostor.Api.Config;
using Empostor.Api.Events.Managers;
using Empostor.Api.Localization;
using Empostor.Api.Net;
using Empostor.Api.Net.Manager;
using Empostor.Api.Service;
@@ -37,8 +36,6 @@ namespace Empostor.Server.Net.Manager
private readonly PortPoolService _portPool;
private readonly IpGeolocationService _ipGeo;
private readonly ClientIdStore _clientIdStore;
private readonly IpRateLimitService _rateLimit;
private readonly ILocalizationService _language;
private int _idLast;
public ClientManager(
@@ -51,9 +48,7 @@ namespace Empostor.Server.Net.Manager
PlayerConnectStore playerConnectStore,
PortPoolService portPool,
IpGeolocationService ipGeo,
ClientIdStore clientIdStore,
IpRateLimitService rateLimit,
ILocalizationService language)
ClientIdStore clientIdStore)
{
_logger = logger;
_eventManager = eventManager;
@@ -66,8 +61,6 @@ namespace Empostor.Server.Net.Manager
_portPool = portPool;
_ipGeo = ipGeo;
_clientIdStore = clientIdStore;
_rateLimit = rateLimit;
_language = language;
_idLast = checked((int)_clientIdStore.GetLastId());
if (_compatibilityConfig.AllowFutureGameVersions)
@@ -171,14 +164,7 @@ namespace Empostor.Server.Net.Manager
{
// Dynamic delta mode: an active port that has no auth info
// bound to it is an unauthenticated UDP connection — reject
// it instead of admitting an anonymous client. An IP that is
// over the request quota gets the localized hint, everyone
// else the plain authentication notice.
if (IsRateLimited(null, clientIp, out var retryNoAuth))
{
await RejectRateLimitedAsync(connection, 0, language, retryNoAuth, NormalizeIp(clientIp));
return;
}
// it instead of admitting an anonymous client.
_logger.LogWarning(
"#{Id} {Name} │ port {Port} has no auth info │ {Ip} │ rejecting unauthenticated UDP connection",
@@ -188,13 +174,6 @@ namespace Empostor.Server.Net.Manager
}
// Port matched — cancel the allocation timeout
var limited = IsRateLimited(authInfo.ClientIp, clientIp, out var retryAfter);
if (limited)
{
await RejectRateLimitedAsync(connection, deltaPort, language, retryAfter, NormalizeIp(clientIp));
return;
}
_portPool.ConfirmPort(deltaPort);
// Mark the auth-cache entry as active so the inactivity
// timer never clears the port while the player is connected.
@@ -209,11 +188,6 @@ namespace Empostor.Server.Net.Manager
else
{
// Fixed-port mode: no auth binding, no PUID/FriendCode.
if (IsRateLimited(null, clientIp, out var retryAfter))
{
await RejectRateLimitedAsync(connection, 0, language, retryAfter, NormalizeIp(clientIp));
return;
}
_logger.LogInformation(
"#{Id} {Name} │ fixed port │ {Location} │ {Lang} │ {Platform}{Reactor}",
@@ -252,54 +226,6 @@ namespace Empostor.Server.Net.Manager
&& _clients.TryGetValue(client.Id, out var c)
&& ReferenceEquals(client, c);
// True when the IP already used up its TCP (HTTP) request quota. The
// IP of the HTTP handshake is preferred: behind a CDN that is the real
// player IP, while the UDP source address may be a proxy node.
private bool IsRateLimited(string? httpIp, IPAddress? udpIp, out TimeSpan retryAfter)
{
retryAfter = TimeSpan.Zero;
IPAddress? ip = null;
if (!string.IsNullOrEmpty(httpIp) && IPAddress.TryParse(httpIp, out var parsed))
{
ip = parsed;
}
ip ??= udpIp;
if (ip == null)
{
return false;
}
return _rateLimit.IsLimited(ip, out retryAfter);
}
// Over-quota players get a localized dialog instead of a black screen:
// the HTTP layer deliberately lets the join request through so the
// client reaches this point and can display the message.
private async ValueTask RejectRateLimitedAsync(
IHazelConnection connection,
int deltaPort,
Language language,
TimeSpan retryAfter,
string ip)
{
var minutes = IpRateLimitService.MinutesUntilRetry(retryAfter);
var message = _language.Get(new LocalizedMessageKey("empostor", IpRateLimitService.MessageKey), language, minutes);
_logger.LogWarning(
"IpRateLimit rejecting game connection from {Ip} │ retry in {Minutes}m",
ip, minutes);
await connection.CustomDisconnectAsync(DisconnectReason.Custom, message);
if (deltaPort > 0)
{
// The port was never confirmed, release it right away instead
// of waiting for the 5-minute allocation timeout.
_portPool.ReturnPort(deltaPort);
}
}
private static string NormalizeIp(IPAddress? addr)
{
+1 -98
View File
@@ -2,17 +2,14 @@ using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Empostor.Api.Config;
using Empostor.Api.Events.Managers;
using Empostor.Api.Localization;
using Empostor.Server.Events.Client;
using Empostor.Server.Net.Hazel;
using Empostor.Server.Net.Manager;
using Empostor.Server.Service.Auth;
using Empostor.Server.Service.Firewall;
using Empostor.Server.Service.Ip;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
using Microsoft.Extensions.Options;
@@ -33,16 +30,10 @@ namespace Empostor.Server.Net
private readonly ServerConfig _serverConfig;
private readonly AuthCacheService _authCache;
private readonly IOptions<AntiCheatConfig> _antiCheatOptions;
private readonly IpRateLimitService _rateLimit;
private readonly ILocalizationService _language;
private UdpConnectionListener? _mainListener;
private readonly ConcurrentDictionary<int, UdpConnectionListener> _deltaListeners = new();
// Shared port for over-quota (rate limited) joins; 0 until first use.
private int _rejectPort;
private readonly SemaphoreSlim _rejectPortLock = new(1, 1);
private IPEndPoint? _mainEndPoint;
public Matchmaker(
@@ -55,9 +46,7 @@ namespace Empostor.Server.Net
IFirewallService firewall,
IOptions<ServerConfig> serverConfig,
AuthCacheService authCache,
IOptions<AntiCheatConfig> antiCheatOptions,
IpRateLimitService rateLimit,
ILocalizationService language)
IOptions<AntiCheatConfig> antiCheatOptions)
{
_eventManager = eventManager;
_clientManager = clientManager;
@@ -69,8 +58,6 @@ namespace Empostor.Server.Net
_serverConfig = serverConfig.Value;
_authCache = authCache;
_antiCheatOptions = antiCheatOptions;
_rateLimit = rateLimit;
_language = language;
// Subscribe to port return events from the pool
_portPool.OnPortReturned += OnPortReturned;
@@ -202,66 +189,6 @@ namespace Empostor.Server.Net
}
}
/// <summary>
/// One shared UDP port for all over-quota joins: reserving it here
/// (once) means rate-limited TCP requests never take a pool port and
/// never start their own listener. The listener above answers every
/// handshake on this port with the localized hint and closes it, so
/// the player is told why they cannot join instead of seeing a black
/// screen — without letting them into a game.
/// </summary>
public async ValueTask<int> GetRateLimitRejectPortAsync()
{
if (!_portPool.IsEnabled)
{
// Fixed-port mode: the main listener is the reject target.
return 0;
}
var existing = Volatile.Read(ref _rejectPort);
if (existing > 0)
{
return existing;
}
await _rejectPortLock.WaitAsync();
try
{
existing = Volatile.Read(ref _rejectPort);
if (existing > 0)
{
return existing;
}
var port = _portPool.AllocatePort("(rate limit reject)");
if (port <= 0)
{
_logger.LogWarning("Matchmaker could not reserve the rate-limit reject port: pool unavailable");
return 0;
}
if (!await StartDeltaListenerAsync(port))
{
// StartDeltaListenerAsync already returned the port.
return 0;
}
// Confirmed so it is never reclaimed by the allocation timeout:
// this port lives for the whole lifetime of the server.
_portPool.ConfirmPort(port);
Volatile.Write(ref _rejectPort, port);
_logger.LogInformation(
"Matchmaker rate-limit reject port reserved on {Port} (one shared port for all over-quota joins)",
port);
return port;
}
finally
{
_rejectPortLock.Release();
}
}
public async ValueTask StopAsync()
{
if (_mainListener != null)
@@ -302,20 +229,6 @@ namespace Empostor.Server.Net
connection = new HazelConnection(e.Connection, _connectionLogger, _antiCheatOptions);
// Shared rate-limit reject port: there is no auth entry and no
// player behind it, so the only thing to do is tell the client
// — in its own language — why it is not let in.
if (port != 0 && port == Volatile.Read(ref _rejectPort))
{
var message = BuildRateLimitMessage(connection.EndPoint?.Address, language);
_logger.LogWarning(
"Matchmaker rate limit rejected {Ip} on reject port {Port} │ {Message}",
connection.EndPoint?.Address?.ToString() ?? "unknown", port, message);
await connection.CustomDisconnectAsync(DisconnectReason.Custom, message);
return;
}
await _eventManager.CallAsync(new ClientConnectionEvent(connection, e.HandshakeData));
await _clientManager.RegisterConnectionAsync(
connection, name, clientVersion, language, chatMode, platformSpecificData,
@@ -336,17 +249,7 @@ namespace Empostor.Server.Net
// left for that IP when it can be read off the quota, the full window
// otherwise (behind a CDN the UDP source address may not be the key the
// requests were counted with).
private string BuildRateLimitMessage(IPAddress? ip, Language language)
{
var minutes = IpRateLimitService.WindowMinutes;
if (ip != null && _rateLimit.IsLimited(ip, out var retryAfter))
{
minutes = IpRateLimitService.MinutesUntilRetry(retryAfter);
}
return _language.Get(new LocalizedMessageKey("empostor", IpRateLimitService.MessageKey), language, minutes);
}
private void OnPortReturned(int port)
{
@@ -1,10 +1,8 @@
using System;
using System.Globalization;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading.Tasks;
using Empostor.Api.Localization;
using Empostor.Server.Localization;
using Empostor.Api.Innersloth;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
@@ -12,29 +10,21 @@ namespace Empostor.Server.Service.Ip;
public sealed class IpRateLimitMiddleware
{
private const string MessageKey = IpRateLimitService.MessageKey;
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
// The client parses a failed matchmaker request as a MatchmakerResponse
// and reads "Errors"; 116 (TooManyRequests) is rendered by the client itself.
private static readonly JsonSerializerOptions MatchmakerJsonOptions = new();
private readonly RequestDelegate _next;
private readonly IpRateLimitService _rateLimit;
private readonly ILocalizationService _language;
private readonly ILogger<IpRateLimitMiddleware> _logger;
public IpRateLimitMiddleware(
RequestDelegate next,
IpRateLimitService rateLimit,
ILocalizationService language,
ILogger<IpRateLimitMiddleware> logger)
{
_next = next;
_rateLimit = rateLimit;
_language = language;
_logger = logger;
}
@@ -50,18 +40,9 @@ public sealed class IpRateLimitMiddleware
var ip = RealIpResolver.Resolve(context);
// Always counted, so the join endpoint cannot be used to burn through
// the quota without being noticed.
var overQuota = !_rateLimit.TryRegister(ip, out var retryAfter);
// The join flow of the game client (POST /api/user, then
// PUT/GET /api/games for FindHost) must never fail over HTTP: the
// client only logs such a failure and then hangs on a black screen.
// These endpoints are therefore counted but never blocked — over-quota
// players still take no pool port and no outbound auth call, and are
// pointed at one shared reject port whose listener sends the localized
// hint in-game (see TokenController / Matchmaker).
if (!overQuota || IsGameFlowPath(context.Request.Path))
// Every non-admin request is counted and rejected over quota, the join
// flow included: no token or port is handed out, so no pool port is spent.
if (_rateLimit.TryRegister(ip, out var retryAfter))
{
await _next(context);
return;
@@ -69,8 +50,6 @@ public sealed class IpRateLimitMiddleware
var minutes = IpRateLimitService.MinutesUntilRetry(retryAfter);
var message = _language.Get(new LocalizedMessageKey("empostor", MessageKey), LanguageCodes.FromTag(ResolveLangCode(context)), minutes);
_logger.LogWarning(
"IpRateLimit blocked {Ip} on {Path} │ retry in {Minutes}m",
ip?.ToString() ?? "unknown",
@@ -81,76 +60,13 @@ public sealed class IpRateLimitMiddleware
context.Response.Headers["Retry-After"] =
((int)Math.Ceiling(retryAfter.TotalSeconds)).ToString(CultureInfo.InvariantCulture);
context.Response.ContentType = "application/json; charset=utf-8";
await context.Response.WriteAsync(JsonSerializer.Serialize(new { error = message }, JsonOptions));
await context.Response.WriteAsync(JsonSerializer.Serialize(
new { Errors = new[] { new { Reason = DisconnectReason.TooManyRequests } } },
MatchmakerJsonOptions));
}
// The admin panel polls its own endpoints, so it is never rate-limited.
private static bool IsAdminPath(PathString path)
=> path.StartsWithSegments("/admin", StringComparison.OrdinalIgnoreCase)
|| path.StartsWithSegments("/api/admin", StringComparison.OrdinalIgnoreCase);
// The join flow of the game client: matchmaking token + FindHost.
// GamesController echoes the token's port back, so the reject port handed
// out by /api/user is what the client connects to.
private static bool IsGameFlowPath(PathString path)
=> path.StartsWithSegments("/api/user", StringComparison.OrdinalIgnoreCase)
|| path.StartsWithSegments("/api/games", StringComparison.OrdinalIgnoreCase);
private static string ResolveLangCode(HttpContext context)
{
var acceptLanguage = context.Request.Headers["Accept-Language"].ToString();
foreach (var entry in acceptLanguage.Split(','))
{
var tag = entry.Split(';')[0].Trim();
if (tag.Length == 0 || tag == "*")
{
continue;
}
var code = MapLangTag(tag);
if (code != null)
{
return code;
}
}
return "en";
}
// Maps a browser/client language tag (zh-CN, pt-BR, ...) to one of the
// server's Languages/*.json codes.
private static string? MapLangTag(string tag)
{
var lower = tag.ToLowerInvariant();
if (lower.StartsWith("zh", StringComparison.Ordinal))
{
return lower.Contains("hant", StringComparison.Ordinal)
|| lower.Contains("tw", StringComparison.Ordinal)
|| lower.Contains("hk", StringComparison.Ordinal)
|| lower.Contains("mo", StringComparison.Ordinal)
? "zh_TW"
: "zh_CN";
}
if (lower.StartsWith("pt-br", StringComparison.Ordinal))
{
return "pt_BR";
}
if (lower.StartsWith("fil", StringComparison.Ordinal) || lower.StartsWith("tl", StringComparison.Ordinal))
{
return "fil";
}
foreach (var code in new[] { "en", "es", "pt", "ko", "ru", "nl", "fr", "de", "it", "ja", "ga" })
{
if (lower.StartsWith(code, StringComparison.Ordinal))
{
return code;
}
}
return null;
}
}
@@ -7,8 +7,6 @@ using Microsoft.Extensions.Options;
namespace Empostor.Server.Service.Ip;
public sealed class IpRateLimitService
{
public const string MessageKey = "ratelimit.too_frequent";
public const int MaxRequestsPerWindow = 30;
public const int WindowMinutes = 1;
@@ -69,42 +67,6 @@ public sealed class IpRateLimitService
}
}
// Reads the quota without counting a request — used to answer the client
// in-game (and to skip expensive work) when the IP is already over quota.
public bool IsLimited(IPAddress? ip, out TimeSpan retryAfter)
{
retryAfter = TimeSpan.Zero;
var config = _options.Value;
var window = GetWindow(config);
if (ip == null || window == null)
{
return false;
}
if (!_windows.TryGetValue(ip.ToString(), out var entry))
{
return false;
}
var now = DateTime.UtcNow;
lock (entry)
{
if (now - entry.StartUtc >= window.Value || entry.Count <= MaxRequestsPerWindow)
{
return false;
}
retryAfter = entry.StartUtc + window.Value - now;
if (retryAfter < TimeSpan.Zero)
{
retryAfter = TimeSpan.Zero;
}
return true;
}
}
private static TimeSpan? GetWindow(AntiCheatConfig config)
{
if (!config.EnableRateLimits)