Enhance GameCodeAuth

This commit is contained in:
linmeideli committed 2026-11-06 10:12:38 +08:00
1 parent b844d3d9f3
commit 3c53de5823
3 files changed
+65 -8

No files matched your search

+1 -1
View File
@@ -299,7 +299,7 @@ public sealed class GamesController : ControllerBase
if (_serverConfig.UseGameCodeMode && auth != null && !game.Code.IsInvalid)
{
listingCode = _gameCodeAuth.CreateChallenge(game.Code, auth);
listingCode = _gameCodeAuth.CreateChallenge(game.Code, auth, code => _gameManager.Find(code) != null);
}
return GameListing.From(game, port, listingCode);
+60 -6
View File
@@ -25,6 +25,9 @@ public sealed class GameCodeAuthManager : IDisposable
// Challenge code -> challenge
private readonly Dictionary<int, Challenge> _challenges = new();
// Reuse a live challenge when a client refreshes the same lobby listing.
private readonly Dictionary<(string Token, GameCode Target), int> _challengeOwners = new();
// Legacy path: real code -> auth info stashed by HTTP join requests
private readonly Dictionary<GameCode, List<PendingJoin>> _pendingJoins = new();
@@ -45,12 +48,23 @@ public sealed class GameCodeAuthManager : IDisposable
private bool Expired(DateTime createdAt) => DateTime.UtcNow - createdAt > _lifetime;
// Issues a challenge code for the listing.
public GameCode CreateChallenge(GameCode targetCode, UserAuthInfo user)
// Issues a challenge code for the listing. A live game code can never be used as a challenge.
public GameCode CreateChallenge(GameCode targetCode, UserAuthInfo user, Func<GameCode, bool> isGameCodeInUse)
{
lock (_gate)
{
var code = NewChallengeCode();
RemoveExpiredChallenge(targetCode.Value);
var owner = (user.MatchmakerToken, targetCode);
if (_challengeOwners.TryGetValue(owner, out var existingCode)
&& _challenges.TryGetValue(existingCode, out var existing)
&& !Expired(existing.CreatedAt)
&& existing.OccupiedBy == null)
{
return existing.Code;
}
_challengeOwners.Remove(owner);
var code = NewChallengeCode(targetCode, isGameCodeInUse);
_challenges[code.Value] = new Challenge
{
@@ -61,11 +75,22 @@ public sealed class GameCodeAuthManager : IDisposable
GameVersion = user.ClientVersion,
CreatedAt = DateTime.UtcNow,
};
_challengeOwners[owner] = code.Value;
return code;
}
}
// Serializes game-code insertion with challenge allocation to prevent cross-type collisions.
public bool TryReserveGameCode(GameCode code, Func<bool> tryAddGame)
{
lock (_gate)
{
RemoveExpiredChallenge(code.Value);
return !_challenges.ContainsKey(code.Value) && tryAddGame();
}
}
// Challenge code -> real code (non-consuming). Used to reverse-map listings and PlatformId queries.
public bool TryGetTarget(GameCode code, out GameCode targetCode)
{
@@ -110,6 +135,12 @@ public sealed class GameCodeAuthManager : IDisposable
return false;
}
if (challenge.OccupiedBy == clientId)
{
reason = "challenge already consumed";
return false;
}
challenge.OccupiedBy = clientId;
user = challenge.User;
targetCode = challenge.TargetCode;
@@ -275,12 +306,15 @@ public sealed class GameCodeAuthManager : IDisposable
}
// Creates a unique challenge code (same V2 format as real codes).
private GameCode NewChallengeCode()
private GameCode NewChallengeCode(GameCode targetCode, Func<GameCode, bool> isGameCodeInUse)
{
for (var i = 0; i < 64; i++)
{
var code = GameCode.Create();
if (!code.IsInvalid && !_challenges.ContainsKey(code.Value))
if (!code.IsInvalid
&& code != targetCode
&& !_challenges.ContainsKey(code.Value)
&& !isGameCodeInUse(code))
{
return code;
}
@@ -289,6 +323,19 @@ public sealed class GameCodeAuthManager : IDisposable
throw new InvalidOperationException("failed to allocate a unique challenge code");
}
private void RemoveExpiredChallenge(int code)
{
if (_challenges.TryGetValue(code, out var challenge) && Expired(challenge.CreatedAt))
{
_challenges.Remove(code);
var owner = (challenge.User.MatchmakerToken, challenge.TargetCode);
if (_challengeOwners.TryGetValue(owner, out var ownerCode) && ownerCode == code)
{
_challengeOwners.Remove(owner);
}
}
}
// Picks the best entry. IP match > name > version; ties go to the older entry.
private static int PickBest(
IEnumerable<(string? Ip, string Name, int GameVersion, DateTime CreatedAt)> candidates,
@@ -346,7 +393,14 @@ public sealed class GameCodeAuthManager : IDisposable
{
foreach (var value in _challenges.Where(x => Expired(x.Value.CreatedAt)).Select(x => x.Key).ToList())
{
_challenges.Remove(value);
if (_challenges.Remove(value, out var challenge))
{
var owner = (challenge.User.MatchmakerToken, challenge.TargetCode);
if (_challengeOwners.TryGetValue(owner, out var ownerCode) && ownerCode == value)
{
_challengeOwners.Remove(owner);
}
}
}
foreach (var code in _pendingJoins.Keys.ToList())
@@ -29,6 +29,7 @@ namespace Empostor.Server.Net.Manager
private readonly IServiceProvider _serviceProvider;
private readonly IEventManager _eventManager;
private readonly IGameCodeFactory _gameCodeFactory;
private readonly GameCodeAuthManager _gameCodeAuth;
private readonly ICompatibilityManager _compatibilityManager;
private readonly ConcurrentDictionary<IClient, Game?> _gamesCreatedBy;
@@ -38,6 +39,7 @@ namespace Empostor.Server.Net.Manager
IServiceProvider serviceProvider,
IEventManager eventManager,
IGameCodeFactory gameCodeFactory,
GameCodeAuthManager gameCodeAuth,
IOptions<CompatibilityConfig> compatibilityConfig,
ICompatibilityManager compatibilityManager)
{
@@ -45,6 +47,7 @@ namespace Empostor.Server.Net.Manager
_serviceProvider = serviceProvider;
_eventManager = eventManager;
_gameCodeFactory = gameCodeFactory;
_gameCodeAuth = gameCodeAuth;
_publicIp = new IPEndPoint(IPAddress.Parse(config.Value.ResolvePublicIp()), config.Value.PublicPort);
_games = new ConcurrentDictionary<int, Game>();
_compatibilityConfig = compatibilityConfig.Value;
@@ -126,7 +129,7 @@ namespace Empostor.Server.Net.Manager
var game = modGuid.HasValue
? ActivatorUtilities.CreateInstance<Game>(_serviceProvider, _publicIp, gameCode, options, filterOptions, modGuid.Value)
: ActivatorUtilities.CreateInstance<Game>(_serviceProvider, _publicIp, gameCode, options, filterOptions);
if (!_games.TryAdd(gameCode, game))
if (!_gameCodeAuth.TryReserveGameCode(gameCode, () => _games.TryAdd(gameCode, game)))
{
return (false, null);
}