Replace login/register forms with Keycloak sign-in flow

- LoginScreen: single "Sign in with Aeternalis" button replaces two-tab
  email/password/register layout; all credential encryption removed
- login_screen.gd: wires Keycloak.token_received → Auth.login_with_keycloak,
  handles auth_error and auth_failed signals
- Auth.gd: rewritten to use Keycloak session tokens; stores Keycloak refresh
  token for silent re-auth; calls Keycloak.revoke on logout
- Keycloak.gd: new autoload implementing Authorization Code + PKCE with
  loopback redirect, silent refresh, and fire-and-forget revocation
- project.godot: register Keycloak as autoload singleton

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-04-02 15:04:43 -04:00
co-authored by Claude Happy
parent d5363fa014
commit 39253716ad
5 changed files with 504 additions and 380 deletions
+149 -78
View File
@@ -1,39 +1,54 @@
extends Node
## Authentication autoload.
##
## Drives the auth handshake (auth.hello / auth.login / auth.register) as the
## first WebSocket message on every connection. Persists the session token to
## disk so the next session can reconnect silently.
## Drives the auth handshake as the first WebSocket message on every connection:
## auth.hello — resume a saved SOR session token (silent reconnect)
## auth.keycloak — exchange a Keycloak access token for a new SOR session token
##
## Scenes interact with this node via signals and the three public methods.
## Persists the SOR session token (30-day opaque token) and the Keycloak refresh
## token to disk so the player stays logged in across restarts.
##
## Silent re-authentication flow:
## 1. On connect, send auth.hello with saved SOR session token.
## 2. If rejected (token expired/revoked): clear session, use saved Keycloak
## refresh token to silently obtain a new Keycloak access token, then
## reconnect and send auth.keycloak — no browser required.
## 3. If the Keycloak refresh token is also expired: route to LoginScreen.
##
## Signals:
## auth_success(user_id, display_name) — auth succeeded; switch to main screen
## auth_failed(error_code, message) — auth rejected; show error to user
## session_expired — auto-logout fired after disconnect timeout
## session_expired — disconnect timeout fired auto-logout
const SAVE_PATH := "user://auth.cfg"
const SECTION := "auth"
## Saved sessions older than this are discarded on load (forces re-login).
## Sessions older than this are discarded on load (forces re-login).
const SESSION_TTL_DAYS := 30
## If the WebSocket stays disconnected for this many minutes while logged in,
## automatically clear the session and return to the login screen.
## If disconnected for this many minutes while logged in, auto-logout.
const DISCONNECT_LOGOUT_MIN := 30
signal auth_success(user_id: String, display_name: String)
signal auth_failed(error_code: String, message: String)
signal session_expired ## Fired when the disconnect timeout logs the user out.
signal session_expired
## Set after a successful auth. Empty while unauthenticated.
var user_id: String = ""
var display_name: String = ""
var session_token: String = ""
## True when the authenticated account has not yet selected a starter deck.
## Reset to false on logout. Checked by login_screen.gd to route new players
## to StarterDeckScreen instead of the normal InitScreen flow.
var needs_starter_deck: bool = false
var user_id: String = ""
var display_name: String = ""
var session_token: String = ""
var needs_starter_deck: bool = false
## Keycloak refresh token — persisted to enable silent re-auth when the SOR
## session token expires. Cleared on logout.
var keycloak_refresh_token: String = ""
## Pending Keycloak access token waiting for the next WebSocket connection.
## Set by _try_silent_refresh and login_with_keycloak; consumed in _on_network_connected.
var _pending_keycloak_token: String = ""
## True while a silent Keycloak refresh is in-flight (prevents duplicate attempts).
var _refresh_in_progress: bool = false
## Monotonic timestamp (seconds) when the last disconnect started; -1 = connected.
var _disconnect_at: float = -1.0
@@ -57,82 +72,137 @@ func _process(_delta: float) -> void:
# ── Public API ────────────────────────────────────────────────────────────────
## Attempt to sign in with email and password.
## Call from the login form.
func login(email: String, password: String) -> void:
Network.request(
"auth.login",
{ "email": email, "password": password },
func(_type: String, p: Variant): _on_auth_ok(p),
func(code: String, msg: String): auth_failed.emit(code, msg)
)
## Exchange a freshly obtained Keycloak access token for a SOR session token.
## Also stores the refresh token so silent re-auth works on next session.
## Called by login_screen.gd after Keycloak.token_received fires.
func login_with_keycloak(access_token: String, refresh_token: String) -> void:
keycloak_refresh_token = refresh_token
_save_session()
_pending_keycloak_token = access_token
if Network.is_online():
_send_keycloak_auth()
# else: _on_network_connected will send it once the socket connects.
## Attempt to create a new account.
## Call from the register form.
func register(email: String, password: String, disp_name: String) -> void:
Network.request(
"auth.register",
{ "email": email, "password": password, "displayName": disp_name },
func(_type: String, p: Variant): _on_auth_ok(p),
func(code: String, msg: String): auth_failed.emit(code, msg)
)
## Clear the saved session and reset auth state.
## Clear all auth state and disconnect, returning to the login screen.
func logout() -> void:
user_id = ""
display_name = ""
session_token = ""
needs_starter_deck = false
# Revoke the Keycloak refresh token with the server (fire-and-forget).
if not keycloak_refresh_token.is_empty():
Keycloak.revoke(keycloak_refresh_token)
user_id = ""
display_name = ""
session_token = ""
keycloak_refresh_token = ""
_pending_keycloak_token = ""
needs_starter_deck = false
_refresh_in_progress = false
_save_session()
Network.force_reconnect()
# ── Private ───────────────────────────────────────────────────────────────────
# ── Internal connection handlers ──────────────────────────────────────────────
## Called every time the WebSocket connects (including after reconnects).
## Cancels the disconnect timer. If a session token is saved, sends auth.hello.
func _on_network_connected() -> void:
_disconnect_at = -1.0 # Cancel any pending auto-logout.
if session_token.is_empty():
return # No token — LoginScreen will drive login/register.
_disconnect_at = -1.0
Network.request(
"auth.hello",
{ "sessionToken": session_token },
func(_type: String, p: Variant): _on_auth_ok(p),
func(code: String, msg: String):
if code == "DISCONNECTED":
# Transient network drop — keep the token and retry on reconnect.
auth_failed.emit(code, msg)
return
# Session explicitly rejected (expired / revoked / invalid).
# Wipe all auth state, emit the failure, then drive the scene
# change here so every screen (main, collection, etc.) is covered
# without each needing its own auth_failed handler.
logout()
auth_failed.emit(code, msg)
get_tree().change_scene_to_file("res://scenes/login/LoginScreen.tscn")
)
if not session_token.is_empty():
# Try to resume the existing SOR session silently.
Network.request(
"auth.hello",
{ "sessionToken": session_token },
func(_type: String, p: Variant): _on_auth_ok(p),
func(code: String, msg: String):
if code == "DISCONNECTED":
# Transient drop — keep the token and retry on next reconnect.
auth_failed.emit(code, msg)
return
# SOR session rejected (expired / revoked).
session_token = ""
_save_session()
if not keycloak_refresh_token.is_empty() and not _refresh_in_progress:
_try_silent_refresh()
else:
_do_logout_and_redirect(code, msg)
)
return
if not _pending_keycloak_token.is_empty():
_send_keycloak_auth()
return
# No credentials — LoginScreen will drive login.
## Called every time the WebSocket disconnects.
## Starts the auto-logout countdown (only if logged in).
func _on_network_disconnected() -> void:
if not session_token.is_empty():
_disconnect_at = _now()
func _send_keycloak_auth() -> void:
var token := _pending_keycloak_token
_pending_keycloak_token = ""
Network.request(
"auth.keycloak",
{ "keycloakToken": token },
func(_type: String, p: Variant): _on_auth_ok(p),
func(code: String, msg: String):
# Keycloak token rejected (invalid, expired, missing role).
keycloak_refresh_token = ""
_save_session()
auth_failed.emit(code, msg)
get_tree().change_scene_to_file("res://scenes/login/LoginScreen.tscn")
)
## Attempt to silently refresh the Keycloak refresh token and re-establish the session.
func _try_silent_refresh() -> void:
_refresh_in_progress = true
Keycloak.token_refreshed.connect(
func(access_token: String, refresh_token: String) -> void:
_refresh_in_progress = false
keycloak_refresh_token = refresh_token # Rotate: Keycloak issues a new one.
_save_session()
_pending_keycloak_token = access_token
Network.force_reconnect(),
CONNECT_ONE_SHOT)
Keycloak.auth_error.connect(
func(msg: String) -> void:
_refresh_in_progress = false
keycloak_refresh_token = "" # Refresh token expired — full re-login required.
_save_session()
_do_logout_and_redirect("AUTH_FAILED", msg),
CONNECT_ONE_SHOT)
Keycloak.refresh(keycloak_refresh_token)
func _on_auth_ok(payload: Variant) -> void:
var p := payload as Dictionary
user_id = p.get("userId", "")
display_name = p.get("displayName", "")
session_token = p.get("sessionToken", "")
needs_starter_deck = p.get("needsStarterDeck", false)
user_id = p.get("userId", "")
display_name = p.get("displayName", "")
session_token = p.get("sessionToken", "")
needs_starter_deck = p.get("needsStarterDeck", false)
_save_session()
auth_success.emit(user_id, display_name)
func _do_logout_and_redirect(code: String = "AUTH_FAILED", msg: String = "") -> void:
# Full state wipe without revoking the Keycloak token (it's already gone).
user_id = ""
display_name = ""
session_token = ""
keycloak_refresh_token = ""
_pending_keycloak_token = ""
needs_starter_deck = false
_save_session()
Network.force_reconnect()
auth_failed.emit(code, msg)
get_tree().change_scene_to_file("res://scenes/login/LoginScreen.tscn")
# ── Persistence ───────────────────────────────────────────────────────────────
func _load_session() -> void:
var cfg := ConfigFile.new()
if cfg.load(SAVE_PATH) != OK:
@@ -142,18 +212,19 @@ func _load_session() -> void:
if saved_at > 0:
var age_days := (int(Time.get_unix_time_from_system()) - saved_at) / 86400
if age_days >= SESSION_TTL_DAYS:
return # Expired — treat as fresh launch.
session_token = cfg.get_value(SECTION, "session_token", "")
user_id = cfg.get_value(SECTION, "user_id", "")
display_name = cfg.get_value(SECTION, "display_name", "")
return
session_token = cfg.get_value(SECTION, "session_token", "")
user_id = cfg.get_value(SECTION, "user_id", "")
display_name = cfg.get_value(SECTION, "display_name", "")
keycloak_refresh_token = cfg.get_value(SECTION, "keycloak_refresh_token", "")
func _save_session() -> void:
var cfg := ConfigFile.new()
cfg.set_value(SECTION, "session_token", session_token)
cfg.set_value(SECTION, "user_id", user_id)
cfg.set_value(SECTION, "display_name", display_name)
# Only write a timestamp when there is an active session to expire.
cfg.set_value(SECTION, "session_token", session_token)
cfg.set_value(SECTION, "user_id", user_id)
cfg.set_value(SECTION, "display_name", display_name)
cfg.set_value(SECTION, "keycloak_refresh_token", keycloak_refresh_token)
if not session_token.is_empty():
cfg.set_value(SECTION, "saved_at", int(Time.get_unix_time_from_system()))
cfg.save(SAVE_PATH)
+310
View File
@@ -0,0 +1,310 @@
extends Node
## Keycloak OAuth2 Authorization Code + PKCE handler (RFC 7636 / RFC 8252).
##
## Registered as an autoload singleton (Keycloak).
##
## Usage:
## Keycloak.start_auth_flow() — opens system browser, emits token_received on success
## Keycloak.refresh(refresh_token) — silent re-auth, emits token_refreshed on success
## Keycloak.revoke(refresh_token) — fire-and-forget token revocation on logout
##
## Both start_auth_flow and refresh emit auth_error(message) on failure.
##
## Flow:
## 1. Generate PKCE code_verifier (64 random bytes → base64url)
## 2. Compute code_challenge = BASE64URL(SHA256(verifier))
## 3. Open system browser to Keycloak auth URL
## 4. Bind a loopback TCP listener (ports 7370-7374) for the redirect
## 5. Browser redirects to http://127.0.0.1:{port}/callback?code=...&state=...
## 6. Validate state, exchange code + verifier for tokens via HTTP POST
## 7. Emit token_received(access_token, refresh_token)
const AUTHORITY := "https://auth.aeternalisgames.com/realms/aeternalis"
const CLIENT_ID := "sor-game"
const TOKEN_URL := AUTHORITY + "/protocol/openid-connect/token"
const AUTH_URL := AUTHORITY + "/protocol/openid-connect/auth"
const REVOKE_URL := AUTHORITY + "/protocol/openid-connect/revoke"
## Loopback ports tried in order; first available wins.
## Register "http://127.0.0.1:*" (or each port) as valid redirect URIs in Keycloak.
const REDIRECT_PORTS := [7370, 7371, 7372, 7373, 7374]
## Emitted when a fresh login yields access + refresh tokens.
signal token_received(access_token: String, refresh_token: String)
## Emitted when a silent refresh yields a new token pair.
signal token_refreshed(access_token: String, refresh_token: String)
## Emitted on any error in the flow.
signal auth_error(message: String)
# ── State ─────────────────────────────────────────────────────────────────────
var _tcp_server : TCPServer = null
var _pending_peer : StreamPeerTCP = null
var _pending_raw : String = ""
var _redirect_port : int = -1
var _code_verifier : String = ""
var _state : String = ""
# Two dedicated HTTPRequest nodes so exchange and refresh never share one.
var _exchange_http : HTTPRequest
var _refresh_http : HTTPRequest
func _ready() -> void:
_exchange_http = HTTPRequest.new()
_refresh_http = HTTPRequest.new()
add_child(_exchange_http)
add_child(_refresh_http)
func _process(_delta: float) -> void:
_poll_tcp()
# ── Public API ────────────────────────────────────────────────────────────────
## Begin the Authorization Code + PKCE login flow.
## Opens the system browser; listen for token_received or auth_error.
func start_auth_flow() -> void:
# Tear down any stale listener from a previous attempt.
_cleanup_listener()
_code_verifier = _generate_code_verifier()
var challenge := _code_challenge(_code_verifier)
_state = _random_state()
_redirect_port = _start_listener()
if _redirect_port < 0:
auth_error.emit("Could not bind a local redirect port (tried 7370-7374).")
return
var redirect_uri := "http://127.0.0.1:%d/callback" % _redirect_port
var params := {
"client_id": CLIENT_ID,
"response_type": "code",
"scope": "openid email profile",
"redirect_uri": redirect_uri,
"state": _state,
"code_challenge": challenge,
"code_challenge_method": "S256",
}
OS.shell_open(AUTH_URL + "?" + _encode_params(params))
## Silently exchange a stored refresh token for a new token pair.
## Emits token_refreshed on success, auth_error on failure (e.g. refresh expired).
func refresh(refresh_token: String) -> void:
if _refresh_http.get_http_client_status() != HTTPClient.STATUS_DISCONNECTED:
auth_error.emit("A token refresh is already in progress.")
return
var body := _encode_params({
"grant_type": "refresh_token",
"client_id": CLIENT_ID,
"refresh_token": refresh_token,
})
_refresh_http.request_completed.connect(_on_refresh_completed, CONNECT_ONE_SHOT)
var err := _refresh_http.request(
TOKEN_URL,
["Content-Type: application/x-www-form-urlencoded"],
HTTPClient.METHOD_POST,
body)
if err != OK:
auth_error.emit("Failed to start refresh request (error %d)." % err)
## Fire-and-forget revocation of a refresh token on logout.
## No signal is emitted — errors are silently ignored.
func revoke(refresh_token: String) -> void:
var http := HTTPRequest.new()
add_child(http)
var body := _encode_params({
"token": refresh_token,
"token_type_hint": "refresh_token",
"client_id": CLIENT_ID,
})
http.request_completed.connect(func(_r, _s, _h, _b): http.queue_free(), CONNECT_ONE_SHOT)
http.request(REVOKE_URL,
["Content-Type: application/x-www-form-urlencoded"],
HTTPClient.METHOD_POST, body)
# ── TCP loopback listener ─────────────────────────────────────────────────────
func _start_listener() -> int:
for port: int in REDIRECT_PORTS:
var srv := TCPServer.new()
if srv.listen(port, "127.0.0.1") == OK:
_tcp_server = srv
return port
return -1
func _cleanup_listener() -> void:
if _tcp_server != null:
_tcp_server.stop()
_tcp_server = null
if _pending_peer != null:
_pending_peer.disconnect_from_host()
_pending_peer = null
_pending_raw = ""
## Called every frame from _process to non-blockingly drain the loopback socket.
func _poll_tcp() -> void:
# Accept a new connection when available.
if _tcp_server != null and _tcp_server.is_connection_available():
_pending_peer = _tcp_server.take_connection()
_tcp_server.stop()
_tcp_server = null
_pending_raw = ""
if _pending_peer == null:
return
_pending_peer.poll()
var available := _pending_peer.get_available_bytes()
if available > 0:
var result := _pending_peer.get_data(available)
if result[0] == OK:
_pending_raw += (result[1] as PackedByteArray).get_string_from_utf8()
# Wait until we have the full HTTP request line + headers.
if not "\r\n\r\n" in _pending_raw:
return
# Respond to the browser immediately so it shows a completion page.
var html := (
"<html><body style='"
+ "font-family:sans-serif;background:#0f0f18;color:#ccc;"
+ "display:flex;flex-direction:column;align-items:center;"
+ "justify-content:center;height:100vh;margin:0'>"
+ "<h2 style='color:#4af'>Authentication complete.</h2>"
+ "<p>You can close this tab and return to the game.</p>"
+ "</body></html>")
var resp := (
"HTTP/1.1 200 OK\r\n"
+ "Content-Type: text/html; charset=utf-8\r\n"
+ "Content-Length: %d\r\n" % html.length()
+ "Connection: close\r\n\r\n"
+ html)
_pending_peer.put_data(resp.to_utf8_buffer())
_pending_peer.disconnect_from_host()
var raw := _pending_raw
_pending_peer = null
_pending_raw = ""
_handle_callback(raw)
func _handle_callback(raw_request: String) -> void:
# Extract path from "GET /callback?code=...&state=... HTTP/1.1"
var first_line := raw_request.split("\r\n")[0]
var parts := first_line.split(" ")
var path := parts[1] if parts.size() > 1 else ""
var query := path.split("?")[1] if "?" in path else ""
var params := _parse_query(query)
if params.has("error"):
auth_error.emit(
"Keycloak: " + str(params.get("error_description", params.get("error", "unknown"))))
return
if not params.has("code"):
auth_error.emit("No authorization code in the redirect.")
return
if params.get("state", "") != _state:
auth_error.emit("State mismatch — possible CSRF attempt, login aborted.")
return
_exchange_code(params["code"])
func _exchange_code(code: String) -> void:
if _exchange_http.get_http_client_status() != HTTPClient.STATUS_DISCONNECTED:
auth_error.emit("Token exchange already in progress.")
return
var body := _encode_params({
"grant_type": "authorization_code",
"client_id": CLIENT_ID,
"code": code,
"redirect_uri": "http://127.0.0.1:%d/callback" % _redirect_port,
"code_verifier": _code_verifier,
})
_exchange_http.request_completed.connect(_on_exchange_completed, CONNECT_ONE_SHOT)
var err := _exchange_http.request(
TOKEN_URL,
["Content-Type: application/x-www-form-urlencoded"],
HTTPClient.METHOD_POST,
body)
if err != OK:
auth_error.emit("Failed to start token exchange request (error %d)." % err)
# ── HTTP response handlers ────────────────────────────────────────────────────
func _on_exchange_completed(
_result: int, status: int,
_headers: PackedStringArray, body: PackedByteArray) -> void:
var json := JSON.parse_string(body.get_string_from_utf8())
if status != 200 or json == null or not (json is Dictionary):
auth_error.emit("Token exchange failed (HTTP %d)." % status)
return
var d := json as Dictionary
if d.has("error"):
auth_error.emit("Token exchange error: " + str(d.get("error_description", d["error"])))
return
token_received.emit(str(d.get("access_token", "")), str(d.get("refresh_token", "")))
func _on_refresh_completed(
_result: int, status: int,
_headers: PackedStringArray, body: PackedByteArray) -> void:
var json := JSON.parse_string(body.get_string_from_utf8())
if status != 200 or json == null or not (json is Dictionary):
auth_error.emit("Token refresh failed (HTTP %d)." % status)
return
var d := json as Dictionary
if d.has("error"):
auth_error.emit("Token refresh error: " + str(d.get("error_description", d["error"])))
return
token_refreshed.emit(str(d.get("access_token", "")), str(d.get("refresh_token", "")))
# ── PKCE helpers ──────────────────────────────────────────────────────────────
## RFC 7636 §4.1 — 64 random bytes → 86-char base64url string (within 43-128 range).
func _generate_code_verifier() -> String:
return _base64url(Crypto.new().generate_random_bytes(64))
## RFC 7636 §4.2 — S256 challenge = BASE64URL(SHA256(ASCII(verifier))).
func _code_challenge(verifier: String) -> String:
var ctx := HashingContext.new()
ctx.start(HashingContext.HASH_SHA256)
ctx.update(verifier.to_utf8_buffer())
return _base64url(ctx.finish())
func _random_state() -> String:
return _base64url(Crypto.new().generate_random_bytes(16))
## Standard base64 → base64url: replace +/→-_, strip padding.
func _base64url(data: PackedByteArray) -> String:
return Marshalls.raw_to_base64(data) \
.replace("+", "-") \
.replace("/", "_") \
.replace("=", "")
func _encode_params(p: Dictionary) -> String:
var parts: Array[String] = []
for k: String in p:
parts.append(k.uri_encode() + "=" + str(p[k]).uri_encode())
return "&".join(parts)
func _parse_query(query: String) -> Dictionary:
var result := {}
for pair: String in query.split("&"):
if "=" in pair:
var idx := pair.find("=")
result[pair.left(idx).uri_decode()] = pair.substr(idx + 1).uri_decode()
return result