Godot client networking + auth + login/main screens; fix admin hamburger

Server:
- ConnectionLoop: accept auth.login and auth.register as valid first messages
  (not just auth.hello); all ack payloads now include sessionToken for client
  persistence
- IGatewayAuthValidator: add LoginAsync and RegisterAsync
- GatewayAuthValidator: implement both via auth gRPC; fetch displayName from
  ValidateAsync after login/register succeeds
- Admin hamburger: custom .sor-admin-hamburger CSS (hardcoded white, no Bootstrap
  btn-link theme fighting); topbar z-index 1050 with position:sticky

Client (Godot 4.5, GDScript):
- autoloads/Network.gd: WebSocketPeer state machine (CONNECTING / CONNECTED /
  RECONNECTING), exponential backoff (1→30s), app-level keepalive ping every
  30s of idle, 30s ping timeout → reconnect, request/reply correlation by
  sequence number, debug_log_packets export flag for full packet dumps
- autoloads/Auth.gd: drives auth.hello / auth.login / auth.register as first
  WS message; persists sessionToken + userId + displayName to user://auth.cfg;
  auto-resumes saved session on reconnect; auth_success / auth_failed signals
- scenes/login/LoginScreen.tscn + login_screen.gd: Login + Register tabs,
  touch-friendly inputs (44px height), status label, Enter key submits, handles
  reconnect/resume states
- scenes/main/MainScreen.tscn + main_screen.gd: top bar with live connection
  dot, welcome label, placeholder nav buttons, sign-out, redirects to login on
  session expiry
