Connect as the other LLeMbas clients do: address, identity, refused token, streams, words

- One address rule (api/Address.kt): scheme in any case, host lower-cased, path, query and
  fragment dropped; an http:// address is answered at the address step (this app needs https).
- User-Agent llembas-android/<version> on every request, and the same string as the device
  code's client_id (the server only stores and shows it).
- A 401 of the instance's own (WWW-Authenticate: Bearer realm="lembas") marks the instance
  whose token it was as signed out: nothing more is asked with it, its pages stay underneath a
  page that offers the sign-in in one step, and nothing else is forgotten. A 403 stays the
  server's sentence; a 401 passed on from a provider behind /v1 signs nobody out.
- Streams: 45 s of silence is a broken connection (the server's keepalive is every 15 s on all
  three routes); reconnect 1 s doubling to 60 s, jittered ±20 %, short again only after 30 s of
  health; a 429 waits for Retry-After.
- A sentence for each failure: unreachable, timeout, certificate not trusted, not LLeMbas,
  "the server answered N", too old, too new. Sign-in polls end by their real reason and survive
  a dropped network or a restarting server.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-12-01 19:22:40 +00:00
1 parent cf092ef1a1
commit 71b2e847cf
25 files changed
+1256 -96

No files matched your search

@@ -13,6 +13,7 @@ import android.os.Bundle
import androidx.core.content.ContextCompat
import eu.llembas.android.api.EventsHub
import eu.llembas.android.api.Frame
import eu.llembas.android.api.RefusedTokens
import eu.llembas.android.api.StreamClient
import eu.llembas.android.auth.InstanceStore
import eu.llembas.android.wake.AppVisibility
@@ -20,14 +21,17 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
/** The process: one store of instances, and the notification channels, made once. */
class LembasApp : Application() {
lateinit var instances: InstanceStore
private set
private val background = CoroutineScope(SupervisorJob() + Dispatchers.Default)
/** The one connection to the person's events route, shared by all that watch it. */
val events = EventsHub(CoroutineScope(SupervisorJob() + Dispatchers.Default))
val events = EventsHub(background)
/**
* The events route of the instance in use, as its frames; null when not signed in. Whoever
@@ -35,10 +39,13 @@ class LembasApp : Application() {
* a scope that outlives the screen: the connection is open for as long as anybody listens.
*/
suspend fun eventFrames(): Flow<Frame>? {
val instance = instances.current() ?: return null
// An instance that signed this phone out is asked nothing more: its route is not opened.
val instance = instances.current()?.takeUnless { it.signedOut } ?: return null
val api = instances.clientFor(instance)
// Every opening of the route waits at the gate: it is not opened, or opened again, behind a lock.
return events.frames(instance.id) { StreamClient(api).watch(turn = { gate.pass() }) { api.events() } }
// The line is the token's, not only the instance's: after a sign-in again the route is
// opened with the new token, never taken up with the one the instance refused.
return events.frames(eventsKey(instance.id, instance.sealedToken)) { StreamClient(api).watch(turn = { gate.pass() }) { api.events() } }
}
/** Whether a new request with the account's files may start: the app in front, the phone unlocked. */
@@ -47,6 +54,10 @@ class LembasApp : Application() {
override fun onCreate() {
super.onCreate()
instances = InstanceStore(this)
// A token the instance refuses (a 401 of its own, on any request: a call, a stream, a
// download) signs out the instance that token belongs to -- that one only, and nothing
// else is forgotten. Its screens then offer the sign-in (MainActivity).
RefusedTokens.heard = { token -> background.launch { runCatching { instances.refused(token) } } }
// Copies of the account's files left by a process that was killed. A viewer's own are
// nobody's now; one another app was handed may still be read there (a mail being
// written), so those go by their age only.
@@ -126,3 +137,6 @@ class LembasApp : Application() {
}
val android.content.Context.lembas: LembasApp get() = applicationContext as LembasApp
/** What names one connection to an instance's events route: the instance and the token it is followed with. */
fun eventsKey(instanceId: String, sealedToken: String): String = instanceId + "#" + sealedToken.hashCode()
@@ -18,6 +18,7 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
@@ -25,6 +26,8 @@ import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
@@ -62,6 +65,7 @@ import eu.llembas.android.ui.scheduled.SchedulingModelsScreen
import eu.llembas.android.ui.settings.McpScreen
import eu.llembas.android.ui.settings.SettingsScreen
import eu.llembas.android.ui.signin.SignInScreen
import eu.llembas.android.ui.signin.SignedOutScreen
import eu.llembas.android.ui.theme.LembasTheme
import eu.llembas.android.update.ReleaseCheck
import eu.llembas.android.wake.WakeBootReceiver
@@ -176,7 +180,45 @@ class MainActivity : ComponentActivity() {
when {
loaded == null -> Box(Modifier.fillMaxSize())
instance == null -> SignInScreen()
else -> key(instance.id) { Home(instance, open, opened) }
else -> key(instance.id) { Signed(instance, open, opened) }
}
}
/**
* The instance in use: its pages, and over them the way back in when the instance signed
* this phone out (it refused the token). The pages stay underneath as they were -- a message
* half written is there again after the sign-in -- and ask the instance nothing meanwhile
* (no client is handed out for a signed-out instance). An instance that was signed out
* before its pages were ever up has none to keep: they are made after the sign-in.
*/
@Composable
private fun Signed(instance: Instance, open: Opening?, opened: () -> Unit) {
val scope = rememberCoroutineScope()
var up by rememberSaveable { mutableStateOf(false) }
if (!instance.signedOut && !up) SideEffect { up = true }
Box(Modifier.fillMaxSize()) {
if (up || !instance.signedOut) Home(instance, open, opened)
if (instance.signedOut) {
val all by lembas.instances.instances.collectAsState(initial = emptyList())
SignedOutScreen(
instance = instance,
others = all.filter { it.id != instance.id },
onUse = { other ->
scope.launch {
lembas.instances.use(other.id)
FileCache.clear(this@MainActivity)
}
},
onRemove = {
scope.launch {
Push.disable(this@MainActivity, instance)
lembas.instances.remove(instance.id)
// The copies of the account's files this phone held go with it.
FileCache.clear(this@MainActivity)
}
},
)
}
}
}
@@ -0,0 +1,51 @@
package eu.llembas.android.api
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
/**
* What a typed address is, by the one rule every LLeMbas client reads an address with: trimmed;
* `https://` when no scheme was typed (a scheme is read whatever its case); http and https only;
* the scheme, the host in lower case and a port that is not the scheme's own are kept; a path, a
* query, a fragment and a trailing slash are dropped.
*
* This app talks https only (Android's network policy of the app forbids cleartext), so an
* `http://` address is its own answer: said in words where the address is typed, not as a
* library's error three steps later.
*/
sealed interface Address {
/** An instance's base URL: `https://host` or `https://host:port`, nothing after it. */
data class Base(val url: String) : Address
/** Nothing was typed. */
data object Empty : Address
/** `http://…`: an address the rule accepts and this app cannot use. */
data object NeedsHttps : Address
/** Another scheme (`ftp://…`): no LLeMbas client reads it. */
data object NotHttp : Address
/** Not an address at all (no host, a port that is no number). */
data object Unreadable : Address
}
private val SCHEME = Regex("^([A-Za-z][A-Za-z0-9+.-]*)://")
/** [typed] as an [Address]. Pure: nothing is looked up, nothing is asked. */
fun address(typed: String): Address {
val text = typed.trim()
if (text.isEmpty()) return Address.Empty
val scheme = SCHEME.find(text)?.groupValues?.get(1)?.lowercase()
val rest = if (scheme == null) text else text.substring(text.indexOf("://") + 3)
return when (scheme) {
null, "https" -> {
val url = "https://$rest".toHttpUrlOrNull() ?: return Address.Unreadable
val base = url.newBuilder().username("").password("").encodedPath("/").query(null).fragment(null).build()
Address.Base(base.toString().trimEnd('/'))
}
"http" -> Address.NeedsHttps
else -> Address.NotHttp
}
}
@@ -33,8 +33,14 @@ import kotlin.coroutines.resumeWithException
/** Where a new agent chat runs: a linked device ([LinkedDevice.id]) and a folder on it. */
data class AgentTarget(val device: String, val directory: String = "")
/** A refusal from the server, in its own words (`{"detail": "…"}`). */
class ApiException(val status: Int, message: String) : IOException(message)
/**
* A refusal from the server, in its own words (`{"detail": "…"}`). [retryAfter] is the seconds a
* 429 asked the caller to wait (`Retry-After`), where it said so.
*/
class ApiException(val status: Int, message: String, val retryAfter: Long? = null) : IOException(message)
/** An address that answered, and is no LLeMbas instance: no discovery document, or another service's. */
class NotLembas : IOException("Not a LLeMbas instance.")
private val JSON = "application/json; charset=utf-8".toMediaType()
@@ -44,6 +50,8 @@ val SharedHttp: OkHttpClient by lazy {
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
// Every request says which app asks, and a token the instance refuses is heard once, here.
.addInterceptor(Identity())
.build()
}
@@ -60,27 +68,26 @@ suspend fun Call.await(): Response = suspendCancellableCoroutine { cont ->
cont.invokeOnCancellation { runCatching { cancel() } }
}
/** The address a person typed, as the instance's base URL: https assumed, no trailing slash. */
fun normaliseBase(typed: String): String {
var text = typed.trim().trimEnd('/')
if (!text.startsWith("http://") && !text.startsWith("https://")) text = "https://$text"
return text.toHttpUrl().toString().trimEnd('/')
}
/** The calls that need no token: finding the instance and signing in. */
class Doorstep(private val http: OkHttpClient = SharedHttp) {
suspend fun discover(base: String): Discovery {
val response = http.newCall(Request.Builder().url("$base/.well-known/lembas.json").build()).await()
return response.use {
if (!it.isSuccessful) throw ApiException(it.code, "Not a LLeMbas instance (${it.code}).")
LembasJson.decodeFromString(Discovery.serializer(), it.body!!.string())
// No such document: something else lives at the address. Any other refusal -- a proxy
// whose server is down (502), a server that is starting -- is the server's answer,
// said with its number: it may well be a LLeMbas instance.
if (it.code == 404) throw NotLembas()
if (!it.isSuccessful) throw ApiException(it.code, "")
val text = it.body?.string().orEmpty()
// A page, or another program's JSON, is not the document either.
runCatching { LembasJson.decodeFromString(Discovery.serializer(), text) }.getOrNull() ?: throw NotLembas()
}
}
suspend fun deviceCode(url: String, deviceName: String, model: String): DeviceCode {
val body = buildJsonObject {
put("scope", "app models")
put("client_id", "lembas-android")
put("client_id", USER_AGENT)
put("device_name", deviceName)
put("device_host", model)
put("device_platform", "android")
@@ -92,14 +99,23 @@ class Doorstep(private val http: OkHttpClient = SharedHttp) {
}
}
/** One poll. A pending login is a 400 with `authorization_pending` -- not a failure. */
/**
* One poll. A pending login is a 400 with `authorization_pending` -- not a failure. An answer
* that is no such document (a proxy's 502 page, a 429) is the server's refusal with its
* number, never "the code expired".
*/
suspend fun deviceToken(url: String, deviceCode: String): DeviceToken {
val body = buildJsonObject {
put("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
put("device_code", deviceCode)
}
val response = http.newCall(post(url, body)).await()
return response.use { LembasJson.decodeFromString(DeviceToken.serializer(), it.body!!.string()) }
return response.use {
val text = it.body?.string().orEmpty()
val said = runCatching { LembasJson.decodeFromString(DeviceToken.serializer(), text) }.getOrNull()
if (said != null && (said.accessToken != null || said.error != null)) return@use said
throw ApiException(it.code, refusal(text).orEmpty(), retryAfterSeconds(it.header("Retry-After")))
}
}
private fun post(url: String, body: JsonObject) = Request.Builder().url(url).post(body.toString().toRequestBody(JSON)).build()
@@ -116,13 +132,14 @@ internal fun detail(response: Response): String {
}
/**
* The server's own sentence in a refusal's body: `detail` on `/api/v2`, and OpenAI's shape
* (`error.message`) on `/v1`, where speech lives. Null when the body says neither.
* The server's own sentence in a refusal's body: `detail` on `/api/v2`, OpenAI's shape
* (`error.message`) on `/v1`, where speech lives, and the sign-in's (`error_description`, RFC
* 8628). Null when the body says none of them.
*/
internal fun refusal(body: String): String? = runCatching {
val said = LembasJson.parseToJsonElement(body) as JsonObject
fun words(of: Any?): String? = (of as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content?.ifBlank { null }
words(said["detail"]) ?: words((said["error"] as? JsonObject)?.get("message"))
words(said["detail"]) ?: words((said["error"] as? JsonObject)?.get("message")) ?: words(said["error_description"])
}.getOrNull()
/**
@@ -0,0 +1,91 @@
package eu.llembas.android.api
import eu.llembas.android.BuildConfig
import okhttp3.Interceptor
import okhttp3.Response
/** This app's name to a server, with [version]: `llembas-android/1.2.3`. */
fun userAgent(version: String): String = "llembas-android/$version"
/**
* Who is asking: the `User-Agent` of every request this app makes (calls, streams, uploads and
* downloads) and the device code's `client_id` -- one string, so a server's list of devices and
* its logs name the same program.
*/
val USER_AGENT: String = userAgent(BuildConfig.VERSION_NAME)
/**
* The token a response says the instance no longer accepts, or null. Only the instance's own
* refusal counts: a 401 with its `WWW-Authenticate: Bearer realm="lembas"`, to a request that
* carried a token. A 401 passed on from somewhere else -- a speech provider behind `/v1`
* refusing the instance's key -- has no such header and signs nobody out; nor does a 403, which
* is the server's sentence about one thing that is not allowed.
*/
fun refusedToken(status: Int, challenge: String?, authorization: String?): String? {
if (status != 401 || challenge == null || authorization == null) return null
val asked = challenge.trim()
if (!asked.startsWith("Bearer", ignoreCase = true) || !asked.contains("realm=\"lembas\"", ignoreCase = true)) return null
if (!authorization.startsWith("Bearer ")) return null
return authorization.removePrefix("Bearer ").trim().ifEmpty { null }
}
/**
* Where a refused token is said: once for the process, heard by whoever keeps the instances
* (`LembasApp`). It is told the token, not "the instance in use" -- a request of another
* instance, or one that was under way while the person switched, signs out the instance whose
* token it carried and no other. Called on the thread the answer arrived on: the listener only
* hands it on.
*/
object RefusedTokens {
@Volatile
var heard: ((String) -> Unit)? = null
}
/** Names the app on every request, and listens for the instance refusing a token. */
internal class Identity : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request().newBuilder().header("User-Agent", USER_AGENT).build()
val response = chain.proceed(request)
refusedToken(response.code, response.header("WWW-Authenticate"), request.header("Authorization"))?.let { token ->
RefusedTokens.heard?.invoke(token)
}
return response
}
}
/** A `Retry-After` in seconds (the server sends a number), or null: absent, a date, or nonsense. */
fun retryAfterSeconds(header: String?): Long? = header?.trim()?.toLongOrNull()?.takeIf { it >= 0 }
/**
* The one reconnect schedule of every LLeMbas client: a pause of 1 second that doubles to 60,
* each within ±20 % so that the clients of a server that restarted do not all return at the same
* moment, and back to 1 second only after a connection that stayed healthy for 30 seconds -- a
* stream that opens, says one frame and breaks again is not a reason to ask every second.
*
* [jitter] gives a number in 0..1 (0.5 is no jitter).
*/
class Reconnect(private val jitter: () -> Double = { Math.random() }) {
private var step = FIRST_MS
/**
* The pause before the next opening. [healthyMs] is how long the connection that just ended
* had been carrying frames (0 for one that never did); [retryAfterMs] is what the server asked
* for on a 429, honoured when it is the longer of the two (up to [MOST_ASKED_MS]).
*/
fun pause(healthyMs: Long, retryAfterMs: Long = 0): Long {
if (healthyMs >= HEALTHY_MS) step = FIRST_MS
val now = step
step = (step * 2).coerceAtMost(LAST_MS)
val jittered = (now * (0.8 + 0.4 * jitter().coerceIn(0.0, 1.0))).toLong()
return maxOf(jittered, retryAfterMs.coerceIn(0L, MOST_ASKED_MS))
}
companion object {
const val FIRST_MS = 1_000L
const val LAST_MS = 60_000L
const val HEALTHY_MS = 30_000L
/** A server may ask for a long wait; a stream somebody watches is looked at again within five minutes. */
const val MOST_ASKED_MS = 300_000L
}
}
@@ -17,32 +17,40 @@ data class Frame(val event: String, val data: String)
/**
* Follow a reply: the stream's frames, and when the connection drops before `close`, the same
* stream opened again after a pause -- 1, 2, 4, 8 … up to 30 seconds. Nothing is replayed or
* stream opened again after a pause -- the one schedule of [Reconnect]. Nothing is replayed or
* deduplicated: the server's first pass after a reconnect is the whole state, which is exactly
* what [LiveReply.apply] wants.
*
* A refusal (a 4xx: the chat was deleted, the token signed out) ends the flow with the error;
* only a broken connection is retried -- and each opening after the first is a new request, so
* it waits for its `turn` (the gate: nothing new is asked behind a lock).
* only a broken connection is retried, and a 429, which is "later" rather than "no" -- and each
* opening after the first is a new request, so it waits for its `turn` (the gate: nothing new is
* asked behind a lock).
*
* Silence is a broken connection too. Every stream this app follows (a reply's, the person's
* events, a chat's activity) is sent a keepalive by the server at least every 15 seconds, so a
* connection that says nothing for [SILENCE_SECONDS] is dead without having said so -- a phone
* that changed network, a proxy that dropped it -- and is opened again like any other.
*/
class StreamClient(private val api: ApiClient) {
private val http = api.http.newBuilder().readTimeout(0, TimeUnit.SECONDS).build()
private val http = api.http.newBuilder().readTimeout(SILENCE_SECONDS, TimeUnit.SECONDS).build()
fun follow(chatId: String, messageId: String, turn: suspend () -> Unit = {}): Flow<Frame> = reopened(turn) { once(api.streamRequest(chatId, messageId)) }
/**
* Follow an events route that ends itself now and then (`close` after a while, as the
* activity panel's does): opened again at once after a `close`, and after a pause that
* grows to 30 seconds when the connection drops or closes without a frame. It runs until
* activity panel's does): opened again at once after a `close`, and after a pause
* ([Reconnect]) when the connection drops or closes without a frame. It runs until
* its collector stops; a refusal (4xx) ends it with the error. Each opening, the first
* too, waits for its [turn].
*/
fun watch(turn: suspend () -> Unit = {}, request: () -> Request): Flow<Frame> = flow {
var wait = 1_000L
val schedule = Reconnect()
while (true) {
var closed = false
var said = false
var refused: ApiException? = null
var since: Long? = null
var slowed = 0L
// Every opening is a request of its own: it waits for its turn (the gate).
turn()
once(request()).collect { result ->
@@ -52,13 +60,15 @@ class StreamClient(private val api: ApiClient) {
closed = true
} else {
said = true
wait = 1_000L
if (since == null) since = monotonicMs()
emit(result.frame)
}
}
is Outcome.Refused -> refused = result.error
is Outcome.Slowed -> slowed = result.seconds
is Outcome.Dropped -> Unit
}
}
@@ -67,8 +77,7 @@ class StreamClient(private val api: ApiClient) {
// that closes having said nothing waits as a dropped one does: a server that only
// ever answers `close` must not be asked in a tight loop.
if (reopenAtOnce(closed, said)) continue
delay(wait)
wait = (wait * 2).coerceAtMost(30_000L)
delay(schedule.pause(healthyMs = since?.let { monotonicMs() - it } ?: 0L, retryAfterMs = slowed * 1000L))
}
}
@@ -87,7 +96,10 @@ class StreamClient(private val api: ApiClient) {
override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
val code = response?.code ?: 0
if (code in 400..499) {
if (code == 429) {
// "Later", not "no": opened again, after what the server asked for.
trySend(Outcome.Slowed(retryAfterSeconds(response?.header("Retry-After")) ?: 0L))
} else if (code in 400..499) {
trySend(Outcome.Refused(ApiException(code, response?.let { detail(it) } ?: "Refused ($code).")))
} else {
trySend(Outcome.Dropped)
@@ -98,43 +110,62 @@ class StreamClient(private val api: ApiClient) {
)
awaitClose { source.cancel() }
}
companion object {
/**
* How long a stream may say nothing before it counts as broken. The server's keepalive
* comes every 15 seconds on each of the three routes followed here; three of them missed
* is not a slow server.
*/
const val SILENCE_SECONDS = 45L
}
}
/** What one opening of a stream gave: a frame, a refusal (4xx), or a connection that broke. */
/** A clock that only goes forward, in milliseconds: for how long a connection lasted. */
fun monotonicMs(): Long = System.nanoTime() / 1_000_000L
/**
* What one opening of a stream gave: a frame, a refusal (4xx), a "too many requests" (429, with
* the seconds its `Retry-After` asked for, 0 when it named none), or a connection that broke.
*/
sealed interface Outcome {
data class Event(val frame: Frame) : Outcome
data class Refused(val error: ApiException) : Outcome
data class Slowed(val seconds: Long) : Outcome
data object Dropped : Outcome
}
/**
* A reply's stream, [open]ed again whenever it ends before `close`: after a pause of 1, 2, 4, 8 …
* up to 30 seconds, and after its [turn] -- every opening but the first is a request nobody is
* waiting for at that moment, so it asks first whether it may start. A refusal ends the flow
* A reply's stream, [open]ed again whenever it ends before `close`: after a pause by [schedule]
* (1 second doubling to 60, jittered, and short again only after a connection that held for half
* a minute by [clock]), and after its [turn] -- every opening but the first is a request nobody
* is waiting for at that moment, so it asks first whether it may start. A refusal ends the flow
* with the error.
*/
fun reopened(turn: suspend () -> Unit, open: () -> Flow<Outcome>): Flow<Frame> = flow {
var wait = 1_000L
fun reopened(turn: suspend () -> Unit, schedule: Reconnect = Reconnect(), clock: () -> Long = ::monotonicMs, open: () -> Flow<Outcome>): Flow<Frame> = flow {
while (true) {
var closed = false
var refused: ApiException? = null
var since: Long? = null
var slowed = 0L
open().collect { result ->
when (result) {
is Outcome.Event -> {
wait = 1_000L
if (since == null) since = clock()
emit(result.frame)
if (result.frame.event == "close") closed = true
}
is Outcome.Refused -> refused = result.error
is Outcome.Slowed -> slowed = result.seconds
is Outcome.Dropped -> Unit
}
}
refused?.let { throw it }
if (closed) return@flow
delay(wait)
wait = (wait * 2).coerceAtMost(30_000L)
delay(schedule.pause(healthyMs = since?.let { clock() - it } ?: 0L, retryAfterMs = slowed * 1000L))
turn()
}
}
@@ -243,7 +243,9 @@ class AssistController(
val own = prefs.forInstance(instance?.id)
_state.update {
it.copy(
signedIn = instance != null,
// An instance that signed this phone out is "not signed in" here: the sheet says
// to sign in in the app, and asks that instance nothing.
signedIn = instance != null && !instance.signedOut,
instanceName = instance?.name?.ifBlank { instance.base }.orEmpty(),
voiceReply = prefs.readAloudSpoken,
canReadNotifications = prefs.notificationSummaries && NotificationAccess.granted(context),
@@ -260,7 +262,7 @@ class AssistController(
private suspend fun loadRemote() {
val store = context.lembas.instances
val prefs = store.prefs.first()
val instance = store.default() ?: return
val instance = store.default()?.takeUnless { it.signedOut } ?: return
targetId = instance.id
val api = store.clientFor(instance)
val own = prefs.forInstance(instance.id)
@@ -622,7 +624,7 @@ class AssistController(
_state.update { it.copy(conversation = talking) }
try {
val store = context.lembas.instances
val instance = store.default() ?: throw ApiException(401, "Not signed in.")
val instance = store.default()?.takeUnless { it.signedOut } ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
targetId = instance.id
val api = store.clientFor(instance)
val prefs = store.prefs.first()
@@ -21,9 +21,14 @@ import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/** One instance this phone is signed in to. The token is stored encrypted, never in the clear. */
/**
* One instance this phone is signed in to. The token is stored encrypted, never in the clear.
* [signedOut]: the instance refused that token (it was revoked there, or it expired). The entry
* stays -- with its place in the list and every choice kept for it -- until the person signs in
* again, which replaces the token, or removes it; meanwhile nothing more is asked with it.
*/
@Serializable
data class Instance(val id: String, val base: String, val name: String, val email: String, val sealedToken: String)
data class Instance(val id: String, val base: String, val name: String, val email: String, val sealedToken: String, val signedOut: Boolean = false)
/**
* The token's lock: an AES key that lives in the Android Keystore and never leaves it. A copy
@@ -96,6 +101,17 @@ object InstanceLogic {
return Triple(next, added.id, keptDefault)
}
/**
* The list after the instance refused a token: every entry whose token [refused] says it was is
* marked signed out, and nothing else changes -- not which instance is in use, not the default,
* not another instance. Null when no entry changes (the token is nobody's any more, or its
* entry is marked already), so that nothing is written.
*/
fun afterRefusal(instances: List<Instance>, refused: (Instance) -> Boolean): List<Instance>? {
if (instances.none { !it.signedOut && refused(it) }) return null
return instances.map { if (!it.signedOut && refused(it)) it.copy(signedOut = true) else it }
}
/** Removing [removedId] promotes the surviving default (or first) for active, and the
* surviving active (or first) for default, or null when no instance remains. */
fun afterRemove(instances: List<Instance>, removedId: String, currentActive: String?, currentDefault: String?): Triple<List<Instance>, String?, String?> {
@@ -216,9 +232,10 @@ class InstanceStore(private val context: Context) {
suspend fun default(): Instance? = defaultInstance.first()
suspend fun client(): ApiClient? = current()?.let { clientFor(it) }
/** A client for the instance in use; none when there is no instance, or it signed this phone out. */
suspend fun client(): ApiClient? = current()?.takeUnless { it.signedOut }?.let { clientFor(it) }
suspend fun defaultClient(): ApiClient? = default()?.let { clientFor(it) }
suspend fun defaultClient(): ApiClient? = default()?.takeUnless { it.signedOut }?.let { clientFor(it) }
fun clientFor(instance: Instance): ApiClient = ApiClient(instance.base, TokenCipher.open(instance.sealedToken))
@@ -240,6 +257,20 @@ class InstanceStore(private val context: Context) {
return instance
}
/**
* The instance refused [token] (a 401 of its own): the entry that holds it is marked signed
* out. Asked by the token, never by "the one in use": the answer may be to a request of
* another instance, or to one sent before the person switched or signed in again -- a token
* that is no entry's any more marks nothing.
*/
suspend fun refused(token: String) {
context.store.edit { prefs ->
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
val next = InstanceLogic.afterRefusal(all) { runCatching { TokenCipher.open(it.sealedToken) }.getOrNull() == token }
if (next != null) prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, next)
}
}
suspend fun use(id: String) {
context.store.edit { it[ACTIVE] = id }
}
@@ -3,23 +3,94 @@ package eu.llembas.android.ui
import android.content.Context
import eu.llembas.android.R
import eu.llembas.android.api.ApiException
import eu.llembas.android.api.NotLembas
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.NoRouteToHostException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.net.UnknownServiceException
import java.security.cert.CertPathValidatorException
import java.security.cert.CertificateException
import javax.net.ssl.SSLPeerUnverifiedException
/** What went wrong between the phone and an instance, as the kinds a person can tell apart. */
enum class Trouble {
/** The instance said no, or answered with an error: its own sentence, or its number. */
ANSWERED,
/** No way to it: no network, a name that does not resolve, a refused connection. */
UNREACHABLE,
/** It was reached and did not answer in time. */
TIMEOUT,
/** Its certificate is not one this phone trusts. */
NOT_TRUSTED,
/** The address is plain http, which this app does not speak. */
NEEDS_HTTPS,
/** Something answers there, and it is no LLeMbas instance. */
NOT_LEMBAS,
/** None of these: the failure's own message is all there is. */
OTHER,
}
/** Which [Trouble] a failure is. Pure, so the cases are a table in a test. */
fun trouble(e: Throwable): Trouble = when {
e is ApiException -> Trouble.ANSWERED
e is NotLembas -> Trouble.NOT_LEMBAS
untrusted(e) -> Trouble.NOT_TRUSTED
e is UnknownHostException || e is ConnectException || e is NoRouteToHostException -> Trouble.UNREACHABLE
// OkHttp's own timeouts are an InterruptedIOException saying "timeout".
e is SocketTimeoutException || (e is InterruptedIOException && e.message == "timeout") -> Trouble.TIMEOUT
// Android's network policy refusing cleartext: "CLEARTEXT communication to … not permitted".
e is UnknownServiceException && e.message.orEmpty().contains("CLEARTEXT", ignoreCase = true) -> Trouble.NEEDS_HTTPS
else -> Trouble.OTHER
}
/**
* A failure in words a person can act on. The server's refusal is its own sentence; a phone
* that cannot reach the instance at all -- no network, a name that does not resolve off the
* home network, a server that is down -- is one sentence saying so, rather than
* "Unable to resolve host" or "failed to connect to /…:443". A certificate the phone does not
* trust keeps its own message: that one names what to fix.
* A failure in words a person can act on, one sentence for each kind of [Trouble]. The server's
* refusal is its own sentence (a 403 says what is not allowed, and signs nobody out); an answer
* without one is said with its number -- "the server answered 502" is never "cannot be reached"
* and never "not a LLeMbas instance". A phone that cannot reach the instance at all, one that
* waited in vain, and a certificate the phone does not trust each say so, the last with what to
* do about it.
*/
fun Context.explain(e: Throwable): String = when {
e is ApiException -> e.message?.ifBlank { null } ?: getString(R.string.offline)
unreachable(e) -> getString(R.string.offline)
else -> e.message?.ifBlank { null } ?: e.javaClass.simpleName
fun Context.explain(e: Throwable): String = when (trouble(e)) {
Trouble.ANSWERED -> e.message?.ifBlank { null } ?: getString(R.string.server_answered, ((e as? ApiException)?.status ?: 0).toString())
Trouble.UNREACHABLE -> getString(R.string.offline)
Trouble.TIMEOUT -> getString(R.string.timed_out)
Trouble.NOT_TRUSTED -> getString(R.string.not_trusted)
Trouble.NEEDS_HTTPS -> getString(R.string.address_needs_https)
Trouble.NOT_LEMBAS -> getString(R.string.signin_not_lembas)
Trouble.OTHER -> e.message?.ifBlank { null } ?: e.javaClass.simpleName
}
/** Whether a failure means "the instance cannot be reached" rather than "it said no". */
fun unreachable(e: Throwable): Boolean = e is UnknownHostException || e is ConnectException || e is SocketTimeoutException || e is NoRouteToHostException
/**
* Whether a failure is a certificate this phone does not trust: no authority the phone knows
* signed it, it is out of date, or the name on it is another host's. Looked for down the
* causes, where the platform puts it under the handshake's failure -- a handshake that failed
* for another reason (no protocol in common) is not this.
*/
fun untrusted(e: Throwable): Boolean {
var at: Throwable? = e
var depth = 0
while (at != null && depth < 8) {
if (at is SSLPeerUnverifiedException || at is CertificateException || at is CertPathValidatorException) return true
at = at.cause
depth++
}
return false
}
@@ -42,6 +42,7 @@ import eu.llembas.android.api.Whereabouts
import eu.llembas.android.api.named
import eu.llembas.android.api.serving
import eu.llembas.android.api.whereabouts
import eu.llembas.android.auth.Instance
import eu.llembas.android.lembas
import eu.llembas.android.ui.explain
import eu.llembas.android.ui.files.noSuchRoute
@@ -370,8 +371,26 @@ class ChatViewModel(app: Application) :
private var agentChat = false
private var api: ApiClient? = null
private suspend fun api(): ApiClient = api ?: getApplication<Application>().lembas.instances.client()?.also { api = it }
?: throw ApiException(401, "Not signed in.")
/** The instance this screen's chat is on, as it was when [api] was made: its id, and the token it was made with. */
private var apiOf: Instance? = null
/**
* The client for this screen's instance: the one in use when the screen first asked, and that
* one from then on. It is made again when the instance has another token (the person signed
* in again after the instance signed this phone out) -- the old one would be refused for
* ever -- and there is none while the instance is signed out, or once it was removed.
*/
private suspend fun api(): ApiClient {
val store = getApplication<Application>().lembas.instances
val mine = apiOf?.id
val now = (if (mine == null) store.current() else store.instances.first().firstOrNull { it.id == mine })
?.takeUnless { it.signedOut } ?: throw ApiException(401, getApplication<Application>().getString(R.string.assist_signed_out))
api?.takeIf { apiOf?.sealedToken == now.sealedToken }?.let { return it }
return store.clientFor(now).also {
api = it
apiOf = now
}
}
private fun fail(e: Throwable) {
// A follow that was replaced by a newer one is cancelled, not failed: nothing to say.
@@ -19,11 +19,13 @@ import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@@ -47,17 +49,22 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.llembas.android.R
import eu.llembas.android.api.Address
import eu.llembas.android.api.ApiException
import eu.llembas.android.api.Doorstep
import eu.llembas.android.api.ServerFit
import eu.llembas.android.api.address
import eu.llembas.android.api.fit
import eu.llembas.android.api.normaliseBase
import eu.llembas.android.auth.Instance
import eu.llembas.android.lembas
import eu.llembas.android.ui.explain
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.io.IOException
/** Where the sign-in is. The token arrives once, by device code, as `lembas login` gets it. */
sealed interface SignInState {
@@ -68,25 +75,56 @@ sealed interface SignInState {
data object Done : SignInState
}
/** The sentence for a server this app will not work with, or null when it fits. */
/**
* The sentence for a server this app will not work with, or null when it fits. Each reason has
* its own, and each says which side is the old one: another service is not "an older LLeMbas".
*/
fun refusal(fit: ServerFit): Int? = when (fit) {
ServerFit.FITS -> null
ServerFit.NOT_LEMBAS, ServerFit.TOO_OLD -> R.string.signin_too_old
ServerFit.NOT_LEMBAS -> R.string.signin_not_lembas
ServerFit.TOO_OLD -> R.string.signin_too_old
ServerFit.TOO_NEW -> R.string.signin_too_new
}
/** The sentence for an address that cannot be used as it was typed, or null for one that can (or for none yet). */
fun refusal(read: Address): Int? = when (read) {
is Address.Base, Address.Empty -> null
Address.NeedsHttps -> R.string.address_needs_https
Address.NotHttp, Address.Unreadable -> R.string.address_unreadable
}
/**
* The sentence a poll's `error` ends the sign-in with, or null while it goes on (still waiting,
* or asked to wait longer). Each end by its real reason: only an expired code is "expired".
*/
fun pollEnd(error: String?): Int? = when (error) {
"authorization_pending", "slow_down" -> null
"access_denied" -> R.string.signin_denied
"expired_token" -> R.string.signin_expired
else -> R.string.signin_failed
}
class SignInViewModel(app: Application) : AndroidViewModel(app) {
private val _state = MutableStateFlow<SignInState>(SignInState.Address)
val state = _state.asStateFlow()
private var polling: Job? = null
fun start(typed: String) {
// The address is read before anything is asked: what is wrong with it is said at this step.
val read = address(typed)
val base = (read as? Address.Base)?.url
if (base == null) {
refusal(read)?.let { said ->
polling?.cancel()
_state.value = SignInState.Failed(getApplication<Application>().getString(said))
}
return
}
polling?.cancel()
polling = viewModelScope.launch {
_state.value = SignInState.Finding
val doorstep = Doorstep()
try {
val base = normaliseBase(typed)
val found = doorstep.discover(base)
refusal(fit(found))?.let { said ->
_state.value = SignInState.Failed(getApplication<Application>().getString(said))
@@ -97,9 +135,28 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) {
_state.value = SignInState.Code(code.userCode, code.verificationUriComplete.ifEmpty { code.verificationUri })
var interval = code.interval.coerceAtLeast(2) * 1000L
val until = System.currentTimeMillis() + code.expiresIn * 1000L
// What last went wrong with a poll, if the code runs out with nothing better to say.
var trouble: Exception? = null
while (System.currentTimeMillis() < until) {
delay(interval)
val answer = doorstep.deviceToken(found.login.device.token, code.deviceCode)
val answer = try {
doorstep.deviceToken(found.login.device.token, code.deviceCode).also { trouble = null }
} catch (e: ApiException) {
// "Too many requests" is asked again, later; a server in trouble (5xx) may
// be back before the code runs out. Any other answer ends the sign-in.
if (e.status == 429) {
interval = maxOf(interval + 5000L, (e.retryAfter ?: 0L) * 1000L)
} else if (e.status < 500) {
throw e
}
trouble = e
continue
} catch (e: IOException) {
// The phone was away for a moment (the browser came to the front, the
// network changed): the approval may still come, so the next poll asks.
trouble = e
continue
}
when {
answer.accessToken != null -> {
val account = answer.account
@@ -115,20 +172,19 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) {
answer.error == "slow_down" -> interval += 5000L
answer.error == "authorization_pending" -> Unit
answer.error == "access_denied" -> {
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_denied))
return@launch
}
else -> {
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
else -> pollEnd(answer.error)?.let { said ->
_state.value = SignInState.Failed(getApplication<Application>().getString(said, answer.error.orEmpty()))
return@launch
}
}
}
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
val last = trouble
_state.value = SignInState.Failed(
if (last != null) getApplication<Application>().explain(last) else getApplication<Application>().getString(R.string.signin_expired),
)
} catch (e: CancellationException) {
// Given up (Cancel, or a new start): not a failure, and nothing to say.
throw e
} catch (e: Exception) {
_state.value = SignInState.Failed(getApplication<Application>().explain(e))
}
@@ -139,12 +195,18 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) {
polling?.cancel()
_state.value = SignInState.Address
}
/** A sign-in that was finished the last time this page was up starts from the address again. */
fun fresh() {
if (_state.value == SignInState.Done) _state.value = SignInState.Address
}
}
@Composable
fun SignInScreen(onDone: () -> Unit = {}, onCancel: (() -> Unit)? = null, model: SignInViewModel = viewModel()) {
val state by model.state.collectAsStateWithLifecycle()
LaunchedEffect(state) { if (state == SignInState.Done) onDone() }
LaunchedEffect(Unit) { model.fresh() }
var address by rememberSaveable { mutableStateOf("") }
val context = LocalContext.current
val knownBases by context.lembas.instances.instances.collectAsState(initial = emptyList())
@@ -200,14 +262,71 @@ fun SignInScreen(onDone: () -> Unit = {}, onCancel: (() -> Unit)? = null, model:
SignInState.Finding, SignInState.Done -> CircularProgressIndicator()
is SignInState.Code -> {
Text(stringResource(R.string.signin_code_intro), modifier = Modifier.widthIn(max = 420.dp))
Text(s.userCode, fontFamily = FontFamily.Monospace, fontSize = 32.sp, style = MaterialTheme.typography.headlineLarge)
Button(onClick = { CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(s.verify)) }) {
Text(stringResource(R.string.signin_open_browser))
is SignInState.Code -> CodeStep(s, onCancel = { model.reset() })
}
}
}
/** The code to approve in the browser, and the way there. Laid out by the column it is put in. */
@Composable
private fun CodeStep(code: SignInState.Code, onCancel: () -> Unit) {
val context = LocalContext.current
Text(stringResource(R.string.signin_code_intro), modifier = Modifier.widthIn(max = 420.dp))
Text(code.userCode, fontFamily = FontFamily.Monospace, fontSize = 32.sp, style = MaterialTheme.typography.headlineLarge)
Button(onClick = { CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(code.verify)) }) {
Text(stringResource(R.string.signin_open_browser))
}
CircularProgressIndicator()
OutlinedButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) }
}
/**
* The instance signed this phone out (it refused the token: revoked there, or expired). Shown
* over the instance's pages, which stay as they were underneath -- what was being written is
* still there after the sign-in. One step back in: the address is known, so "Sign in again"
* goes straight to the code. The other instances stay a tap away, and this one can be removed.
*/
@Composable
fun SignedOutScreen(
instance: Instance,
others: List<Instance>,
onUse: (Instance) -> Unit,
onRemove: () -> Unit,
model: SignInViewModel = viewModel(key = "signed-out:" + instance.id),
) {
val state by model.state.collectAsStateWithLifecycle()
LaunchedEffect(Unit) { model.fresh() }
Surface(modifier = Modifier.fillMaxSize()) {
Column(
// It scrolls: several other instances, large type or a small screen must not push a button out of reach.
modifier = Modifier.fillMaxSize().safeDrawingPadding().verticalScroll(rememberScrollState()).padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(stringResource(R.string.app_name), style = MaterialTheme.typography.headlineMedium)
Text(
stringResource(R.string.signed_out, instance.name.ifBlank { instance.base }),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.widthIn(max = 420.dp),
)
when (val s = state) {
SignInState.Address, is SignInState.Failed -> {
if (s is SignInState.Failed) {
Text(s.message, color = MaterialTheme.colorScheme.error, modifier = Modifier.widthIn(max = 420.dp))
}
Button(onClick = { model.start(instance.base) }) { Text(stringResource(R.string.signed_out_again)) }
others.forEach { other ->
OutlinedButton(onClick = { onUse(other) }) {
Text(stringResource(R.string.signed_out_use, other.name.ifBlank { other.base }))
}
}
TextButton(onClick = onRemove) { Text(stringResource(R.string.signed_out_remove)) }
}
CircularProgressIndicator()
OutlinedButton(onClick = { model.reset() }) { Text(stringResource(R.string.cancel)) }
SignInState.Finding, SignInState.Done -> CircularProgressIndicator()
is SignInState.Code -> CodeStep(s, onCancel = { model.reset() })
}
}
}