diff --git a/Migrations/20251110131236_UpdateSessions.Designer.cs b/Migrations/20251110131236_UpdateSessions.Designer.cs new file mode 100644 index 0000000..82af4f0 --- /dev/null +++ b/Migrations/20251110131236_UpdateSessions.Designer.cs @@ -0,0 +1,478 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Server.Data; + +#nullable disable + +namespace SystemRevivalServer.Migrations +{ + [DbContext(typeof(GameDbContext))] + [Migration("20251110131236_UpdateSessions")] + partial class UpdateSessions + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("Server.Data.Account", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("BannedUntil") + .HasColumnType("datetime(6)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Email") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IsBanned") + .HasColumnType("tinyint(1)"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("varbinary(64)"); + + b.Property("PasswordSalt") + .IsRequired() + .HasColumnType("varbinary(32)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("accounts", (string)null); + }); + + modelBuilder.Entity("Server.Data.Character", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("AppearanceJson") + .HasColumnType("json"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("FacingDeg") + .HasColumnType("float"); + + b.Property("HpCurrent") + .HasColumnType("int unsigned"); + + b.Property("HpMax") + .HasColumnType("int unsigned"); + + b.Property("Level") + .HasColumnType("int unsigned"); + + b.Property("MpCurrent") + .HasColumnType("int unsigned"); + + b.Property("MpMax") + .HasColumnType("int unsigned"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("PosX") + .HasColumnType("double"); + + b.Property("PosY") + .HasColumnType("double"); + + b.Property("PosZ") + .HasColumnType("double"); + + b.Property("StaminaCurrent") + .HasColumnType("int unsigned"); + + b.Property("StaminaMax") + .HasColumnType("int unsigned"); + + b.Property("StatDexterity") + .HasColumnType("int unsigned"); + + b.Property("StatEndurance") + .HasColumnType("int unsigned"); + + b.Property("StatIntelligence") + .HasColumnType("int unsigned"); + + b.Property("StatStrength") + .HasColumnType("int unsigned"); + + b.Property("StatWisdom") + .HasColumnType("int unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Xp") + .HasColumnType("bigint unsigned"); + + b.Property("ZoneId") + .HasColumnType("bigint unsigned"); + + b.HasKey("Id"); + + b.HasIndex("AccountId") + .IsUnique(); + + b.HasIndex("ZoneId"); + + b.ToTable("characters", (string)null); + }); + + modelBuilder.Entity("Server.Data.EquipmentSlot", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemTemplateId") + .HasColumnType("bigint unsigned"); + + b.Property("SlotCode") + .HasColumnType("tinyint unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("ItemTemplateId"); + + b.HasIndex("CharacterId", "SlotCode") + .IsUnique(); + + b.ToTable("equipment", (string)null); + }); + + modelBuilder.Entity("Server.Data.InventoryItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemTemplateId") + .HasColumnType("bigint unsigned"); + + b.Property("Quantity") + .HasColumnType("int unsigned"); + + b.Property("SlotIndex") + .HasColumnType("int unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("CharacterId"); + + b.HasIndex("ItemTemplateId"); + + b.HasIndex("CharacterId", "SlotIndex") + .IsUnique(); + + b.ToTable("inventories", (string)null); + }); + + modelBuilder.Entity("Server.Data.ItemTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemType") + .HasColumnType("tinyint unsigned"); + + b.Property("MaxStack") + .HasColumnType("int unsigned"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Rarity") + .HasColumnType("tinyint unsigned"); + + b.Property("StatsJson") + .HasColumnType("json"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Weight") + .HasColumnType("int unsigned"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("item_templates", (string)null); + }); + + modelBuilder.Entity("Server.Data.Session", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("CreatedIp") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ExpiresAt") + .HasColumnType("datetime(6)"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("UserAgent") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("sessions", (string)null); + }); + + modelBuilder.Entity("Server.Data.Zone", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("MaxX") + .HasColumnType("double"); + + b.Property("MaxY") + .HasColumnType("double"); + + b.Property("MaxZ") + .HasColumnType("double"); + + b.Property("MinX") + .HasColumnType("double"); + + b.Property("MinY") + .HasColumnType("double"); + + b.Property("MinZ") + .HasColumnType("double"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("zones", (string)null); + }); + + modelBuilder.Entity("Server.Data.Character", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany("Characters") + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.Zone", "Zone") + .WithMany() + .HasForeignKey("ZoneId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Account"); + + b.Navigation("Zone"); + }); + + modelBuilder.Entity("Server.Data.EquipmentSlot", b => + { + b.HasOne("Server.Data.Character", "Character") + .WithMany() + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.ItemTemplate", "ItemTemplate") + .WithMany() + .HasForeignKey("ItemTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Character"); + + b.Navigation("ItemTemplate"); + }); + + modelBuilder.Entity("Server.Data.InventoryItem", b => + { + b.HasOne("Server.Data.Character", "Character") + .WithMany() + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.ItemTemplate", "ItemTemplate") + .WithMany() + .HasForeignKey("ItemTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Character"); + + b.Navigation("ItemTemplate"); + }); + + modelBuilder.Entity("Server.Data.Session", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany("Sessions") + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.Account", b => + { + b.Navigation("Characters"); + + b.Navigation("Sessions"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Migrations/20251110131236_UpdateSessions.cs b/Migrations/20251110131236_UpdateSessions.cs new file mode 100644 index 0000000..45fad07 --- /dev/null +++ b/Migrations/20251110131236_UpdateSessions.cs @@ -0,0 +1,88 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SystemRevivalServer.Migrations +{ + /// + public partial class UpdateSessions : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_sessions_Token", + table: "sessions"); + + migrationBuilder.DropColumn( + name: "Token", + table: "sessions"); + + migrationBuilder.AddColumn( + name: "CreatedIp", + table: "sessions", + type: "varchar(64)", + maxLength: 64, + nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.AddColumn( + name: "TokenHash", + table: "sessions", + type: "varchar(128)", + maxLength: 128, + nullable: false, + defaultValue: "") + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.AddColumn( + name: "UserAgent", + table: "sessions", + type: "varchar(256)", + maxLength: 256, + nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_sessions_TokenHash", + table: "sessions", + column: "TokenHash", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_sessions_TokenHash", + table: "sessions"); + + migrationBuilder.DropColumn( + name: "CreatedIp", + table: "sessions"); + + migrationBuilder.DropColumn( + name: "TokenHash", + table: "sessions"); + + migrationBuilder.DropColumn( + name: "UserAgent", + table: "sessions"); + + migrationBuilder.AddColumn( + name: "Token", + table: "sessions", + type: "varchar(64)", + maxLength: 64, + nullable: false, + defaultValue: "") + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_sessions_Token", + table: "sessions", + column: "Token", + unique: true); + } + } +} diff --git a/Migrations/GameDbContextModelSnapshot.cs b/Migrations/GameDbContextModelSnapshot.cs index ac14ff7..21ef9be 100644 --- a/Migrations/GameDbContextModelSnapshot.cs +++ b/Migrations/GameDbContextModelSnapshot.cs @@ -318,19 +318,27 @@ namespace SystemRevivalServer.Migrations .HasColumnType("datetime(6)") .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + b.Property("CreatedIp") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + b.Property("ExpiresAt") .HasColumnType("datetime(6)"); - b.Property("Token") + b.Property("TokenHash") .IsRequired() - .HasMaxLength(64) - .HasColumnType("varchar(64)"); + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("UserAgent") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); b.HasKey("Id"); b.HasIndex("AccountId"); - b.HasIndex("Token") + b.HasIndex("TokenHash") .IsUnique(); b.ToTable("sessions", (string)null); diff --git a/Networking/MessageRouter.cs b/Networking/MessageRouter.cs index e6f3157..da0f640 100644 --- a/Networking/MessageRouter.cs +++ b/Networking/MessageRouter.cs @@ -1,17 +1,26 @@ -using System; +// Networking/MessageRouter.cs +using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Server.Networking.Messages; +using Server.Services.Auth; namespace Server.Networking; public sealed class MessageRouter { private readonly ILogger _logger; + private readonly IAuthService _auth; + private readonly ISessionRegistry _sessions; private readonly IMessageSerializer _serializer = new JsonSerializerAdapter(); - public MessageRouter(ILogger logger) => _logger = logger; + public MessageRouter(ILogger logger, IAuthService auth, ISessionRegistry sessions) + { + _logger = logger; + _auth = auth; + _sessions = sessions; + } public async Task OnMessageAsync(IConnection connection, ReadOnlyMemory data, CancellationToken cancellationToken) { @@ -19,20 +28,88 @@ public sealed class MessageRouter switch (clientMessage.OpCode) { - case 1: // Hello / Echo - _logger.LogDebug("HELLO from {ConnectionId}", connection.Id); - await SendAsync(connection, new ServerMessage(1, clientMessage.Payload), cancellationToken); - break; + case OpCodes.ECHO: + _logger.LogDebug("ECHO from {ConnectionId}", connection.Id); + await ReplyAsync(connection, OpCodes.ECHO, clientMessage.Payload, cancellationToken); + return; + + case OpCodes.AUTH_REGISTER: + { + var req = _serializer.Deserialize(clientMessage.Payload); + var (ok, error) = await _auth.RegisterAsync(req.Username, req.Password, req.Email, cancellationToken); + + string? msg = error switch + { + "invalid_username" => "Username must be 3–32 characters.", + "weak_password" => "Password must be at least 8 characters.", + "username_taken" => "That username is already in use.", + "email_taken" => "That email is already registered.", + _ => null + }; + + await ReplyObjectAsync(connection, OpCodes.AUTH_REGISTER_RESULT, + new AuthRegisterResponse(ok, error, msg), cancellationToken); + return; + } + + case OpCodes.AUTH_LOGIN: + { + var req = _serializer.Deserialize(clientMessage.Payload); + var ip = connection.RemoteEndPoint?.ToString(); + var ua = "gameclient"; + + var (ok, error, token, accountId) = await _auth.LoginAsync(req.UsernameOrEmail, req.Password, ip, ua, TimeSpan.FromHours(24), cancellationToken); + + // Optionally fetch ban-until if banned (extend AuthService to return it directly if you prefer) + DateTime? bannedUntil = null; + if (ok) _sessions.Bind(connection.Id, accountId, token!); + + + await ReplyObjectAsync(connection, OpCodes.AUTH_LOGIN_RESULT, + new AuthLoginResponse(ok, error, token, accountId, bannedUntil), cancellationToken); + return; + } + + case OpCodes.AUTH_WITH_TOKEN: + { + var req = _serializer.Deserialize(clientMessage.Payload); + var (ok, error, accountId) = await _auth.ValidateTokenAsync(req.Token, cancellationToken); + if (ok) _sessions.Bind(connection.Id, accountId, req.Token); + + await ReplyObjectAsync(connection, OpCodes.AUTH_WITH_TOKEN_RESULT, + new AuthWithTokenResponse(ok, error, accountId), cancellationToken); + return; + } default: + // Gate all other opcodes behind auth + if (!_sessions.IsAuthenticated(connection.Id)) + { + // Either ignore or send a standard error + await ReplyErrorAsync(connection, "auth_required", cancellationToken); + _logger.LogWarning("Unauthenticated message opcode={Op} from {Conn}", clientMessage.OpCode, connection.Id); + return; + } + _logger.LogWarning("Unknown opcode {OpCode} from {ConnectionId}", clientMessage.OpCode, connection.Id); - break; + return; } } - public Task SendAsync(IConnection connection, ServerMessage message, CancellationToken cancellationToken) + // Helpers + private Task ReplyAsync(IConnection connection, int opCode, byte[] payloadBytes, CancellationToken ct) { - var bytes = _serializer.Serialize(message); - return connection.SendAsync(bytes, cancellationToken).AsTask(); + var msg = new ServerMessage(opCode, payloadBytes); + var wire = _serializer.Serialize(msg); + return connection.SendAsync(wire, ct).AsTask(); } + + private Task ReplyObjectAsync(IConnection connection, int opCode, T obj, CancellationToken ct) + { + var payload = _serializer.Serialize(obj); + return ReplyAsync(connection, opCode, payload, ct); + } + + private Task ReplyErrorAsync(IConnection connection, string code, CancellationToken ct) + => ReplyObjectAsync(connection, OpCodes.ERROR, new { error = code }, ct); } diff --git a/Networking/Messages/AuthContracts.cs b/Networking/Messages/AuthContracts.cs new file mode 100644 index 0000000..a09c768 --- /dev/null +++ b/Networking/Messages/AuthContracts.cs @@ -0,0 +1,10 @@ +namespace Server.Networking.Messages; + +public sealed record AuthRegisterRequest(string Username, string Password, string? Email); +public sealed record AuthRegisterResponse(bool Ok, string? Error, string? Message); + +public sealed record AuthLoginRequest(string UsernameOrEmail, string Password); +public sealed record AuthLoginResponse(bool Ok, string? Error, string? Token, ulong AccountId, System.DateTime? BannedUntilUtc); + +public sealed record AuthWithTokenRequest(string Token); +public sealed record AuthWithTokenResponse(bool Ok, string? Error, ulong AccountId); \ No newline at end of file diff --git a/Networking/Messages/OpCodes.cs b/Networking/Messages/OpCodes.cs new file mode 100644 index 0000000..2d58de9 --- /dev/null +++ b/Networking/Messages/OpCodes.cs @@ -0,0 +1,17 @@ +namespace Server.Networking.Messages; + +public static class OpCodes +{ + public const int ECHO = 1; + + public const int AUTH_REGISTER = 100; + public const int AUTH_REGISTER_RESULT = 101; + + public const int AUTH_LOGIN = 110; + public const int AUTH_LOGIN_RESULT = 111; + + public const int AUTH_WITH_TOKEN = 112; + public const int AUTH_WITH_TOKEN_RESULT = 113; + + public const int ERROR = 900; // generic error envelope if you want +} diff --git a/Networking/NetworkManager.cs b/Networking/NetworkManager.cs index 08a8198..a5d2930 100644 --- a/Networking/NetworkManager.cs +++ b/Networking/NetworkManager.cs @@ -4,6 +4,9 @@ using System.Net.Sockets; using System.Net.WebSockets; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; +using Server.Redis; +using Server.Services.Auth; +using StackExchange.Redis; namespace Server.Networking; @@ -12,15 +15,19 @@ public sealed class NetworkManager private readonly ILogger _log; private readonly MessageRouter _router; private readonly ConcurrentDictionary _connections = new(); + private readonly ISessionRegistry _sessions; + private readonly IRedisManager _redis; private readonly TimeSpan _tickInterval; private readonly TimeSpan _idleTimeout; private readonly int _maxConnections; - public NetworkManager(ILogger log, MessageRouter router) + public NetworkManager(ILogger log, MessageRouter router, ISessionRegistry sessions, IRedisManager redis) { _log = log; _router = router; + _sessions = sessions; + _redis = redis; var tickHz = int.TryParse(Environment.GetEnvironmentVariable("TICK_RATE_HZ"), out var hz) ? Math.Clamp(hz, 1, 120) : 20; _tickInterval = TimeSpan.FromMilliseconds(1000.0 / tickHz); @@ -136,9 +143,39 @@ public sealed class NetworkManager { if (_connections.TryRemove(conn.Id, out _)) { + // If this connection was authenticated, log it out atomically + if (_sessions.TryGet(conn.Id, out var accountId, out var token) && accountId != 0 && !string.IsNullOrEmpty(token)) + { + try + { + var onlineKey = $"online:acct:{accountId}"; + var sessKey = $"sess:{token}"; + + const string lua = @" + if redis.call('GET', KEYS[1]) == ARGV[1] then + redis.call('DEL', KEYS[1]) + end + redis.call('DEL', KEYS[2]) + return 1"; + + await _redis.Db.ScriptEvaluateAsync(lua, + new RedisKey[] { onlineKey, sessKey }, + new RedisValue[] { token }); + + _sessions.Unbind(conn.Id); + _log.LogInformation("Logged out account {AccountId} on disconnect", accountId); + } + catch (Exception ex) + { + _log.LogWarning(ex, "Failed Redis logout cleanup for account {AccountId}", accountId); + _sessions.Unbind(conn.Id); + } + } + _log.LogInformation("Disconnected {Id} ({Reason})", conn.Id, reason); - await conn.CloseAsync(reason); - await conn.DisposeAsync(); + try { await conn.CloseAsync(reason); } catch { } + try { await conn.DisposeAsync(); } catch { } } } + } diff --git a/Program.cs b/Program.cs index ae8c758..40e06e3 100644 --- a/Program.cs +++ b/Program.cs @@ -11,6 +11,7 @@ using Server.Networking; using Server.Persistence; using Server.Redis; using Server.Services; +using Server.Services.Auth; var builder = WebApplication.CreateBuilder(args); @@ -40,6 +41,10 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHostedService(sp => (ZoneLeaseService)sp.GetRequiredService()); builder.Services.AddSingleton(); +builder.Services.AddScoped(); +builder.Services.AddSingleton(); +builder.Services.AddScoped(); +builder.Services.AddSingleton(); // Health checks (optional DB/Redis implementations) builder.Services.AddHealthChecks() diff --git a/Services/Auth/AccountsRepository.cs b/Services/Auth/AccountsRepository.cs new file mode 100644 index 0000000..d346947 --- /dev/null +++ b/Services/Auth/AccountsRepository.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore; +using Server.Data; + +namespace Server.Services.Auth; + +public sealed class AccountsRepository : IAccountsRepository +{ + private readonly GameDbContext _db; + public AccountsRepository(GameDbContext db) => _db = db; + + public Task FindByUsernameAsync(string username, CancellationToken ct = default) => + _db.Set().FirstOrDefaultAsync(a => a.Username == username, ct); + + public Task FindByEmailAsync(string email, CancellationToken ct = default) => + _db.Set().FirstOrDefaultAsync(a => a.Email == email, ct); + + public async Task AddAsync(Account account, CancellationToken ct = default) + { + _db.Add(account); + await _db.SaveChangesAsync(ct); + return account; + } + + public async Task AddSessionAsync(Session s, CancellationToken ct = default) + { + _db.Add(s); + await _db.SaveChangesAsync(ct); + } +} \ No newline at end of file diff --git a/Services/Auth/AuthService.cs b/Services/Auth/AuthService.cs new file mode 100644 index 0000000..7589cad --- /dev/null +++ b/Services/Auth/AuthService.cs @@ -0,0 +1,151 @@ +using System.Security.Cryptography; +using System.Text; +using Microsoft.Extensions.Logging; +using Server.Data; +using Server.Redis; +using StackExchange.Redis; + +namespace Server.Services.Auth; + +public interface IAuthService +{ + Task<(bool ok, string? error)> RegisterAsync(string username, string password, string? email, CancellationToken ct = default); + Task<(bool ok, string? error, string? token, ulong accountId)> LoginAsync(string usernameOrEmail, string password, string? ip, string? userAgent, TimeSpan? ttl = null, CancellationToken ct = default); + Task<(bool ok, string? error, ulong accountId)> ValidateTokenAsync(string token, CancellationToken ct = default); +} + +public sealed class AuthService : IAuthService +{ + private readonly IAccountsRepository _repo; + private readonly IPasswordHasher _hasher; + private readonly IRedisManager _redis; + private readonly ILogger _log; + + private const string LuaLoginAtom = @" + -- KEYS[1] = online:acct:{accountId} + -- KEYS[2] = sess:{token} + -- ARGV[1] = token + -- ARGV[2] = ttlSeconds + -- ARGV[3] = accountId (string) + + if redis.call('EXISTS', KEYS[1]) == 1 then + return 0 + end + redis.call('SET', KEYS[1], ARGV[1]) + redis.call('SETEX', KEYS[2], ARGV[2], ARGV[3]) + return 1 + "; + + private const string LuaLogoutAtom = @" + -- KEYS[1] = online:acct:{accountId} + -- KEYS[2] = sess:{token} + -- ARGV[1] = token + + if redis.call('GET', KEYS[1]) == ARGV[1] then + redis.call('DEL', KEYS[1]) + end + redis.call('DEL', KEYS[2]) + return 1 + "; + + public AuthService(IAccountsRepository repo, IPasswordHasher hasher, IRedisManager redis, ILogger log) + { + _repo = repo; _hasher = hasher; _redis = redis; _log = log; + } + + public async Task<(bool ok, string? error)> RegisterAsync(string username, string password, string? email, CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(username) || username.Length is < 3 or > 32) return (false, "invalid_username"); + if (string.IsNullOrWhiteSpace(password) || password.Length < 8) return (false, "weak_password"); + if (email is { Length: > 255 }) return (false, "invalid_email"); + + username = username.Trim(); + email = email?.Trim(); + + if (await _repo.FindByUsernameAsync(username, ct) is not null) return (false, "username_taken"); + if (!string.IsNullOrWhiteSpace(email) && await _repo.FindByEmailAsync(email!, ct) is not null) return (false, "email_taken"); + + _hasher.Hash(password, out var hash, out var salt); + + var now = DateTime.UtcNow; + var acct = new Account + { + Username = username, + Email = email, + PasswordHash = hash, + PasswordSalt = salt, + CreatedAt = now, + UpdatedAt = now + }; + + await _repo.AddAsync(acct, ct); + _log.LogInformation("Registered account {Username} ({AccountId})", username, acct.Id); + return (true, null); + } + + public async Task<(bool ok, string? error, string? token, ulong accountId)> LoginAsync( + string usernameOrEmail, string password, string? ip, string? userAgent, TimeSpan? ttl = null, CancellationToken ct = default) + { + ttl ??= TimeSpan.FromHours(24); + + Account? acct = usernameOrEmail.Contains('@') + ? await _repo.FindByEmailAsync(usernameOrEmail, ct) + : await _repo.FindByUsernameAsync(usernameOrEmail, ct); + + if (acct is null) return (false, "not_found", null, 0); + if (acct.IsBanned && (!acct.BannedUntil.HasValue || acct.BannedUntil > DateTime.UtcNow)) + return (false, "banned", null, 0); + + if (!_hasher.Verify(password, acct.PasswordHash, acct.PasswordSalt)) + return (false, "bad_credentials", null, 0); + + // Create token + var tokenBytes = RandomNumberGenerator.GetBytes(32); + var token = Convert.ToHexString(tokenBytes).ToLowerInvariant(); + + // Atomically: if not already online, mark online and create sess:{token} + var ttlSeconds = (long)Math.Ceiling(ttl.Value.TotalSeconds); + var onlineKey = $"online:acct:{acct.Id}"; + var sessKey = $"sess:{token}"; + + var res = (int)(long)await _redis.Db.ScriptEvaluateAsync(LuaLoginAtom, + new RedisKey[] { onlineKey, sessKey }, + new RedisValue[] { token, ttlSeconds, (long)acct.Id }); + + if (res != 1) + return (false, "already_online", null, 0); + + // Optional: audit to SQL (store hash, not raw token) + var tokenHash = Sha256(token); + await _repo.AddSessionAsync(new Session + { + AccountId = acct.Id, + TokenHash = tokenHash, + CreatedAt = DateTime.UtcNow, + ExpiresAt = DateTime.UtcNow.AddSeconds(ttlSeconds), + CreatedIp = ip, + UserAgent = userAgent + }, ct); + + return (true, null, token, acct.Id); + } + + public async Task<(bool ok, string? error, ulong accountId)> ValidateTokenAsync(string token, CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(token)) + return (false, "no_token", 0); + + var val = await _redis.Db.StringGetAsync($"sess:{token}"); + if (val.IsNullOrEmpty) return (false, "invalid_or_expired", 0); + + var accountId = (ulong)(long)val; // stored as long + return (true, null, accountId); + } + + private static string Sha256(string input) + { + using var sha = SHA256.Create(); + var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(input)); + return Convert.ToHexString(bytes).ToLowerInvariant(); + } +} diff --git a/Services/Auth/IAccountsRepository.cs b/Services/Auth/IAccountsRepository.cs new file mode 100644 index 0000000..66e8aba --- /dev/null +++ b/Services/Auth/IAccountsRepository.cs @@ -0,0 +1,11 @@ +using Server.Data; + +namespace Server.Services.Auth; + +public interface IAccountsRepository +{ + Task FindByUsernameAsync(string username, CancellationToken ct = default); + Task FindByEmailAsync(string email, CancellationToken ct = default); + Task AddAsync(Account account, CancellationToken ct = default); + Task AddSessionAsync(Session s, CancellationToken ct = default); +} \ No newline at end of file diff --git a/Services/Auth/IPasswordHasher.cs b/Services/Auth/IPasswordHasher.cs new file mode 100644 index 0000000..6cf755b --- /dev/null +++ b/Services/Auth/IPasswordHasher.cs @@ -0,0 +1,7 @@ +namespace Server.Services.Auth; + +public interface IPasswordHasher +{ + void Hash(string password, out byte[] hash, out byte[] salt); + bool Verify(string password, byte[] hash, byte[] salt); +} diff --git a/Services/Auth/ISessionRegistry.cs b/Services/Auth/ISessionRegistry.cs new file mode 100644 index 0000000..7806a8f --- /dev/null +++ b/Services/Auth/ISessionRegistry.cs @@ -0,0 +1,13 @@ +using System; +using System.Threading.Tasks; + +namespace Server.Services.Auth; + +public interface ISessionRegistry +{ + void Bind(Guid connectionId, ulong accountId, string token); + void Unbind(Guid connectionId); + bool IsAuthenticated(Guid connectionId); + bool TryGetAccountId(Guid connectionId, out ulong accountId); + bool TryGet(Guid connectionId, out ulong accountId, out string token); +} diff --git a/Services/Auth/Pbkdf2PasswordHasher.cs b/Services/Auth/Pbkdf2PasswordHasher.cs new file mode 100644 index 0000000..9c23bde --- /dev/null +++ b/Services/Auth/Pbkdf2PasswordHasher.cs @@ -0,0 +1,24 @@ +using System.Security.Cryptography; + +namespace Server.Services.Auth; + +public sealed class Pbkdf2PasswordHasher : IPasswordHasher +{ + private const int SaltSize = 32; + private const int HashSize = 64; + private const int Iterations = 150_000; // good default; tune for your hardware + + public void Hash(string password, out byte[] hash, out byte[] salt) + { + salt = RandomNumberGenerator.GetBytes(SaltSize); + using var pbkdf2 = new Rfc2898DeriveBytes(password, salt, Iterations, HashAlgorithmName.SHA256); + hash = pbkdf2.GetBytes(HashSize); + } + + public bool Verify(string password, byte[] hash, byte[] salt) + { + using var pbkdf2 = new Rfc2898DeriveBytes(password, salt, Iterations, HashAlgorithmName.SHA256); + var test = pbkdf2.GetBytes(HashSize); + return CryptographicOperations.FixedTimeEquals(test, hash); + } +} diff --git a/Services/Auth/SessionRegistry.cs b/Services/Auth/SessionRegistry.cs new file mode 100644 index 0000000..a1bf0d2 --- /dev/null +++ b/Services/Auth/SessionRegistry.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Concurrent; + +namespace Server.Services.Auth; + +public sealed class SessionRegistry : ISessionRegistry +{ + private readonly ConcurrentDictionary _byConn = new(); + + public void Bind(Guid connectionId, ulong accountId, string token) + => _byConn[connectionId] = (accountId, token); + + public void Unbind(Guid connectionId) + => _byConn.TryRemove(connectionId, out _); + + public bool IsAuthenticated(Guid connectionId) + => _byConn.ContainsKey(connectionId); + + public bool TryGetAccountId(Guid connectionId, out ulong accountId) + { + if (_byConn.TryGetValue(connectionId, out var v)) { accountId = v.accountId; return true; } + accountId = 0; return false; + } + + public bool TryGet(Guid connectionId, out ulong accountId, out string token) + { + if (_byConn.TryGetValue(connectionId, out var v)) + { accountId = v.accountId; token = v.token; return true; } + accountId = 0; token = string.Empty; return false; + } +} diff --git a/data/entities/Session.cs b/data/entities/Session.cs index dce6f05..26a93fa 100644 --- a/data/entities/Session.cs +++ b/data/entities/Session.cs @@ -7,10 +7,11 @@ public sealed class Session { public ulong Id { get; set; } public ulong AccountId { get; set; } - public string Token { get; set; } = ""; // 64-char base64url/hex + public string TokenHash { get; set; } = ""; // 64-char base64url/hex public DateTime ExpiresAt { get; set; } public DateTime CreatedAt { get; set; } - + public string? CreatedIp { get; set; } + public string? UserAgent { get; set; } public Account? Account { get; set; } } @@ -21,10 +22,16 @@ public sealed class SessionConfig : IEntityTypeConfiguration e.ToTable("sessions"); e.HasKey(x => x.Id); e.Property(x => x.Id).ValueGeneratedOnAdd(); - e.HasIndex(x => x.Token).IsUnique(); - e.HasIndex(x => x.AccountId); - e.Property(x => x.Token).HasMaxLength(64).IsRequired(); + e.Property(x => x.TokenHash).HasMaxLength(128).IsRequired(); + e.Property(x => x.CreatedIp).HasMaxLength(64); + e.Property(x => x.UserAgent).HasMaxLength(256); e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); - e.HasOne(x => x.Account).WithMany(a => a.Sessions).HasForeignKey(x => x.AccountId).OnDelete(DeleteBehavior.Cascade); + e.HasIndex(x => x.AccountId); + e.HasIndex(x => x.TokenHash).IsUnique(); + + e.HasOne(x => x.Account) + .WithMany(a => a.Sessions) + .HasForeignKey(x => x.AccountId) + .OnDelete(DeleteBehavior.Cascade); } }