* feat(#349): smart auth login flow — probe dashboard, show correct fields Landing screen with two buttons (Auth Login / Pairing Login) replaces ConnectScreen as the start screen. Auth login probes the dashboard to detect what auth it needs (token-only, basic-auth, or both) and shows only the relevant input fields. Changes: - NavigationKeys.kt: add LandingScreen, AuthLoginScreen NavKeys - LandingScreen.kt: new screen with hero icon + two login buttons - AuthLoginScreen.kt: IP/Port input, probe logic, dynamic field rendering - AuthLoginViewModel.kt: probe API, dashboard auth detection, connect flow - Navigation.kt: wire new screens, start on LandingScreen, hide bottom bar - strings.xml: add string resources for both screens * fix(#351): align AuthLoginScreen field names with ViewModel API, fix TAG refs - state.isProbing → state.probing - DashboardAuthMode.BOTH → DashboardAuthMode.ALL - viewModel.probe() → viewModel.probeDashboard() - state.isConnecting → state.isLoading - Removed unused TAG constant, replaced with inline tag string - Made connectTokenOnly suspend to fix safeApiCall compilation This fixes the CI compilation errors. * fix(#351): revert probeDashboard() call to probe() to match VM * fix(#351): rename isProbing to probing in ViewModel * fix(#351): follow redirects in basic auth login — / redirects to /login * fix(#351): show all fields when basic auth detected — still needs session token for WS * refactor(#349): remove old ConnectScreen, clean up NavKey + navigation * fix(#351): validate token against /api/sessions (auth-protected) instead of /api/status (public) /api/status is a public endpoint that returns 200 even with wrong tokens, causing invalid tokens to be saved and the WebSocket to spin forever on the chat screen. /api/sessions requires auth and returns 401 on bad tokens. * fix(#351): rewrite basic auth login — POST to /auth/password-login, then fetch SPA with cookie to extract token * fix(#351): use ticket-based WS auth when basic auth is active The updated dashboard on 0.0.0.0 always has auth_required=True, which rejects legacy ?token= in favor of ?ticket= (single-use, 30s TTL). Added AuthManager.setWsAuthParam() to support both ?token= (loopback) and ?ticket= (gated mode) in wsUrl(). connectBasicAuth now mints a ticket via POST /api/auth/ws-ticket after login instead of extracting the token from the SPA. * fix(#351): use requirePrefs() instead of direct prefs reference in wsUrl() * fix(#351): handle relaxed-mock empty string in wsUrl() authParam fallback * feat(#349): auto-extract session token from SPA HTML during probe The probe now extracts the __HERMES_SESSION_TOKEN__ value from the dashboard SPA and auto-populates the token field in TOKEN_ONLY mode, eliminating the need for manual token pasting. - Introduced ProbeResult data class to carry authMode + extractedToken - Regex extraction of __HERMES_SESSION_TOKEN__ from dashboard HTML - Token field auto-filled on probe completion for TOKEN_ONLY mode * fix(#349): return BASIC_AUTH from probe when basic auth detected Bug: probe returned ALL instead of BASIC_AUTH for basic-auth-only dashboards, causing token+credential fields to show and the connect flow to fall through to connectTokenOnly() on basic auth failure, producing a confusing 'Unauthorized (HTTP 401)' NetworkResult error. Fix: probe now returns DashboardAuthMode.BASIC_AUTH when a redirect to /login is detected. BASIC_AUTH in connect() calls connectBasicAuth() directly with no fallback. ALL mode also no longer falls through to connectTokenOnly(). * fix(#349): use session cookie for REST API in gated mode The dashboard's gated mode authenticates REST API requests via session cookies (hermes_session_at), not Bearer tokens. The app was storing the WS ticket as the token and sending it as Authorization: Bearer <ticket> for all REST calls, which the server rejected with 401. - Extract hermes_session_at cookie from Set-Cookie header after POST /auth/password-login and store it in AuthManager - ApiClient authInterceptor now sends Cookie header when session cookie is present, falls back to Bearer token for loopback mode - ConnectResult carries both WS credential (ticket) and session cookie separately - WS ticket used only for WebSocket (?ticket=), session cookie used for REST API * feat(#349): add logout button to Settings > About Red error-style button that clears all auth credentials (token, session cookie, WS auth param) and navigates back to LandingScreen. Wired through SettingsScreen onLogout callback to Navigation.kt. * fix(#349): improve logout navigation flow * fix(#349): keep backstack stable across logout Use remember without keys for NavBackStack so the same backstack object persists across startScreen changes. Use LaunchedEffect keyed on startScreen to reset stack content atomically. This avoids NavDisplay losing snapshot observation when a new NavBackStack object is created. * fix(#349): mint fresh WS ticket on every connect The WS ticket is a single-use 30-second credential. On app restart (or reconnect), the stored ticket is expired. Now refreshWsTicketIfNeeded() mints a new ticket using the session cookie before every WS connection attempt. Loopback mode (no session cookie) is unaffected. * fix(#349): refresh ticket in openSocket for reconnect paths scheduleReconnect() bypasses connect() and calls openSocket() directly. Moving the ticket refresh into openSocket() ensures every WS connection attempt — first launch and reconnect — uses a fresh ticket. * fix(#349): stub getSessionCookie() in ApiClientTest mockkObject(AuthManager) is strict, so unstubbed getSessionCookie() calls throw MockKException which manifests as IOException. --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com>
This commit is contained in:
1 parent
11ca9b55c8
commit
c1af989220
13 files changed
+1026
-362
No files matched your search
@@ -30,6 +30,8 @@ object AuthManager {
|
||||
private const val KEY_TYPING_EFFECT_DELAY_MS = "typing_effect_delay_ms"
|
||||
private const val KEY_CONNECTION_PROFILES = "connection_profiles"
|
||||
private const val KEY_SELECTED_PROFILE_ID = "selected_profile_id"
|
||||
private const val KEY_WS_AUTH_PARAM = "ws_auth_param"
|
||||
private const val KEY_SESSION_COOKIE = "session_cookie"
|
||||
private const val KEY_USE_DYNAMIC_COLORS = "use_dynamic_colors"
|
||||
private const val KEY_THEME_PRESET = "theme_preset"
|
||||
private const val KEY_BOTTOM_NAV_DISPLAY_MODE = "bottom_nav_display_mode"
|
||||
@@ -93,9 +95,25 @@ object AuthManager {
|
||||
}
|
||||
|
||||
private fun requirePrefs(): SharedPreferences =
|
||||
prefs ?: throw IllegalStateException(
|
||||
"AuthManager not initialised – call AuthManager.init(context) first",
|
||||
)
|
||||
prefs ?: throw IllegalStateException("AuthManager not initialized. Call init(context) first.")
|
||||
|
||||
fun setWsAuthParam(param: String) {
|
||||
requirePrefs().edit().putString(KEY_WS_AUTH_PARAM, param).apply()
|
||||
}
|
||||
|
||||
// ── Session Cookie (for gated/dashboard REST API) ────────────────────
|
||||
|
||||
/**
|
||||
* In gated mode (basic auth), the dashboard authenticates REST API
|
||||
* requests via the `hermes_session_at` cookie, not via
|
||||
* `Authorization: *** We store it here so [ApiClient]'s
|
||||
* authInterceptor can add it as a `Cookie` header.
|
||||
*/
|
||||
fun getSessionCookie(): String? = requirePrefs().getString(KEY_SESSION_COOKIE, null)
|
||||
|
||||
fun setSessionCookie(cookie: String?) {
|
||||
requirePrefs().edit().putString(KEY_SESSION_COOKIE, cookie).apply()
|
||||
}
|
||||
|
||||
// ── Connection Profiles ──────────────────────────────────────────────
|
||||
|
||||
@@ -290,7 +308,12 @@ object AuthManager {
|
||||
|
||||
/** Convenience: build the WebSocket URL with token query param.
|
||||
* NOTE: Token in query string — trusted local network only. */
|
||||
fun wsUrl(): String = "ws://${getHost()}:${getPort()}/api/ws?token=${getToken().orEmpty()}"
|
||||
fun wsUrl(): String {
|
||||
val raw = requirePrefs().getString(KEY_WS_AUTH_PARAM, "token")
|
||||
val authParam = if (raw.isNullOrBlank()) "token" else raw
|
||||
val credential = getToken().orEmpty()
|
||||
return "ws://${getHost()}:${getPort()}/api/ws?$authParam=$credential"
|
||||
}
|
||||
|
||||
// ── Bottom nav bar items ──────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -100,18 +100,30 @@ object ApiClient {
|
||||
|
||||
val authInterceptor =
|
||||
Interceptor { chain ->
|
||||
val token = AuthManager.getToken()
|
||||
val request =
|
||||
if (!token.isNullOrBlank()) {
|
||||
chain
|
||||
.request()
|
||||
val request = chain.request()
|
||||
val sessionCookie = AuthManager.getSessionCookie()
|
||||
if (!sessionCookie.isNullOrBlank()) {
|
||||
// Gated mode: authenticate via session cookie
|
||||
chain.proceed(
|
||||
request
|
||||
.newBuilder()
|
||||
.addHeader("Authorization", "Bearer $token")
|
||||
.build()
|
||||
.addHeader("Cookie", "hermes_session_at=$sessionCookie")
|
||||
.build(),
|
||||
)
|
||||
} else {
|
||||
// Loopback mode: authenticate via Bearer token
|
||||
val token = AuthManager.getToken()
|
||||
if (!token.isNullOrBlank()) {
|
||||
chain.proceed(
|
||||
request
|
||||
.newBuilder()
|
||||
.addHeader("Authorization", "Bearer $token")
|
||||
.build(),
|
||||
)
|
||||
} else {
|
||||
chain.request()
|
||||
chain.proceed(request)
|
||||
}
|
||||
chain.proceed(request)
|
||||
}
|
||||
}
|
||||
|
||||
// SEC-11: No certificate pinning is configured by default since the app
|
||||
|
||||
@@ -25,6 +25,7 @@ import kotlinx.coroutines.launch
|
||||
import okhttp3.CertificatePinner
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
@@ -139,9 +140,51 @@ object HermesWsClient {
|
||||
intentionalClose.set(false)
|
||||
currentBackoff = INITIAL_BACKOFF_MS
|
||||
_connectionStatus.value = ConnectionStatus.CONNECTING
|
||||
refreshWsTicketIfNeeded()
|
||||
openSocket()
|
||||
}
|
||||
|
||||
/**
|
||||
* If a session cookie is present (gated mode), mint a fresh WS ticket
|
||||
* from the dashboard. The ticket is single-use and has a 30-second TTL,
|
||||
* so we must mint a new one on every connect (first launch and reconnect).
|
||||
*/
|
||||
private fun refreshWsTicketIfNeeded() {
|
||||
val sessionCookie = AuthManager.getSessionCookie()
|
||||
if (sessionCookie.isNullOrBlank()) {
|
||||
// Loopback mode — the stored token IS a session token, not a
|
||||
// WS ticket, so no refresh needed.
|
||||
return
|
||||
}
|
||||
try {
|
||||
val client =
|
||||
OkHttpClient.Builder()
|
||||
.connectTimeout(5, TimeUnit.SECONDS)
|
||||
.readTimeout(5, TimeUnit.SECONDS)
|
||||
.build()
|
||||
val request =
|
||||
Request.Builder()
|
||||
.url("http://${AuthManager.getHost()}:${AuthManager.getPort()}/api/auth/ws-ticket")
|
||||
.header("Cookie", "hermes_session_at=$sessionCookie")
|
||||
.post(RequestBody.create(null, "{}"))
|
||||
.build()
|
||||
val response = client.newCall(request).execute()
|
||||
if (response.isSuccessful) {
|
||||
val body = response.body?.string() ?: ""
|
||||
val ticketMatch = Regex(""""ticket":"([^"]+)"""").find(body)
|
||||
val ticket = ticketMatch?.groupValues?.getOrNull(1)
|
||||
if (!ticket.isNullOrBlank()) {
|
||||
AuthManager.setToken(ticket)
|
||||
if (BuildConfig.DEBUG) Log.d(TAG, "WS ticket refreshed")
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "WS ticket refresh failed: HTTP ${response.code}")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "WS ticket refresh failed: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/** Cleanly close the WebSocket and stop auto-reconnect. */
|
||||
fun disconnect() {
|
||||
intentionalClose.set(true)
|
||||
@@ -197,6 +240,7 @@ object HermesWsClient {
|
||||
// ── Internal ─────────────────────────────────────────────────────────
|
||||
|
||||
private fun openSocket() {
|
||||
refreshWsTicketIfNeeded()
|
||||
val url = AuthManager.wsUrl()
|
||||
// B2 (Jun 18 2026, kanban t_8884db16): url contains the auth token
|
||||
// as a query param — never stream to logcat in release builds.
|
||||
|
||||
Reference in new issue
Block a user