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:
@@ -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)
|
||||
|
||||
@@ -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
|
||||
@@ -21,6 +21,7 @@ Network="*res://autoloads/Network.gd"
|
||||
ContentCache="*res://autoloads/ContentCache.gd"
|
||||
BoardTemplateCache="*res://autoloads/BoardTemplateCache.gd"
|
||||
Auth="*res://autoloads/Auth.gd"
|
||||
Keycloak="*res://autoloads/Keycloak.gd"
|
||||
CollectionCache="*res://autoloads/CollectionCache.gd"
|
||||
Chat="*res://autoloads/Chat.gd"
|
||||
Settings="*res://autoloads/Settings.gd"
|
||||
|
||||
@@ -62,124 +62,15 @@ text = "Stone of Revival"
|
||||
horizontal_alignment = 1
|
||||
|
||||
[node name="Spacer" type="Control" parent="Center/Panel/Margin/VBox"]
|
||||
custom_minimum_size = Vector2(0, 6)
|
||||
custom_minimum_size = Vector2(0, 16)
|
||||
layout_mode = 2
|
||||
|
||||
[node name="Tabs" type="TabContainer" parent="Center/Panel/Margin/VBox"]
|
||||
layout_mode = 2
|
||||
size_flags_vertical = 3
|
||||
tab_alignment = 1
|
||||
current_tab = 0
|
||||
|
||||
[node name="Login" type="VBoxContainer" parent="Center/Panel/Margin/VBox/Tabs"]
|
||||
layout_mode = 2
|
||||
theme_override_constants/separation = 8
|
||||
metadata/_tab_index = 0
|
||||
|
||||
[node name="Spacer" type="Control" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
custom_minimum_size = Vector2(0, 6)
|
||||
layout_mode = 2
|
||||
|
||||
[node name="EmailLabel" type="Label" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
layout_mode = 2
|
||||
text = "Channeler Email"
|
||||
horizontal_alignment = 1
|
||||
|
||||
[node name="EmailInput" type="LineEdit" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
[node name="SignInBtn" type="Button" parent="Center/Panel/Margin/VBox"]
|
||||
unique_name_in_owner = true
|
||||
custom_minimum_size = Vector2(0, 44)
|
||||
custom_minimum_size = Vector2(0, 52)
|
||||
layout_mode = 2
|
||||
theme_override_font_sizes/font_size = 15
|
||||
placeholder_text = "your@email.com"
|
||||
virtual_keyboard_type = 5
|
||||
|
||||
[node name="PasswordLabel" type="Label" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
layout_mode = 2
|
||||
tooltip_text = "Password"
|
||||
text = "Memory Seal"
|
||||
horizontal_alignment = 1
|
||||
|
||||
[node name="PasswordInput" type="LineEdit" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
unique_name_in_owner = true
|
||||
custom_minimum_size = Vector2(0, 44)
|
||||
layout_mode = 2
|
||||
theme_override_font_sizes/font_size = 15
|
||||
placeholder_text = "••••••••"
|
||||
secret = true
|
||||
|
||||
[node name="RememberMe" type="CheckBox" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
theme_override_font_sizes/font_size = 13
|
||||
theme_override_colors/checkbox_checked_color = Color(1, 1, 1, 1)
|
||||
theme_override_colors/checkbox_unchecked_color = Color(1, 1, 1, 1)
|
||||
text = "Remember me"
|
||||
|
||||
[node name="LoginSpacer" type="Control" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
custom_minimum_size = Vector2(0, 4)
|
||||
layout_mode = 2
|
||||
|
||||
[node name="LoginBtn" type="Button" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
unique_name_in_owner = true
|
||||
custom_minimum_size = Vector2(0, 48)
|
||||
layout_mode = 2
|
||||
theme_override_font_sizes/font_size = 15
|
||||
text = "Enter the Realm"
|
||||
|
||||
[node name="Register" type="VBoxContainer" parent="Center/Panel/Margin/VBox/Tabs"]
|
||||
visible = false
|
||||
layout_mode = 2
|
||||
theme_override_constants/separation = 8
|
||||
metadata/_tab_index = 1
|
||||
|
||||
[node name="RegEmailLabel" type="Label" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
layout_mode = 2
|
||||
text = "Channeler Email"
|
||||
horizontal_alignment = 1
|
||||
|
||||
[node name="RegEmailInput" type="LineEdit" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
unique_name_in_owner = true
|
||||
custom_minimum_size = Vector2(0, 44)
|
||||
layout_mode = 2
|
||||
theme_override_font_sizes/font_size = 15
|
||||
placeholder_text = "your@email.com"
|
||||
virtual_keyboard_type = 5
|
||||
|
||||
[node name="RegPasswordLabel" type="Label" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
layout_mode = 2
|
||||
tooltip_text = "Password"
|
||||
text = "Memory Seal"
|
||||
horizontal_alignment = 1
|
||||
|
||||
[node name="RegPasswordInput" type="LineEdit" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
unique_name_in_owner = true
|
||||
custom_minimum_size = Vector2(0, 44)
|
||||
layout_mode = 2
|
||||
theme_override_font_sizes/font_size = 15
|
||||
placeholder_text = "••••••••"
|
||||
secret = true
|
||||
|
||||
[node name="RegNameLabel" type="Label" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
layout_mode = 2
|
||||
text = "Display Name"
|
||||
|
||||
[node name="RegNameInput" type="LineEdit" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
unique_name_in_owner = true
|
||||
custom_minimum_size = Vector2(0, 44)
|
||||
layout_mode = 2
|
||||
theme_override_font_sizes/font_size = 15
|
||||
placeholder_text = "YourName"
|
||||
|
||||
[node name="RegSpacer" type="Control" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
custom_minimum_size = Vector2(0, 4)
|
||||
layout_mode = 2
|
||||
|
||||
[node name="RegisterBtn" type="Button" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
unique_name_in_owner = true
|
||||
custom_minimum_size = Vector2(0, 48)
|
||||
layout_mode = 2
|
||||
theme_override_font_sizes/font_size = 15
|
||||
text = "Create Account"
|
||||
theme_override_font_sizes/font_size = 16
|
||||
text = "Sign in with Aeternalis"
|
||||
|
||||
[node name="StatusLabel" type="Label" parent="Center/Panel/Margin/VBox"]
|
||||
unique_name_in_owner = true
|
||||
|
||||
@@ -1,50 +1,24 @@
|
||||
extends Control
|
||||
## Login / Register screen.
|
||||
## Login screen — Keycloak Authorization Code + PKCE flow.
|
||||
##
|
||||
## Shown as the entry point before authentication. Uses two tabs:
|
||||
## "Login" — email + password → auth.login
|
||||
## "Register" — email + password + display name → auth.register
|
||||
## Single "Sign in with Aeternalis" button triggers the browser-based OAuth2 flow.
|
||||
## On success: Keycloak.token_received → Auth.login_with_keycloak → auth_success → InitScreen.
|
||||
## On failure: Keycloak.auth_error or Auth.auth_failed → show error, re-enable button.
|
||||
##
|
||||
## Listens to Auth.auth_success and Auth.auth_failed.
|
||||
## On success: transitions to InitScreen (which runs version check + content sync,
|
||||
## then proceeds to MainScreen).
|
||||
## On failure: shows an error message and re-enables the form.
|
||||
##
|
||||
## Remember Me: saves email + password encrypted with AES-256-CBC to
|
||||
## user://creds.dat. Cleared when the user unchecks the box and logs in.
|
||||
## Silent resume: if Auth already has a session token when this scene loads
|
||||
## (e.g. app was restarted with a valid saved token), it skips straight to main.
|
||||
|
||||
# ── Node references (unique names set in the .tscn) ──────────────────────────
|
||||
# ── Node references ───────────────────────────────────────────────────────────
|
||||
|
||||
@onready var email_input : LineEdit = %EmailInput
|
||||
@onready var password_input : LineEdit = %PasswordInput
|
||||
@onready var remember_me : CheckBox = %RememberMe
|
||||
@onready var login_btn : Button = %LoginBtn
|
||||
|
||||
@onready var reg_email_input : LineEdit = %RegEmailInput
|
||||
@onready var reg_password_input : LineEdit = %RegPasswordInput
|
||||
@onready var reg_name_input : LineEdit = %RegNameInput
|
||||
@onready var register_btn : Button = %RegisterBtn
|
||||
|
||||
@onready var status_label : Label = %StatusLabel
|
||||
|
||||
# ── Credential encryption ─────────────────────────────────────────────────────
|
||||
# AES-256-CBC, 32-byte key embedded and XOR-obfuscated across two halves.
|
||||
|
||||
const _CREDS_PATH := "user://creds.dat"
|
||||
|
||||
|
||||
# ── State ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
var _was_manual_login := false
|
||||
var _pending_email := ""
|
||||
var _pending_pass := ""
|
||||
@onready var sign_in_btn : Button = %SignInBtn
|
||||
@onready var status_label : Label = %StatusLabel
|
||||
|
||||
# ── Lifecycle ─────────────────────────────────────────────────────────────────
|
||||
|
||||
func _ready() -> void:
|
||||
ContentCache.apply_scene_background(self)
|
||||
# If already authenticated (e.g. scene reloaded), skip straight to main.
|
||||
# Use call_deferred so the scene tree is not modified while _ready() is running.
|
||||
|
||||
# Already authenticated — skip straight to main (e.g. valid saved token).
|
||||
if not Auth.user_id.is_empty():
|
||||
_go_to_main.call_deferred()
|
||||
return
|
||||
@@ -53,24 +27,12 @@ func _ready() -> void:
|
||||
Auth.auth_failed.connect(_on_auth_failed)
|
||||
Network.connected.connect(_on_network_connected)
|
||||
|
||||
login_btn.pressed.connect(_on_login_pressed)
|
||||
register_btn.pressed.connect(_on_register_pressed)
|
||||
Keycloak.token_received.connect(_on_token_received)
|
||||
Keycloak.auth_error.connect(_on_keycloak_error)
|
||||
|
||||
# Allow pressing Enter to submit the login form.
|
||||
password_input.text_submitted.connect(func(_t): _on_login_pressed())
|
||||
reg_name_input.text_submitted.connect(func(_t): _on_register_pressed())
|
||||
sign_in_btn.pressed.connect(_on_sign_in_pressed)
|
||||
|
||||
# Pre-fill email/password if saved credentials exist.
|
||||
var creds := _load_creds()
|
||||
if creds.size() == 2:
|
||||
email_input.text = creds[0]
|
||||
password_input.text = creds[1]
|
||||
remember_me.button_pressed = true
|
||||
|
||||
# Make the Remember Me label visible against dark backgrounds.
|
||||
remember_me.add_theme_color_override("font_color", Color(0.8, 0.8, 0.8))
|
||||
|
||||
# Show connection / session-resume status on first open.
|
||||
# Show connecting / resume status while the socket is still coming up.
|
||||
if not Auth.session_token.is_empty():
|
||||
_set_status("Resuming session…", false)
|
||||
_set_enabled(false)
|
||||
@@ -85,59 +47,47 @@ func _exit_tree() -> void:
|
||||
Auth.auth_failed.disconnect(_on_auth_failed)
|
||||
if Network.connected.is_connected(_on_network_connected):
|
||||
Network.connected.disconnect(_on_network_connected)
|
||||
if Keycloak.token_received.is_connected(_on_token_received):
|
||||
Keycloak.token_received.disconnect(_on_token_received)
|
||||
if Keycloak.auth_error.is_connected(_on_keycloak_error):
|
||||
Keycloak.auth_error.disconnect(_on_keycloak_error)
|
||||
|
||||
# ── Button handlers ───────────────────────────────────────────────────────────
|
||||
# ── Button handler ────────────────────────────────────────────────────────────
|
||||
|
||||
func _on_login_pressed() -> void:
|
||||
var email := email_input.text.strip_edges()
|
||||
var pass_ := password_input.text
|
||||
if email.is_empty() or pass_.is_empty():
|
||||
_set_status("Please enter your email and password.", true)
|
||||
return
|
||||
_was_manual_login = true
|
||||
_pending_email = email
|
||||
_pending_pass = pass_
|
||||
func _on_sign_in_pressed() -> void:
|
||||
_set_status("Opening browser…", false)
|
||||
_set_enabled(false)
|
||||
Keycloak.start_auth_flow()
|
||||
|
||||
# ── Keycloak signal handlers ──────────────────────────────────────────────────
|
||||
|
||||
func _on_token_received(access_token: String, refresh_token: String) -> void:
|
||||
_set_status("Signing in…", false)
|
||||
_set_enabled(false)
|
||||
Auth.login(email, pass_)
|
||||
Auth.login_with_keycloak(access_token, refresh_token)
|
||||
|
||||
|
||||
func _on_register_pressed() -> void:
|
||||
var email := reg_email_input.text.strip_edges()
|
||||
var pass_ := reg_password_input.text
|
||||
var name_ := reg_name_input.text.strip_edges()
|
||||
if email.is_empty() or pass_.is_empty() or name_.is_empty():
|
||||
_set_status("Please fill in all fields.", true)
|
||||
return
|
||||
_set_status("Creating account…", false)
|
||||
_set_enabled(false)
|
||||
Auth.register(email, pass_, name_)
|
||||
func _on_keycloak_error(message: String) -> void:
|
||||
_set_status(message, true)
|
||||
_set_enabled(true)
|
||||
|
||||
# ── Auth signal handlers ──────────────────────────────────────────────────────
|
||||
|
||||
func _on_auth_success(_user_id: String, _display_name: String) -> void:
|
||||
if _was_manual_login:
|
||||
if remember_me.button_pressed:
|
||||
_save_creds(_pending_email, _pending_pass)
|
||||
else:
|
||||
_clear_creds()
|
||||
_was_manual_login = false
|
||||
_go_to_main()
|
||||
|
||||
|
||||
func _on_network_connected() -> void:
|
||||
# Once the socket is up with no session in flight, clear the spinner.
|
||||
# Socket is up but no session in flight — clear the spinner.
|
||||
if Auth.session_token.is_empty() and status_label.text == "Connecting…":
|
||||
_set_status("", false)
|
||||
|
||||
|
||||
func _on_auth_failed(error_code: String, message: String) -> void:
|
||||
_was_manual_login = false
|
||||
if error_code == "DISCONNECTED":
|
||||
_set_status("Connection lost. Retrying…", false)
|
||||
else:
|
||||
_set_status(_friendly_error(error_code, message), true)
|
||||
_set_enabled(true)
|
||||
_set_enabled(true)
|
||||
|
||||
# ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -154,114 +104,15 @@ func _set_status(text: String, is_error: bool) -> void:
|
||||
|
||||
|
||||
func _set_enabled(enabled: bool) -> void:
|
||||
login_btn.disabled = not enabled
|
||||
register_btn.disabled = not enabled
|
||||
sign_in_btn.disabled = not enabled
|
||||
|
||||
|
||||
func _friendly_error(code: String, message: String) -> String:
|
||||
match code:
|
||||
"INVALID_CREDENTIALS", \
|
||||
"INVALID_PASSWORD", \
|
||||
"USER_NOT_FOUND": return "Wrong email or password."
|
||||
"EMAIL_TAKEN": return "That email is already in use."
|
||||
"DISPLAY_NAME_TAKEN": return "That display name is already in use."
|
||||
# ASP.NET Identity password-policy codes:
|
||||
"WEAK_PASSWORD", \
|
||||
"PasswordTooShort": return "Password must be at least 12 characters."
|
||||
"PasswordRequiresUpper": return "Password must include an uppercase letter."
|
||||
"PasswordRequiresLower": return "Password must include a lowercase letter."
|
||||
"PasswordRequiresNonAlphanumeric": return "Password must include a special character (e.g. !@#$)."
|
||||
"PasswordRequiresDigit": return "Password must include a number."
|
||||
"PasswordRequiresUniqueChars": return "Password must contain more unique characters."
|
||||
"INVALID_EMAIL": return "Please enter a valid email address."
|
||||
"ACCOUNT_LOCKED": return "Account locked. Please try again later."
|
||||
"AUTH_FAILED": return "Session expired. Please sign in again."
|
||||
"AUTH_REQUIRED": return "Please sign in to continue."
|
||||
"AUTH_SERVICE_UNAVAILABLE": return "Server unavailable. Please try again shortly."
|
||||
"AUTH_FAILED": return "Session expired. Please sign in again."
|
||||
"AUTH_REQUIRED": return "Please sign in to continue."
|
||||
"AUTH_SERVICE_UNAVAILABLE": return "Server unavailable. Please try again shortly."
|
||||
"MISSING_ROLE": return "Your account does not have access to this game."
|
||||
_:
|
||||
return message if not message.is_empty() \
|
||||
else "Something went wrong (%s)." % code
|
||||
|
||||
# ── Credential storage (AES-256-CBC) ─────────────────────────────────────────
|
||||
|
||||
func _build_key() -> PackedByteArray:
|
||||
# Key halves XOR'd at runtime so the plaintext key is never a contiguous
|
||||
# literal in the binary.
|
||||
var a := PackedByteArray([
|
||||
0x7A, 0x4D, 0x9F, 0x2C, 0xB8, 0x61, 0xE3, 0x5A,
|
||||
0x0F, 0xC7, 0x94, 0x3B, 0xD6, 0x2E, 0x81, 0xF5,
|
||||
])
|
||||
var b := PackedByteArray([
|
||||
0x4C, 0xA9, 0x73, 0x1E, 0x5B, 0xD8, 0x06, 0x92,
|
||||
0xE7, 0x3F, 0xC4, 0x6A, 0x17, 0x85, 0xB0, 0x2D,
|
||||
])
|
||||
var key := PackedByteArray()
|
||||
key.resize(32)
|
||||
for i in 16:
|
||||
key[i] = a[i] ^ (i * 0x11)
|
||||
key[i + 16] = b[i] ^ (i * 0x11)
|
||||
return key
|
||||
|
||||
|
||||
func _save_creds(email: String, password: String) -> void:
|
||||
var plain := (email + "\n" + password).to_utf8_buffer()
|
||||
# PKCS#7 padding to 16-byte block boundary.
|
||||
var pad := 16 - (plain.size() % 16)
|
||||
for _i in pad:
|
||||
plain.append(pad)
|
||||
|
||||
var iv := Crypto.new().generate_random_bytes(16)
|
||||
var key := _build_key()
|
||||
var aes := AESContext.new()
|
||||
if aes.start(AESContext.MODE_CBC_ENCRYPT, key, iv) != OK:
|
||||
push_warning("LoginScreen: AES encrypt start failed")
|
||||
return
|
||||
var cipher := aes.update(plain)
|
||||
aes.finish()
|
||||
|
||||
var f := FileAccess.open(_CREDS_PATH, FileAccess.WRITE)
|
||||
if f == null:
|
||||
push_warning("LoginScreen: cannot write credentials file")
|
||||
return
|
||||
f.store_buffer(iv)
|
||||
f.store_buffer(cipher)
|
||||
|
||||
|
||||
func _load_creds() -> Array:
|
||||
if not FileAccess.file_exists(_CREDS_PATH):
|
||||
return []
|
||||
var f := FileAccess.open(_CREDS_PATH, FileAccess.READ)
|
||||
if f == null:
|
||||
return []
|
||||
var data := f.get_buffer(f.get_length())
|
||||
if data.size() < 32: # 16 IV + at least one 16-byte block
|
||||
return []
|
||||
|
||||
var iv := data.slice(0, 16)
|
||||
var cipher := data.slice(16)
|
||||
var key := _build_key()
|
||||
var aes := AESContext.new()
|
||||
if aes.start(AESContext.MODE_CBC_DECRYPT, key, iv) != OK:
|
||||
push_warning("LoginScreen: AES decrypt start failed")
|
||||
return []
|
||||
var plain := aes.update(cipher)
|
||||
aes.finish()
|
||||
|
||||
# Strip PKCS#7 padding.
|
||||
if plain.size() == 0:
|
||||
return []
|
||||
var pad_len := plain[plain.size() - 1]
|
||||
if pad_len < 1 or pad_len > 16 or pad_len > plain.size():
|
||||
return []
|
||||
plain = plain.slice(0, plain.size() - pad_len)
|
||||
|
||||
var text := plain.get_string_from_utf8()
|
||||
var parts := text.split("\n", false)
|
||||
if parts.size() != 2:
|
||||
return []
|
||||
return [parts[0], parts[1]]
|
||||
|
||||
|
||||
func _clear_creds() -> void:
|
||||
if FileAccess.file_exists(_CREDS_PATH):
|
||||
DirAccess.remove_absolute(ProjectSettings.globalize_path(_CREDS_PATH))
|
||||
|
||||
Reference in New Issue
Block a user