Repository navigation
feat(server): keep the Komga session token and support multiple addresses with failover - #98
Merged
Merged
Conversation
… every request Komga stamps every authenticated response with `X-Auth-Token`. The app ignored it and sent Basic Auth (or `X-API-Key`) on every request, so each image, list page and SSE frame re-ran credential verification and wrote an authentication-activity row on the server — the reason the iOS client caches the same token in `AppConfig`. `SessionTokenStore` keeps one token per host + account (`baseUrl#username`), because a Komga session token is only valid on the instance that issued it. The identity is deliberately separate from the cache namespace, so a later endpoint switch can move the cache identity without moving the token. The OkHttp interceptor reads the token per request and falls back to the credential when none is stored, so an upgrade with no token behaves exactly like before and heals itself on the first response. A 401 for a request that did carry a token refreshes it once through a dedicated 5 s client (no authenticator, no reachability accounting) and retries the call; a burst of 401s coalesces on one login by re-reading the store under a lock. API-key instances send the key beside the token — Komga skips key re-authentication while the session is valid and falls back to the key afterwards — and are never retried on 401, matching iOS. Tokens are only accepted from the active session (`setActive`), so a late response from a session the user just left cannot resurrect a token; logout drops the token with the credential and editing credentials clears the old one. Temporary clients (login, edit-server validation) pass no store: they neither inherit another session's token nor record the token they receive — the caller persists the token once the credentials are accepted. `KomgaAuthHeadersTest` pins header composition, host/account scoping and the late-response URL guard.
…s and failover A Komga server is often reachable through several routes - the public URL, the LAN address, a Tailscale host - and which route works depends on where the reader is. This mirrors the iOS app (PR #1355): each saved instance now keeps an ordered address list, probes them, and can move the live session to another address without logging out. iOS parity is the design contract here, so the behaviour and the failure distinctions follow the Apple implementation rather than reinvent a local model. The blocker was cache identity. `ServerConfig.cacheNamespace` used to be "baseUrl#username", which tied an instance's caches, pins and per-instance preferences to one address: switching to the LAN route looked like another server and started every cache cold. `ServerConfig` and `ServerInstance` now carry a separate `cacheKeyUrl` that names the instance; blank falls back to the base URL, which is the key existing installs already use, so there is no migration and the legacy rows are upgraded on read. The session token identity deliberately does NOT follow the cache anchor: an X-Auth-Token is only valid on the host that issued it, so it stays "$baseUrl#$username". The SSE resume cursor is keyed on the same host+account pair - a Last-Event-ID from the public address must never be replayed against the LAN one. Probing is a stateless one-shot GET /api/v2/users/me with a dedicated 4s client, not an ApiClients: a backup address being down says nothing about the active one and must not feed the offline verdict. A 2xx only counts when the body decodes to a user with an id, otherwise a reverse proxy or SSO page would make a non-Komga host look healthy. `ServerEndpointHealthStore` shares those verdicts between the edit screen and the server list, throttles re-probes for 10s, de-duplicates in-flight ones, and cancels a probe whose address was edited. `ServerEndpointSwitchService` serialises switches, refuses to touch an instance that is not the one the session is signed in to, probes the target before a manual switch (a failover already proved it reachable) and writes the new base URL while preserving the cache anchor and the instance's address list. Failover probes the remaining addresses concurrently and takes the first reachable one in priority order; a repeat call right after a failed attempt reuses that verdict for 5s. `ServerFailoverCoordinator` listens for the offline verdict, and retry/foreground try the other addresses before re-dialing the dead one, because returning to the foreground is the natural moment for a changed network. `ApiClients` ignores responses from an address it no longer talks to, so an in-flight reply from the old host cannot drive the offline flag, trigger a failover or overwrite the session token (iOS `targetsCurrentServer`). The edit screen now edits the address list: label, URL, which one is active, reorder and remove, with duplicate addresses blocked exactly like iOS. Adding, relabelling or reordering a backup address saves directly - an unreachable backup is precisely what the user may be preparing for - while a new active address or changed credentials still has to pass Validate Connection. Validating also captures the address's own session token, and saving clears only the token of an identity that no longer exists (address or account changed), never the one just obtained for the new address. The server list shows every address of an instance with a latency/failure badge and lets the active card move between them with one tap, reporting the swap or the reason it was refused. Verified with :app:compileDebugKotlin, :app:testDebugUnitTest (endpoint bookkeeping contract plus the existing suite) and the :app:lintDebug gate.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Two iOS-parity changes to how the Android app talks to Komga servers, stacked because the second depends on the first:
X-Auth-Token) — stop re-authenticating every request. Komga was logging a fresh authentication activity for every page/thumbnail request, and the Android app looked like a login storm in the server's activity log. The app now keeps the token Komga returns onGET /api/v2/users/me(and stamps on every response), sends it alone on subsequent requests, re-logs in once on a 401 and rebuilds the client from a host-scoped identity.1. Session token (commit e739099)
SessionTokenStorepersists tokens in their own DataStore (session_tokens), keyedbaseUrl#username, so the token survives client rebuilds without recreatingApiClients(which would tear down SSE and the image loaders).KomgaSessionAuthenticatorrefreshes only when the request actually carried a token, takes one lock so concurrent 401s collapse into one login, and never retries API-key requests.RootViewModel.logoutclears the token before dropping the session.This is also what keeps the authentication log clean — the previous behaviour repeated Basic Auth on every request.
2. Multiple addresses (commit ea096ca)
Cache identity had to be decoupled first.
cacheNamespacewasbaseUrl#username, so switching to another address of the same server looked like a different server and every cache, pin and per-instance preference went cold.ServerConfig/ServerInstancenow carrycacheKeyUrl(blank falls back tobaseUrl, i.e. exactly what old installs already use — no migration). The session identity staysbaseUrl#usernamebecause a token is only valid where it was issued, and the SSE resume cursor is keyed the same way so aLast-Event-IDfrom the public host is never replayed against the LAN host.GET /api/v2/users/meon a dedicated 4 s client (no authenticator, no reachability feed). Only a 2xx whose body decodes to a user with an id counts as reachable — a reverse proxy or SSO page returning 200 must not pass.retryConnection, and returning to the foreground (the natural moment for a changed network).ApiClientsignores responses from a host it no longer targets — an in-flight reply from the old address cannot drive the offline flag, trigger a failover or overwrite the token (iOStargetsCurrentServer).Verification
:app:compileDebugKotlin:app:testDebugUnitTest— existing suite plus endpoint bookkeeping contract tests (cache namespace stability across address switches, legacy-row fallback, dedupe/normalisation, login-through-new-address):app:lintDebuggate passes (only the 4 pre-existing warnings):app:assembleDebugbuilds a working APK (109 MB debug, arm64-v8a + armeabi-v7a)Notes