- project.godot: Network and Auth autoloads registered; LoginScreen as main scene

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-02-27 20:48:53 -05:00
co-authored by Claude Happy
parent af9e335868
commit 3aaabe75e3
12 changed files with 1052 additions and 164 deletions
@@ -8,7 +8,7 @@
@* Mobile topbar: hamburger + brand. Hidden on desktop via CSS. *@
<div class="sor-admin-topbar">
<button class="btn btn-link text-white p-0 me-3"
<button class="sor-admin-hamburger"
@onclick="ToggleDrawer"
aria-label="Toggle navigation">
<i class="bi bi-list fs-3"></i>
+31 -4
View File
@@ -75,16 +75,21 @@ html, body {
/* ── Mobile overrides (< lg = 992px) ────────────────────────────────────────── */
@media (max-width: 991.98px) {
/* Topbar strip: hamburger + brand */
/* Topbar strip: hamburger + brand.
position:sticky keeps it visible when content scrolls;
z-index:1050 puts it above the sidebar (1045) and backdrop (1040)
so the hamburger is always tappable. */
.sor-admin-topbar {
display: flex;
align-items: center;
height: 56px;
padding: 0 1rem;
background: var(--bs-dark, #212529);
color: white;
background: #212529; /* hard-coded: stays dark in both BS themes */
color: #fff;
flex-shrink: 0;
z-index: 1000;
position: sticky;
top: 0;
z-index: 1050;
}
/* Sidebar becomes a fixed overlay drawer, slides in from the left */
@@ -117,6 +122,28 @@ html, body {
}
}
/* ── Hamburger button ───────────────────────────────────────────────────────── */
/* Bypasses Bootstrap btn/btn-link color overrides entirely — always white,
regardless of the active BS theme (light or dark). */
.sor-admin-hamburger {
background: none;
border: none;
color: #fff;
padding: 0.375rem 0.5rem;
margin-right: 0.5rem;
line-height: 1;
cursor: pointer;
border-radius: 4px;
-webkit-tap-highlight-color: transparent;
}
.sor-admin-hamburger:hover,
.sor-admin-hamburger:focus {
background: rgba(255, 255, 255, 0.12);
outline: none;
}
/* ── Monospace JSON editor ──────────────────────────────────────────────────── */
.font-monospace {
@@ -17,8 +17,6 @@ using SOR.Shared.Proto;
/// </summary>
public sealed class GatewayAuthValidator : IGatewayAuthValidator
{
// AuthService.AuthServiceClient is the generated client stub from auth.proto.
// It wraps a gRPC channel and provides typed RPC methods (ValidateTokenAsync, etc.).
private readonly AuthService.AuthServiceClient _grpcClient;
private readonly ILogger<GatewayAuthValidator> _logger;
@@ -37,8 +35,6 @@ public sealed class GatewayAuthValidator : IGatewayAuthValidator
{
try
{
// Call the Auth service's ValidateToken RPC.
// This is a synchronous RPC (request → response) over gRPC.
var response = await _grpcClient.ValidateTokenAsync(
new ValidateTokenRequest { SessionToken = sessionToken },
cancellationToken: cancellationToken);
@@ -53,11 +49,56 @@ public sealed class GatewayAuthValidator : IGatewayAuthValidator
}
catch (Grpc.Core.RpcException ex)
{
// gRPC exception: Auth service is unreachable, overloaded, or returned an error.
// Treat as invalid — never accept a connection that cannot be validated.
_logger.LogWarning(ex,
"Auth gRPC call failed during token validation: {Status}", ex.Status.StatusCode);
return (false, string.Empty, string.Empty);
}
}
/// <inheritdoc/>
public async Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName)>
LoginAsync(string email, string password, CancellationToken cancellationToken = default)
{
try
{
var response = await _grpcClient.LoginAsync(
new LoginRequest { Email = email, Password = password },
cancellationToken: cancellationToken);
if (!response.Success)
return (false, response.ErrorCode, string.Empty, string.Empty, string.Empty);
// Token is returned; fetch display name via ValidateToken (it includes it).
var validate = await ValidateAsync(response.SessionToken, cancellationToken);
return (true, string.Empty, response.SessionToken, validate.UserId, validate.DisplayName);
}
catch (Grpc.Core.RpcException ex)
{
_logger.LogWarning(ex, "Auth gRPC call failed during login: {Status}", ex.Status.StatusCode);
return (false, "AUTH_SERVICE_UNAVAILABLE", string.Empty, string.Empty, string.Empty);
}
}
/// <inheritdoc/>
public async Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName)>
RegisterAsync(string email, string password, string displayName, CancellationToken cancellationToken = default)
{
try
{
var response = await _grpcClient.RegisterAsync(
new RegisterRequest { Email = email, Password = password, DisplayName = displayName },
cancellationToken: cancellationToken);
if (!response.Success)
return (false, response.ErrorCode, string.Empty, string.Empty, string.Empty);
var validate = await ValidateAsync(response.SessionToken, cancellationToken);
return (true, string.Empty, response.SessionToken, validate.UserId, validate.DisplayName);
}
catch (Grpc.Core.RpcException ex)
{
_logger.LogWarning(ex, "Auth gRPC call failed during register: {Status}", ex.Status.StatusCode);
return (false, "AUTH_SERVICE_UNAVAILABLE", string.Empty, string.Empty, string.Empty);
}
}
}
@@ -14,18 +14,24 @@ namespace SOR.Gateway.Auth;
public interface IGatewayAuthValidator
{
/// <summary>
/// Validates a session token by calling the Auth service.
///
/// Returns a tuple:
/// - Valid: true if the token exists and has not expired or been revoked
/// - UserId: the token owner's user ID (empty string if Valid = false)
/// - DisplayName: the token owner's display name (empty string if Valid = false)
///
/// On Auth service unavailability (gRPC exception), returns Valid = false.
/// This treats auth failures as invalid — better to reject than to let
/// potentially invalid connections through.
/// Validates an existing session token.
/// Returns (Valid=false, …) on invalid/expired token or Auth service error.
/// </summary>
Task<(bool Valid, string UserId, string DisplayName)> ValidateAsync(
string sessionToken,
CancellationToken cancellationToken = default);
/// <summary>
/// Authenticates with email + password. Returns the new session token on success.
/// ErrorCode is set (and SessionToken is empty) on failure.
/// </summary>
Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName)>
LoginAsync(string email, string password, CancellationToken cancellationToken = default);
/// <summary>
/// Registers a new account. Returns the new session token on success.
/// ErrorCode is set (and SessionToken is empty) on failure.
/// </summary>
Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName)>
RegisterAsync(string email, string password, string displayName, CancellationToken cancellationToken = default);
}
+115 -143
View File
@@ -13,85 +13,63 @@ using SOR.Shared.Networking;
/// <summary>
/// Runs the full lifecycle of a single client connection.
///
/// This is the most important class in the Gateway. Every connected client
/// has exactly one ConnectionLoop running as an independent Task.
///
/// Lifecycle phases:
/// Phase 1: Auth handshake — wait for auth.hello, validate token
/// Phase 2: Promote to authenticated — register in ConnectionManager
/// Phase 1: Receive first message (auth.hello / auth.login / auth.register)
/// Phase 2: Validate / create session — promote to AuthenticatedConnection
/// Phase 3: Subscribe to Redis push channel
/// Phase 4: Main message loop — receive → dispatch → optional reply
/// Phase 5: Cleanup — always runs in finally (guaranteed cleanup)
///
/// Lifetime: Transient per connection. GatewayHostedService fires one Task per
/// accepted IClientConnection. Each Task owns this class for its lifetime.
/// Lifetime: Transient per connection.
/// </summary>
public sealed class ConnectionLoop
{
private readonly ConnectionManager _connectionManager;
private readonly IMessageDispatcher _dispatcher;
private readonly IMessageSerializer _serializer;
private readonly IGatewayAuthValidator _authValidator;
private readonly IConnectionMultiplexer _redis;
private readonly GatewayOptions _options;
private readonly ConnectionManager _connectionManager;
private readonly IMessageDispatcher _dispatcher;
private readonly IMessageSerializer _serializer;
private readonly IGatewayAuthValidator _authValidator;
private readonly IConnectionMultiplexer _redis;
private readonly GatewayOptions _options;
private readonly ILogger<ConnectionLoop> _logger;
public ConnectionLoop(
ConnectionManager connectionManager,
IMessageDispatcher dispatcher,
IMessageSerializer serializer,
IGatewayAuthValidator authValidator,
IConnectionMultiplexer redis,
ConnectionManager connectionManager,
IMessageDispatcher dispatcher,
IMessageSerializer serializer,
IGatewayAuthValidator authValidator,
IConnectionMultiplexer redis,
IOptions<GatewayOptions> options,
ILogger<ConnectionLoop> logger)
{
_connectionManager = connectionManager;
_dispatcher = dispatcher;
_serializer = serializer;
_authValidator = authValidator;
_redis = redis;
_options = options.Value;
_logger = logger;
_dispatcher = dispatcher;
_serializer = serializer;
_authValidator = authValidator;
_redis = redis;
_options = options.Value;
_logger = logger;
}
/// <summary>
/// Runs the full connection lifecycle for a raw, unauthenticated IClientConnection.
///
/// This method is called by GatewayHostedService as a fire-and-forget Task.
/// It handles its own exceptions — errors here must not propagate to the accept loop.
///
/// The 'appCancellationToken' is the application shutdown token. When cancelled,
/// the connection closes gracefully.
/// </summary>
public async Task RunAsync(
IClientConnection rawConnection,
CancellationToken appCancellationToken)
{
// 'authConn' is null until the handshake completes.
// Used in finally to decide whether to unregister from ConnectionManager.
AuthenticatedConnection? authConn = null;
RedisPushSubscriber? pushSubscriber = null;
AuthenticatedConnection? authConn = null;
RedisPushSubscriber? pushSubscriber = null;
try
{
// ── Phase 1: Auth Handshake ────────────────────────────────────────────
// ── Phase 1: Receive first message ────────────────────────────────────
_logger.LogDebug(
"Connection accepted: ConnectionId={ConnectionId} Remote={Remote}",
rawConnection.ConnectionId, rawConnection.RemoteAddress);
// Create a combined cancellation token: cancel if either the app shuts down
// OR the auth timeout expires. Whichever comes first.
//
// CancellationTokenSource.CreateLinkedTokenSource creates a new token that
// is cancelled when ANY of the source tokens are cancelled.
using var authTimeoutSts =
new CancellationTokenSource(TimeSpan.FromMilliseconds(_options.AuthTimeoutMs));
using var authLinked = CancellationTokenSource.CreateLinkedTokenSource(
appCancellationToken, authTimeoutSts.Token);
// Wait for the first message. Must be auth.hello.
// Returns null on clean close (client disconnected before sending anything).
var rawMsg = await rawConnection.ReceiveAsync(authLinked.Token);
if (rawMsg is null)
@@ -102,8 +80,6 @@ public sealed class ConnectionLoop
return;
}
// Parse the envelope (type, seq, inner payload bytes).
// rawMsg.Payload contains the full wire bytes (envelope + payload).
IClientMessage parsedMsg;
try
{
@@ -118,80 +94,102 @@ public sealed class ConnectionLoop
return;
}
// The first message MUST be auth.hello.
if (!string.Equals(parsedMsg.Type, "auth.hello", StringComparison.OrdinalIgnoreCase))
// ── Phase 2: Auth Handshake — hello / login / register ────────────────
//
// auth.hello { sessionToken } — reconnect with saved token
// auth.login { email, password } — credential login
// auth.register { email, password, displayName } — new account
string sessionToken;
string userId;
string displayName;
string ackType;
switch (parsedMsg.Type.ToLowerInvariant())
{
_logger.LogWarning(
"First message is not auth.hello: Type={Type} ConnectionId={ConnectionId}",
parsedMsg.Type, rawConnection.ConnectionId);
case "auth.hello":
{
AuthHelloPayload payload;
try { payload = _serializer.DeserializePayload<AuthHelloPayload>(parsedMsg.Payload); }
catch { await RejectAsync(rawConnection, parsedMsg.Seq, "INVALID_PAYLOAD", "auth.hello payload is malformed.", appCancellationToken); return; }
await SendErrorAsync(rawConnection, parsedMsg.Seq,
"AUTH_REQUIRED", "First message must be auth.hello.", appCancellationToken);
await rawConnection.CloseAsync("auth_required", appCancellationToken);
return;
}
var (valid, uid, dname) =
await _authValidator.ValidateAsync(payload.SessionToken, appCancellationToken);
if (!valid)
{
await RejectAsync(rawConnection, parsedMsg.Seq,
"AUTH_FAILED", "Invalid or expired session token.", appCancellationToken);
return;
}
(sessionToken, userId, displayName, ackType) =
(payload.SessionToken, uid, dname, "auth.hello.ack");
break;
}
// Deserialize the auth.hello payload to get the session token.
AuthHelloPayload helloPayload;
try
{
helloPayload = _serializer.DeserializePayload<AuthHelloPayload>(parsedMsg.Payload);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"Failed to deserialize auth.hello payload: ConnectionId={ConnectionId}",
rawConnection.ConnectionId);
await SendErrorAsync(rawConnection, parsedMsg.Seq,
"INVALID_PAYLOAD", "auth.hello payload is malformed.", appCancellationToken);
await rawConnection.CloseAsync("invalid_payload", appCancellationToken);
return;
}
case "auth.login":
{
AuthLoginPayload payload;
try { payload = _serializer.DeserializePayload<AuthLoginPayload>(parsedMsg.Payload); }
catch { await RejectAsync(rawConnection, parsedMsg.Seq, "INVALID_PAYLOAD", "auth.login payload is malformed.", appCancellationToken); return; }
// ── Phase 2: Token Validation ──────────────────────────────────────────
var (success, errorCode, token, uid, dname) =
await _authValidator.LoginAsync(payload.Email, payload.Password, appCancellationToken);
if (!success)
{
await RejectAsync(rawConnection, parsedMsg.Seq, errorCode, "Login failed.", appCancellationToken);
return;
}
(sessionToken, userId, displayName, ackType) =
(token, uid, dname, "auth.login.ack");
break;
}
var (isValid, userId, displayName) =
await _authValidator.ValidateAsync(helloPayload.SessionToken, appCancellationToken);
case "auth.register":
{
AuthRegisterPayload payload;
try { payload = _serializer.DeserializePayload<AuthRegisterPayload>(parsedMsg.Payload); }
catch { await RejectAsync(rawConnection, parsedMsg.Seq, "INVALID_PAYLOAD", "auth.register payload is malformed.", appCancellationToken); return; }
if (!isValid)
{
_logger.LogInformation(
"Auth failed: ConnectionId={ConnectionId} Remote={Remote}",
rawConnection.ConnectionId, rawConnection.RemoteAddress);
var (success, errorCode, token, uid, dname) =
await _authValidator.RegisterAsync(
payload.Email, payload.Password, payload.DisplayName, appCancellationToken);
if (!success)
{
await RejectAsync(rawConnection, parsedMsg.Seq, errorCode, "Registration failed.", appCancellationToken);
return;
}
(sessionToken, userId, displayName, ackType) =
(token, uid, dname, "auth.register.ack");
break;
}
await SendErrorAsync(rawConnection, parsedMsg.Seq,
"AUTH_FAILED", "Invalid or expired session token.", appCancellationToken);
await rawConnection.CloseAsync("auth_failed", appCancellationToken);
return;
default:
_logger.LogWarning(
"First message is not an auth type: Type={Type} ConnectionId={ConnectionId}",
parsedMsg.Type, rawConnection.ConnectionId);
await RejectAsync(rawConnection, parsedMsg.Seq, "AUTH_REQUIRED",
"First message must be auth.hello, auth.login, or auth.register.",
appCancellationToken);
return;
}
// ── Phase 3: Promote to Authenticated Connection ───────────────────────
authConn = new AuthenticatedConnection(
rawConnection, userId, displayName, helloPayload.SessionToken);
authConn = new AuthenticatedConnection(rawConnection, userId, displayName, sessionToken);
_connectionManager.Register(authConn);
_logger.LogInformation(
"User authenticated: UserId={UserId} DisplayName={DisplayName} " +
"ConnectionId={ConnectionId}",
userId, displayName, rawConnection.ConnectionId);
"User authenticated via {Type}: UserId={UserId} DisplayName={DisplayName} ConnectionId={ConnectionId}",
parsedMsg.Type, userId, displayName, rawConnection.ConnectionId);
// Send acknowledgement to client.
// Ack includes sessionToken so the client can persist it after login/register.
await SendMessageAsync(
rawConnection,
ServerMessage.Reply("auth.hello.ack", parsedMsg.Seq, new
{
userId,
displayName
}),
ServerMessage.Reply(ackType, parsedMsg.Seq, new { userId, displayName, sessionToken }),
appCancellationToken);
// ── Phase 4: Subscribe to Redis Push Channel ───────────────────────────
// Create a logger for the push subscriber that includes the userId.
// GetRequiredService<ILogger{RedisPushSubscriber}> would give a generic logger;
// we use CreateLogger with a category name that includes the userId for filtering.
var pushLogger = _logger as ILogger<RedisPushSubscriber>
?? Microsoft.Extensions.Logging.Abstractions.NullLogger<RedisPushSubscriber>.Instance;
@@ -202,8 +200,6 @@ public sealed class ConnectionLoop
while (rawConnection.IsConnected && !appCancellationToken.IsCancellationRequested)
{
// Wait for the next message from the client.
// Returns null on clean close (client sent WebSocket close frame).
IClientMessage? nextRaw;
try
{
@@ -211,21 +207,17 @@ public sealed class ConnectionLoop
}
catch (OperationCanceledException)
{
// App is shutting down — exit the loop cleanly.
break;
}
catch (Exception ex)
{
// Network error (connection dropped unexpectedly).
_logger.LogDebug(ex,
"Receive error for user {UserId}: connection dropped",
userId);
"Receive error for user {UserId}: connection dropped", userId);
break;
}
if (nextRaw is null) break; // Clean close from client.
if (nextRaw is null) break;
// Parse the message envelope.
IClientMessage nextMsg;
try
{
@@ -235,13 +227,11 @@ public sealed class ConnectionLoop
{
_logger.LogWarning(ex,
"Failed to deserialize message from user {UserId}", userId);
// Malformed message: send an error but keep the connection alive.
await SendErrorAsync(rawConnection, 0,
"INVALID_MESSAGE", "Message could not be parsed.", appCancellationToken);
continue;
}
// Check that a handler exists for this message type.
if (!_dispatcher.HasHandler(nextMsg.Type))
{
_logger.LogDebug(
@@ -254,7 +244,6 @@ public sealed class ConnectionLoop
continue;
}
// Dispatch to the registered handler.
IServerMessage? response;
try
{
@@ -263,7 +252,6 @@ public sealed class ConnectionLoop
}
catch (Exception ex)
{
// Handler threw an unexpected exception.
_logger.LogError(ex,
"Handler for '{Type}' threw for user {UserId}",
nextMsg.Type, userId);
@@ -272,41 +260,30 @@ public sealed class ConnectionLoop
continue;
}
// Send the handler's reply if one was returned.
if (response is not null)
{
await SendMessageAsync(rawConnection, response, appCancellationToken);
}
}
}
catch (OperationCanceledException)
{
// Normal exit: auth timeout fired, or app shutdown, or client disconnected.
// OperationCanceledException is not an error — it's the expected exit signal.
_logger.LogDebug(
"Connection loop cancelled: ConnectionId={ConnectionId}",
rawConnection.ConnectionId);
}
catch (Exception ex)
{
// Unexpected error in the connection loop itself (not in a handler).
_logger.LogError(ex,
"Unexpected error in connection loop: ConnectionId={ConnectionId}",
rawConnection.ConnectionId);
}
finally
{
// ── Phase 6: Cleanup — ALWAYS runs, regardless of how the loop exited ──
// Unsubscribe from Redis push channel.
if (pushSubscriber is not null)
await pushSubscriber.DisposeAsync();
// Unregister from the connection map.
if (authConn is not null)
_connectionManager.Unregister(rawConnection.ConnectionId);
// Dispose the connection (closes WebSocket, signals middleware done TCS).
await rawConnection.DisposeAsync();
_logger.LogDebug(
@@ -317,13 +294,9 @@ public sealed class ConnectionLoop
// ── Private helpers ────────────────────────────────────────────────────────
/// <summary>
/// Serializes and sends a message to the raw (pre-auth) or authenticated connection.
/// Errors here are swallowed — if the send fails the connection is already gone.
/// </summary>
private async Task SendMessageAsync(
IClientConnection connection,
IServerMessage message,
IServerMessage message,
CancellationToken cancellationToken)
{
try
@@ -341,25 +314,24 @@ public sealed class ConnectionLoop
private Task SendErrorAsync(
IClientConnection connection,
int refSeq,
string errorCode,
string errorMessage,
int refSeq, string errorCode, string errorMessage,
CancellationToken cancellationToken) =>
SendMessageAsync(
connection,
SendMessageAsync(connection,
ServerMessage.Error(refSeq, errorCode, errorMessage),
cancellationToken);
// ── Inner type: auth.hello payload ────────────────────────────────────────
private async Task RejectAsync(
IClientConnection connection,
int refSeq, string errorCode, string errorMessage,
CancellationToken cancellationToken)
{
await SendErrorAsync(connection, refSeq, errorCode, errorMessage, cancellationToken);
await connection.CloseAsync(errorCode.ToLowerInvariant(), cancellationToken);
}
// ── Auth payload types ─────────────────────────────────────────────────────
/// <summary>
/// Deserialization target for the auth.hello message payload.
///
/// Client sends:
/// { "type": "auth.hello", "seq": 1, "payload": { "sessionToken": "abc123..." } }
///
/// 'record' with 'init' properties: immutable after deserialization.
/// Properties must match JSON keys (camelCase by default via IMessageSerializer options).
/// </summary>
private sealed record AuthHelloPayload(string SessionToken);
private sealed record AuthLoginPayload(string Email, string Password);
private sealed record AuthRegisterPayload(string Email, string Password, string DisplayName);
}