Files
79fa08e192 Fix Keycloak: scene reload on error, web signal missed, redirect URI
PC — scene reloading on auth error:
  Auth.gd's keycloak error handler called change_scene_to_file(LoginScreen)
  after emitting auth_failed, which reloaded the scene and wiped the error
  message before the user could see it. Removed the scene change — the
  login screen is already active and handles auth_failed itself.

Web — token_received signal never handled after page redirect:
  login_screen._ready() returned early when Keycloak.auth_in_progress was
  true, before connecting Keycloak.token_received. When the exchange
  completed nobody was listening, so the game sat frozen. Signals are now
  connected before the early-return check.

Web — fragile redirect URI and sessionStorage injection:
  JavaScriptBridge.eval return value could stringify as "<null>". Now uses
  separate origin + pathname evals with a null check. sessionStorage items
  and the final navigation use uri_encode() + decodeURIComponent() instead
  of manual quote-escaping, preventing injection from PKCE values.

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>
2026-04-02 19:20:04 -04:00

405 lines
15 KiB
GDScript

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 / 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.
##
## 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
## 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)
##
## 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"
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 (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]
## 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 _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
func _ready() -> void:
_exchange_http = HTTPRequest.new()
_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:
_poll_tcp()
# ── Public API ────────────────────────────────────────────────────────────────
## Begin the Authorization Code + PKCE login flow.
## 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:
_cleanup_listener()
_code_verifier = _generate_code_verifier()
var challenge := _code_challenge(_code_verifier)
_state = _random_state()
var params: Dictionary
if OS.get_name() == "Web":
# Redirect the page; on return _check_web_callback() handles the code.
var origin : String = str(JavaScriptBridge.eval("window.location.origin", true))
var path : String = str(JavaScriptBridge.eval("window.location.pathname", true))
if origin.is_empty() or origin == "<null>":
auth_error.emit("Could not determine page origin for redirect URI.")
return
_redirect_uri = origin + path
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",
}
var auth_url := AUTH_URL + "?" + _encode_params(params)
# Persist PKCE state to sessionStorage before the page navigates away.
# Each item is set in a separate eval so no value can escape the string.
JavaScriptBridge.eval("sessionStorage.setItem('sor_cv', decodeURIComponent('%s'));" \
% _code_verifier.uri_encode())
JavaScriptBridge.eval("sessionStorage.setItem('sor_st', decodeURIComponent('%s'));" \
% _state.uri_encode())
JavaScriptBridge.eval("sessionStorage.setItem('sor_ru', decodeURIComponent('%s'));" \
% _redirect_uri.uri_encode())
JavaScriptBridge.eval("window.location.href = decodeURIComponent('%s');" \
% auth_url.uri_encode())
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
_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,
"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)
# ── 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:
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": _redirect_uri,
"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_in_progress = false
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:
auth_in_progress = false
var json :Variant= 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 :Variant= 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