Fix Keycloak auth: DISCONNECTED retry + web export support

PC native — connection lost, retrying:
  _send_keycloak_auth's DISCONNECTED handler was clearing _pending_keycloak_token
  (taken at top of function) without restoring it, so the next _on_network_connected
  had no token to retry with. Restore it: _pending_keycloak_token = token.

Web export — could not bind a local redirect port:
  Godot's HTML5 export cannot create TCP server sockets. Add a separate web
  code path in Keycloak.gd:
  - start_auth_flow() detects OS.get_name() == "Web" and navigates the page
    to Keycloak, persisting PKCE state (verifier, state, redirect_uri) in
    sessionStorage before the page leaves.
  - _check_web_callback() (called in _ready()) detects the ?code= params on
    return, recovers state from sessionStorage, cleans the URL via
    history.replaceState, then calls _exchange_code().
  - auth_in_progress flag lets login_screen show "Completing sign-in..."
    while the token exchange is in flight after page reload.
  Requires the web game's origin to be registered as a valid redirect URI
  in the Keycloak sor-game client.

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 16:39:13 -04:00
co-authored by Claude Happy
parent 60d6098c11
commit 1c6064e157
3 changed files with 105 additions and 14 deletions
+2 -2
View File
@@ -151,8 +151,8 @@ func _send_keycloak_auth() -> void:
func(_type: String, p: Variant): _on_auth_ok(p),
func(code: String, msg: String):
if code == "DISCONNECTED":
# Transient drop — keep the refresh token and surface the error.
# _on_network_connected will retry auth.keycloak on the next reconnect.
# Transient drop — restore the token so the next reconnect retries.
_pending_keycloak_token = token
auth_failed.emit(code, msg)
return
# Keycloak token rejected (invalid, expired, missing role).
+97 -12
View File
@@ -4,13 +4,13 @@ extends Node
## Registered as an autoload singleton (Keycloak).
##
## Usage:
## Keycloak.start_auth_flow() — opens system browser, emits token_received on success
## Keycloak.start_auth_flow() — opens system browser / redirects page, 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:
## Desktop / mobile flow (RFC 8252 native app):
## 1. Generate PKCE code_verifier (64 random bytes → base64url)
## 2. Compute code_challenge = BASE64URL(SHA256(verifier))
## 3. Open system browser to Keycloak auth URL
@@ -18,6 +18,14 @@ extends Node
## 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)
##
## Web (HTML5) flow:
## 1. Generate PKCE verifier + state, persist both to sessionStorage
## 2. Navigate the current page to the Keycloak auth URL
## 3. Keycloak redirects back to the same page with ?code=...&state=...
## 4. On startup (_ready), _check_web_callback detects the query params
## 5. Retrieve verifier + state from sessionStorage, exchange code for tokens
## 6. Emit token_received(access_token, refresh_token)
const AUTHORITY := "https://auth.aeternalisgames.com/realms/aeternalis"
const CLIENT_ID := "sor-game"
@@ -25,7 +33,7 @@ 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.
## Loopback ports tried in order; first available wins (desktop/mobile only).
## Register "http://127.0.0.1:*" (or each port) as valid redirect URIs in Keycloak.
const REDIRECT_PORTS := [7370, 7371, 7372, 7373, 7374]
@@ -42,9 +50,13 @@ var _tcp_server : TCPServer = null
var _pending_peer : StreamPeerTCP = null
var _pending_raw : String = ""
var _redirect_port : int = -1
var _redirect_uri : String = "" ## Full redirect URI used in the current flow.
var _code_verifier : String = ""
var _state : String = ""
## True while a web callback exchange is in-flight (login_screen reads this).
var auth_in_progress: bool = false
# Two dedicated HTTPRequest nodes so exchange and refresh never share one.
var _exchange_http : HTTPRequest
var _refresh_http : HTTPRequest
@@ -54,6 +66,9 @@ func _ready() -> void:
_refresh_http = HTTPRequest.new()
add_child(_exchange_http)
add_child(_refresh_http)
# Web export: check if we're returning from a Keycloak page redirect.
if OS.get_name() == "Web":
_check_web_callback()
func _process(_delta: float) -> void:
@@ -62,26 +77,51 @@ func _process(_delta: float) -> void:
# ── Public API ────────────────────────────────────────────────────────────────
## Begin the Authorization Code + PKCE login flow.
## Opens the system browser; listen for token_received or auth_error.
## Desktop/mobile: opens the system browser and starts a loopback TCP listener.
## Web: navigates the current page to Keycloak (page will reload on return).
## 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()
var params: Dictionary
if OS.get_name() == "Web":
# Redirect the page; on return _check_web_callback() handles the code.
_redirect_uri = JavaScriptBridge.eval(
"window.location.origin + window.location.pathname", true)
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",
}
# Persist PKCE state to sessionStorage before the page navigates away.
JavaScriptBridge.eval(
"sessionStorage.setItem('sor_cv','%s');" % _code_verifier.replace("'", "\\'")
+ "sessionStorage.setItem('sor_st','%s');" % _state.replace("'", "\\'")
+ "sessionStorage.setItem('sor_ru','%s');" % _redirect_uri.replace("'", "\\'")
+ "window.location.href='%s';" % (AUTH_URL + "?" + _encode_params(params)).replace("'", "\\'"))
return
# ── Desktop / mobile: loopback TCP ────────────────────────────────────────
_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 := {
_redirect_uri = "http://127.0.0.1:%d/callback" % _redirect_port
params = {
"client_id": CLIENT_ID,
"response_type": "code",
"scope": "openid email profile",
"redirect_uri": redirect_uri,
"redirect_uri": _redirect_uri,
"state": _state,
"code_challenge": challenge,
"code_challenge_method": "S256",
@@ -125,6 +165,49 @@ func revoke(refresh_token: String) -> void:
["Content-Type: application/x-www-form-urlencoded"],
HTTPClient.METHOD_POST, body)
# ── Web callback handler ──────────────────────────────────────────────────────
## Called from _ready() on the web export to detect a Keycloak redirect-back.
func _check_web_callback() -> void:
var search: String = JavaScriptBridge.eval("window.location.search", true)
if search.is_empty() or not ("code=" in search or "error=" in search):
return
var params := _parse_query(search.lstrip("?"))
# Recover PKCE state stored before the redirect.
var verifier : String = JavaScriptBridge.eval("sessionStorage.getItem('sor_cv') || ''", true)
var st : String = JavaScriptBridge.eval("sessionStorage.getItem('sor_st') || ''", true)
var ru : String = JavaScriptBridge.eval("sessionStorage.getItem('sor_ru') || ''", true)
# Always clean up sessionStorage and the URL so a page refresh is harmless.
JavaScriptBridge.eval(
"sessionStorage.removeItem('sor_cv');"
+ "sessionStorage.removeItem('sor_st');"
+ "sessionStorage.removeItem('sor_ru');"
+ "window.history.replaceState({},'',window.location.pathname);")
if params.has("error"):
auth_error.emit(
"Keycloak: " + str(params.get("error_description", params.get("error", "unknown"))))
return
if not params.has("code"):
return
if verifier.is_empty() or st.is_empty():
auth_error.emit("Auth state missing — please try signing in again.")
return
if params.get("state", "") != st:
auth_error.emit("State mismatch — possible CSRF attempt, login aborted.")
return
_code_verifier = verifier
_redirect_uri = ru
auth_in_progress = true
_exchange_code(params["code"])
# ── TCP loopback listener ─────────────────────────────────────────────────────
func _start_listener() -> int:
@@ -226,7 +309,7 @@ func _exchange_code(code: String) -> void:
"grant_type": "authorization_code",
"client_id": CLIENT_ID,
"code": code,
"redirect_uri": "http://127.0.0.1:%d/callback" % _redirect_port,
"redirect_uri": _redirect_uri,
"code_verifier": _code_verifier,
})
_exchange_http.request_completed.connect(_on_exchange_completed, CONNECT_ONE_SHOT)
@@ -236,6 +319,7 @@ func _exchange_code(code: String) -> void:
HTTPClient.METHOD_POST,
body)
if err != OK:
auth_in_progress = false
auth_error.emit("Failed to start token exchange request (error %d)." % err)
# ── HTTP response handlers ────────────────────────────────────────────────────
@@ -243,7 +327,8 @@ func _exchange_code(code: String) -> void:
func _on_exchange_completed(
_result: int, status: int,
_headers: PackedStringArray, body: PackedByteArray) -> void:
var json : Variant = JSON.parse_string(body.get_string_from_utf8())
auth_in_progress = false
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
@@ -257,7 +342,7 @@ func _on_exchange_completed(
func _on_refresh_completed(
_result: int, status: int,
_headers: PackedStringArray, body: PackedByteArray) -> void:
var json :Variant= JSON.parse_string(body.get_string_from_utf8())
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
@@ -32,6 +32,12 @@ func _ready() -> void:
sign_in_btn.pressed.connect(_on_sign_in_pressed)
# Web export: returning from Keycloak redirect — exchange is already in flight.
if Keycloak.auth_in_progress:
_set_status("Completing sign-in…", false)
_set_enabled(false)
return
# Show connecting / resume status while the socket is still coming up.
if not Auth.session_token.is_empty():
_set_status("Resuming session…", false)