Files
sor/Client/origin-client/autoloads/Keycloak.gd
T
60d6098c11 Fix Keycloak login: force fresh WebSocket before auth.keycloak
The server closes idle unauthenticated connections after AuthTimeoutMs
(10 s). A user authenticating in the browser takes longer than that, so
the socket the client held while the browser was open is already dead
when token_received fires. Sending auth.keycloak on that stale
connection produces no reply and the scene never changes.

Fix: login_with_keycloak() now calls Network.force_reconnect() instead
of sending immediately. _on_network_connected() then sends auth.keycloak
as the guaranteed-first message on the fresh connection.

Also: DISCONNECTED errors in the auth.keycloak error callback no longer
clear keycloak_refresh_token, preserving silent re-auth on transient drops.

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 16:20:45 -04:00

311 lines
11 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, 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 : 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