Skip to content

feat(server): keep the Komga session token and support multiple addresses with failover - #98

Merged
dyphire merged 2 commits into
mainfrom
feat/auth-session-token
Nov 28, 2026
Merged

dyphire merged 2 commits into
mainfrom
feat/auth-session-token

Conversation

@dyphire

@dyphire dyphire commented Nov 28, 2026

Copy link
Copy Markdown
Member

Summary

Two iOS-parity changes to how the Android app talks to Komga servers, stacked because the second depends on the first:

  1. Session token (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 on GET /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.
  2. Multiple addresses per server — mirrors iOS PR feat(server): support multiple endpoints with health checks and failover kmreader#1355: an ordered endpoint list per instance, health/latency probes, in-place switching and automatic failover, without logging out or losing local state.

1. Session token (commit e739099)

  • SessionTokenStore persists tokens in their own DataStore (session_tokens), keyed baseUrl#username, so the token survives client rebuilds without recreating ApiClients (which would tear down SSE and the image loaders).
  • KomgaSessionAuthenticator refreshes only when the request actually carried a token, takes one lock so concurrent 401s collapse into one login, and never retries API-key requests.
  • Tokens are host-scoped: a token issued by the public URL must never be sent to the LAN address. RootViewModel.logout clears 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. cacheNamespace was baseUrl#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/ServerInstance now carry cacheKeyUrl (blank falls back to baseUrl, i.e. exactly what old installs already use — no migration). The session identity stays baseUrl#username because a token is only valid where it was issued, and the SSE resume cursor is keyed the same way so a Last-Event-ID from the public host is never replayed against the LAN host.

  • Probe: one-shot GET /api/v2/users/me on 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.
  • Health store: shared across edit screen and server list, 10 s refresh throttle, in-flight de-duplication, cancels a probe for an address that was edited/removed.
  • Switch service: serialised, checks the instance is the signed-in one, probes the target for manual switches, saves the new base URL while preserving the cache anchor and the instance row.
  • Failover: concurrent probes of the remaining addresses, first reachable in priority order wins, 5 s verdict reuse, guarded against concurrent attempts. Triggered by the offline verdict, retryConnection, and returning to the foreground (the natural moment for a changed network).
  • Guard: ApiClients ignores 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 (iOS targetsCurrentServer).
  • UI: the edit screen edits the address list (label, URL, active selection, reorder, remove, duplicate addresses blocked) — backup-only edits save directly because an unreachable backup is exactly what a user may be preparing for, while a new active address or changed credentials still requires Validate Connection. The server list shows every address of an instance with a latency/failure badge and one-tap switching on the active card. Strings in en / zh-rCN / zh-rTW.

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:lintDebug gate passes (only the 4 pre-existing warnings)
  • :app:assembleDebug builds a working APK (109 MB debug, arm64-v8a + armeabi-v7a)

Notes

  • No GRDB-style schema migration is needed: rows written before this change are normalised on read.
  • Manual testing focus: switch between public/LAN address from the server list, then disable the active route and confirm failover moves the session while the open reader survives; check the Komga activity log no longer fills up with per-request logins.

… 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.
@dyphire
dyphire merged commit 9578e03 into main Nov 28, 2026
1 check passed
@dyphire
dyphire deleted the feat/auth-session-token branch November 28, 2026 16:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant