diff --git a/CHANGELOG.md b/CHANGELOG.md index cb9d318..0e11d22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,15 @@ How the app connects to an instance, brought in line with the other LLeMbas clie `example.org:8443/` are read as the other LLeMbas clients read them: the scheme in any case, the host in lower case, the path dropped. An `http://` address is answered where it is typed -- this app needs https -- instead of failing later with a library's error. +- **The address you typed is the one kept.** A new sign-in stores the address as it was typed + (read by the rule above), not the one the instance says of itself, and the sign-in itself goes + only to that address: an instance whose proxy makes it name another host says so in words. + Instances already on the phone are untouched -- same entry, same token, same settings, same + notifications -- and signing in again to one of them, by either address, refreshes that entry + rather than adding a second one. +- **An instance can say the app is too old.** Where an instance names the oldest version of + the app it works with (`min_clients` in its discovery document) and this one is older, the app + says so with both versions and does not go on. - **Each failure says what it is.** Cannot be reached, did not answer in time, a certificate the phone does not trust (with where to install the CA), no LLeMbas instance at the address, "the server answered 502", an instance too old, an app too old: one sentence each. A server in diff --git a/app/src/main/java/eu/llembas/android/api/Address.kt b/app/src/main/java/eu/llembas/android/api/Address.kt index 5aba289..9ec6165 100644 --- a/app/src/main/java/eu/llembas/android/api/Address.kt +++ b/app/src/main/java/eu/llembas/android/api/Address.kt @@ -49,3 +49,23 @@ fun address(typed: String): Address { else -> Address.NotHttp } } + +/** + * Whether two stored or said bases name one instance: compared as [address] reads them, so that + * a capital, a trailing slash or the scheme's own port makes no difference. One that the rule + * does not read (an `http://` base a server once said of itself) is compared as it stands. + */ +fun sameBase(one: String, other: String): Boolean = canonical(one) == canonical(other) + +private fun canonical(base: String): String = (address(base) as? Address.Base)?.url ?: base.trim().trimEnd('/').lowercase() + +/** + * Whether [url] is on the origin of [base]: the same scheme, host and port. An endpoint a + * discovery document names is used only then -- the token and the sign-in go to the address the + * person typed and to no other host, whatever the document says. + */ +fun onOrigin(base: String, url: String): Boolean { + val home = base.toHttpUrlOrNull() ?: return false + val there = url.toHttpUrlOrNull() ?: return false + return home.scheme == there.scheme && home.host == there.host && home.port == there.port +} diff --git a/app/src/main/java/eu/llembas/android/api/Compat.kt b/app/src/main/java/eu/llembas/android/api/Compat.kt index 385532e..fbcfe3b 100644 --- a/app/src/main/java/eu/llembas/android/api/Compat.kt +++ b/app/src/main/java/eu/llembas/android/api/Compat.kt @@ -1,5 +1,8 @@ package eu.llembas.android.api +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive + /** * The app API this app reads: 2, the server's 2.0 (no canvas, no `knowledge_bases`, the `show` * card and its route, and the person's files). A server with a newer one is told about, not @@ -29,3 +32,38 @@ fun fit(found: Discovery): ServerFit { else -> ServerFit.FITS } } + +/** This app's name among the products a discovery document's `min_clients` lists. */ +const val PRODUCT = "android" + +/** The oldest version of [product] the instance says it works with, or null: nothing said, or not in words this app reads. */ +fun Discovery.minClient(product: String = PRODUCT): String? { + val said = (minClients as? JsonObject)?.get(product) as? JsonPrimitive ?: return null + return said.takeIf { it.isString }?.content?.trim()?.ifEmpty { null } +} + +private val VERSION = Regex("""^v?(\d+)\.(\d+)\.(\d+)(?:-beta\.(\d+))?""") + +/** + * A version as numbers that compare: `1.2.3` or `1.2.3-beta.4`, a release above every beta of + * itself. Whatever follows is a build's own mark (`-debug.12`, a flavour) and is left off. Null + * for what is no such version. + */ +fun versionNumbers(text: String): List? { + val match = VERSION.find(text.trim()) ?: return null + val (major, minor, patch, beta) = match.destructured + val parts = listOf(major.toIntOrNull(), minor.toIntOrNull(), patch.toIntOrNull(), if (beta.isEmpty()) Int.MAX_VALUE else beta.toIntOrNull()) + return if (parts.any { it == null }) null else parts.filterNotNull() +} + +/** + * Whether the version [mine] is older than [needed]. By numbers, never as text: `1.0.0-beta.10` + * is newer than `1.0.0-beta.9`, and `1.0.0` newer than both. False when either cannot be read: + * a document that says nonsense locks nobody out. + */ +fun olderThan(mine: String, needed: String): Boolean { + val own = versionNumbers(mine) ?: return false + val least = versionNumbers(needed) ?: return false + for (i in own.indices) if (own[i] != least[i]) return own[i] < least[i] + return false +} diff --git a/app/src/main/java/eu/llembas/android/api/Models.kt b/app/src/main/java/eu/llembas/android/api/Models.kt index 54fa672..ffa3c7c 100644 --- a/app/src/main/java/eu/llembas/android/api/Models.kt +++ b/app/src/main/java/eu/llembas/android/api/Models.kt @@ -33,6 +33,12 @@ data class Discovery( @SerialName("app_api") val appApi: Int = 0, val login: Login = Login(), val scopes: List = emptyList(), + /** + * The oldest version of each client the instance works with, by product (`{"android": "1.0.0"}`). + * Kept as whatever the document says -- read through [minClient], so that a shape this app + * does not expect is "says nothing", never "not a LLeMbas instance". + */ + @SerialName("min_clients") val minClients: JsonElement? = null, ) { @Serializable data class Login(val device: DeviceLogin = DeviceLogin()) diff --git a/app/src/main/java/eu/llembas/android/auth/Instances.kt b/app/src/main/java/eu/llembas/android/auth/Instances.kt index cab874c..01cfad7 100644 --- a/app/src/main/java/eu/llembas/android/auth/Instances.kt +++ b/app/src/main/java/eu/llembas/android/auth/Instances.kt @@ -9,6 +9,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import eu.llembas.android.api.ApiClient import eu.llembas.android.api.LembasJson +import eu.llembas.android.api.sameBase import eu.llembas.android.wake.WakeAttempt import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first @@ -23,6 +24,10 @@ import javax.crypto.spec.GCMParameterSpec /** * One instance this phone is signed in to. The token is stored encrypted, never in the clear. + * [base] is the address the person typed, as the address rule reads it; what the instance says + * of its own address is not kept. [id] is a key and nothing more: whatever it was made from, it + * is never taken apart or made again -- the choices kept for the instance, its notifications and + * its push registration all hang on it. * [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. @@ -93,6 +98,21 @@ object InstanceLogic { fun pickActive(instances: List, activeId: String?, defaultId: String?): Instance? = instances.firstOrNull { it.id == activeId } ?: pickDefault(instances, defaultId) + /** + * The entry a finished sign-in is kept as. An instance already here for the same account -- + * its stored base is the address just typed, or the one the instance says of itself + * ([said], which older versions of the app stored) -- is that same instance: it keeps its + * id, and so everything kept under it, and gets the new token and the typed address. Only an + * instance that is not here yet is a new entry, its id made from the typed address. + */ + fun signedIn(instances: List, typed: String, said: String, name: String, email: String, sealedToken: String): Instance { + val twin = instances.firstOrNull { + it.email.equals(email, ignoreCase = true) && (sameBase(it.base, typed) || (said.isNotBlank() && sameBase(it.base, said))) + } + return twin?.copy(base = typed, name = name, sealedToken = sealedToken, signedOut = false) + ?: Instance(id = "$email@$typed", base = typed, name = name, email = email, sealedToken = sealedToken) + } + /** Adding [added] replaces any existing entry with the same id, makes it active, and sets it * as default only when no surviving default exists yet. */ fun afterAdd(instances: List, added: Instance, currentDefault: String?): Triple, String, String> { @@ -239,22 +259,21 @@ class InstanceStore(private val context: Context) { fun clientFor(instance: Instance): ApiClient = ApiClient(instance.base, TokenCipher.open(instance.sealedToken)) - suspend fun add(base: String, name: String, email: String, token: String): Instance { - val instance = Instance( - id = "$email@$base", - base = base, - name = name, - email = email, - sealedToken = TokenCipher.seal(token), - ) + /** + * A sign-in finished: at [base], the address the person typed as the address rule reads it, + * which is the one kept. [said] is the instance's own word for its address -- never stored, + * and looked at only to know an instance signed in to before ([InstanceLogic.signedIn]). + */ + suspend fun add(base: String, said: String, name: String, email: String, token: String) { + val locked = TokenCipher.seal(token) context.store.edit { prefs -> val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList() + val instance = InstanceLogic.signedIn(all, base, said, name, email, locked) val (next, activeId, defaultId) = InstanceLogic.afterAdd(all, instance, prefs[DEFAULT]) prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, next) prefs[ACTIVE] = activeId prefs[DEFAULT] = defaultId } - return instance } /** diff --git a/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt b/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt index e8f35e1..62de620 100644 --- a/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt +++ b/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt @@ -90,11 +90,10 @@ import eu.llembas.android.api.LembasJson import eu.llembas.android.api.ReplyFrame import eu.llembas.android.api.ReportsFrame import eu.llembas.android.api.SearchHit -import eu.llembas.android.api.fit import eu.llembas.android.auth.Instance import eu.llembas.android.lembas import eu.llembas.android.ui.explain -import eu.llembas.android.ui.signin.refusal +import eu.llembas.android.ui.signin.unfit import eu.llembas.android.ui.theme.LocalPalette import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job @@ -200,7 +199,7 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) { val state = _state.asStateFlow() /** Why this instance is refused, once it was asked what it is; null while it fits. */ - private var refused: Int? = null + private var refused: String? = null private var checked = false /** Read the list; the rows already shown stay while it is read again. */ @@ -214,11 +213,11 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) { if (!checked) { runCatching { Doorstep().discover(api.base) }.onSuccess { checked = true - refused = refusal(fit(it)) + refused = getApplication().unfit(it) } } refused?.let { said -> - _state.value = ChatsState(error = getApplication().getString(said)) + _state.value = ChatsState(error = said) return@launch } val told = reportsTold diff --git a/app/src/main/java/eu/llembas/android/ui/signin/SignInScreen.kt b/app/src/main/java/eu/llembas/android/ui/signin/SignInScreen.kt index 36222a3..e433feb 100644 --- a/app/src/main/java/eu/llembas/android/ui/signin/SignInScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/signin/SignInScreen.kt @@ -3,6 +3,7 @@ package eu.llembas.android.ui.signin import android.app.Application +import android.content.Context import android.net.Uri import android.os.Build import androidx.browser.customtabs.CustomTabsIntent @@ -48,13 +49,18 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.compose.viewModel +import eu.llembas.android.BuildConfig import eu.llembas.android.R import eu.llembas.android.api.Address import eu.llembas.android.api.ApiException +import eu.llembas.android.api.Discovery 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.minClient +import eu.llembas.android.api.olderThan +import eu.llembas.android.api.onOrigin import eu.llembas.android.auth.Instance import eu.llembas.android.lembas import eu.llembas.android.ui.explain @@ -86,6 +92,22 @@ fun refusal(fit: ServerFit): Int? = when (fit) { ServerFit.TOO_NEW -> R.string.signin_too_new } +/** + * Whether the instance [found] describes asks for a newer app than [version]: the version it + * needs, or null. Asked only of a LLeMbas instance -- what another service says is not a rule. + */ +fun newerAppNeeded(found: Discovery, version: String): String? = found.minClient()?.takeIf { found.service == "lembas" && olderThan(version, it) } + +/** + * Why this app will not work with the instance [found] describes, in words, or null when it + * will. An instance that names an oldest version for this app, above [version], says so with + * both versions -- "update the app" -- before anything else is asked of it. + */ +fun Context.unfit(found: Discovery, version: String = BuildConfig.VERSION_NAME): String? { + newerAppNeeded(found, version)?.let { needed -> return getString(R.string.signin_app_too_old, needed, version) } + return refusal(fit(found))?.let { getString(it) } +} + /** 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 @@ -126,8 +148,17 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) { val doorstep = Doorstep() try { val found = doorstep.discover(base) - refusal(fit(found))?.let { said -> - _state.value = SignInState.Failed(getApplication().getString(said)) + getApplication().unfit(found)?.let { said -> + _state.value = SignInState.Failed(said) + return@launch + } + // The sign-in goes to the address that was typed and to no other host: where the + // document names its doors elsewhere (a proxy that does not pass the address on), + // that is said, rather than a code asked of a host the person never named. + val doors = found.login.device + if (!onOrigin(base, doors.code) || !onOrigin(base, doors.token)) { + val named = doors.code.ifBlank { found.baseUrl } + _state.value = SignInState.Failed(getApplication().getString(R.string.signin_other_origin, named)) return@launch } val device = getApplication().getString(R.string.device_name) @@ -161,7 +192,8 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) { answer.accessToken != null -> { val account = answer.account getApplication().lembas.instances.add( - base = found.baseUrl.ifEmpty { base }.trimEnd('/'), + base = base, + said = found.baseUrl, name = found.name, email = account?.email.orEmpty(), token = answer.accessToken, diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 0412a3a..8cece04 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -15,6 +15,8 @@ Tato instance používá novější rozhraní API pro aplikace než tato aplikace. Aktualizujte aplikaci. Na této adrese není žádná instance LLeMbas. Přihlášení se nepodařilo dokončit (%1$s). Zkuste to znovu. + Tato instance potřebuje LLeMbas pro Android %1$s nebo novější, a toto je %2$s. Aktualizujte aplikaci. + Tato instance uvádí pro přihlášení jinou adresu (%1$s), než jakou jste zadali. Její proxy musí předávat adresu, na které je dostupná. Tato aplikace potřebuje adresu https://: prosté http není podporováno. Tuto adresu aplikace nedokáže použít. Zadejte adresu instance, například llm.example.org. Server odpověděl %1$s. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 2e51f53..d39a24b 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -15,6 +15,8 @@ Diese Instanz spricht eine neuere App-API als diese App. Aktualisieren Sie die App. Unter dieser Adresse gibt es keine LLeMbas-Instanz. Die Anmeldung konnte nicht abgeschlossen werden (%1$s). Versuchen Sie es erneut. + Diese Instanz braucht LLeMbas für Android %1$s oder neuer, und dies ist %2$s. Aktualisieren Sie die App. + Diese Instanz nennt für die Anmeldung eine andere Adresse (%1$s) als die eingegebene. Ihr Proxy muss die Adresse weitergeben, unter der sie erreicht wird. Diese App braucht eine https://-Adresse: einfaches http wird nicht unterstützt. Diese Adresse kann die App nicht verwenden. Geben Sie die Adresse der Instanz ein, zum Beispiel llm.example.org. Der Server hat mit %1$s geantwortet. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 55d833c..05c8465 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -15,6 +15,8 @@ Esta instancia habla una API de aplicaciones más reciente que esta aplicación. Actualice la aplicación. No hay ninguna instancia de LLeMbas en esa dirección. No se pudo completar el inicio de sesión (%1$s). Inténtelo de nuevo. + Esta instancia necesita LLeMbas para Android %1$s o posterior, y esta es la %2$s. Actualice la aplicación. + Esta instancia indica para iniciar sesión otra dirección (%1$s) que la que escribió. Su proxy debe transmitir la dirección por la que se accede a ella. Esta aplicación necesita una dirección https://: no se admite http sin cifrar. La aplicación no puede usar esa dirección. Escriba la dirección de la instancia, por ejemplo llm.example.org. El servidor respondió %1$s. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index bed22ab..364db3f 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -15,6 +15,8 @@ Cette instance utilise une API d\'application plus récente que cette application. Mettez à jour l\'application. Il n\'y a pas d\'instance LLeMbas à cette adresse. La connexion n\'a pas pu aboutir (%1$s). Réessayez. + Cette instance nécessite LLeMbas pour Android %1$s ou plus récent, et ceci est la version %2$s. Mettez à jour l\'application. + Cette instance indique pour la connexion une autre adresse (%1$s) que celle que vous avez saisie. Son proxy doit transmettre l\'adresse par laquelle elle est jointe. Cette application a besoin d\'une adresse https:// : le simple http n\'est pas pris en charge. L\'application ne peut pas utiliser cette adresse. Saisissez l\'adresse de l\'instance, par exemple llm.example.org. Le serveur a répondu %1$s. diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index b597e5a..ee65114 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -15,6 +15,8 @@ Ez a példány újabb alkalmazás-API-t használ, mint ez az alkalmazás. Frissítse az alkalmazást. Ezen a címen nincs LLeMbas példány. A bejelentkezést nem sikerült befejezni (%1$s). Próbálja újra. + Ehhez a példányhoz az Androidos LLeMbas %1$s vagy újabb verziója kell, ez pedig a %2$s. Frissítse az alkalmazást. + Ez a példány más címet ad meg a bejelentkezéshez (%1$s), mint amit beírt. A proxyjának tovább kell adnia azt a címet, amelyen elérik. Ehhez az alkalmazáshoz https:// cím kell: a sima http nem támogatott. Ezt a címet az alkalmazás nem tudja használni. Írja be a példány címét, például llm.example.org. A kiszolgáló válasza: %1$s. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 45c31b5..7d032c6 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -15,6 +15,8 @@ Questa istanza usa un\'API per l\'app più recente di questa app. Aggiorna l\'app. Non c\'è nessuna istanza LLeMbas a quell\'indirizzo. Non è stato possibile completare l\'accesso (%1$s). Riprova. + Questa istanza richiede LLeMbas per Android %1$s o successivo, e questa è la %2$s. Aggiorna l\'app. + Questa istanza indica per l\'accesso un indirizzo diverso (%1$s) da quello che hai scritto. Il suo proxy deve inoltrare l\'indirizzo con cui viene raggiunta. Questa app richiede un indirizzo https://: il semplice http non è supportato. L\'app non può usare questo indirizzo. Scrivi l\'indirizzo dell\'istanza, ad esempio llm.example.org. Il server ha risposto %1$s. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index d61a8b3..1204fb0 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -15,6 +15,8 @@ Ta instancja używa nowszego API aplikacji niż ta aplikacja. Zaktualizuj aplikację. Pod tym adresem nie ma instancji LLeMbas. Nie udało się dokończyć logowania (%1$s). Spróbuj ponownie. + Ta instancja wymaga LLeMbas dla Androida %1$s lub nowszego, a to jest %2$s. Zaktualizuj aplikację. + Ta instancja podaje do logowania inny adres (%1$s) niż wpisany. Jej proxy musi przekazywać adres, pod którym jest dostępna. Ta aplikacja wymaga adresu https://: zwykłe http nie jest obsługiwane. Aplikacja nie może użyć tego adresu. Wpisz adres instancji, na przykład llm.example.org. Serwer odpowiedział: %1$s. diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index d54f6e0..2005a14 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -15,6 +15,8 @@ Táto inštancia používa novšie API pre aplikácie než táto aplikácia. Aktualizujte aplikáciu. Na tejto adrese nie je žiadna inštancia LLeMbas. Prihlásenie sa nepodarilo dokončiť (%1$s). Skúste to znova. + Táto inštancia potrebuje LLeMbas pre Android %1$s alebo novší, a toto je %2$s. Aktualizujte aplikáciu. + Táto inštancia uvádza na prihlásenie inú adresu (%1$s), než akú ste zadali. Jej proxy musí odovzdávať adresu, na ktorej je dostupná. Táto aplikácia potrebuje adresu https://: obyčajné http nie je podporované. Túto adresu aplikácia nevie použiť. Zadajte adresu inštancie, napríklad llm.example.org. Server odpovedal %1$s. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index af7186a..f45b3e8 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -16,6 +16,8 @@ This instance speaks a newer app API than this app. Update the app. There is no LLeMbas instance at that address. The sign-in could not be completed (%1$s). Try again. + This instance needs LLeMbas for Android %1$s or newer, and this is %2$s. Update the app. + This instance names another address for signing in (%1$s) than the one you typed. Its proxy has to pass on the address it is reached by. This app needs an https:// address: plain http is not supported. That is not an address this app can use. Type the instance\'s address, like llm.example.org. The server answered %1$s. diff --git a/app/src/test/java/eu/llembas/android/ConnectionTest.kt b/app/src/test/java/eu/llembas/android/ConnectionTest.kt index b74fc43..c873716 100644 --- a/app/src/test/java/eu/llembas/android/ConnectionTest.kt +++ b/app/src/test/java/eu/llembas/android/ConnectionTest.kt @@ -3,6 +3,7 @@ package eu.llembas.android import eu.llembas.android.api.Address import eu.llembas.android.api.ApiClient import eu.llembas.android.api.ApiException +import eu.llembas.android.api.Discovery import eu.llembas.android.api.Doorstep import eu.llembas.android.api.Frame import eu.llembas.android.api.LembasJson @@ -15,13 +16,20 @@ import eu.llembas.android.api.StreamClient import eu.llembas.android.api.USER_AGENT import eu.llembas.android.api.address import eu.llembas.android.api.fit +import eu.llembas.android.api.minClient +import eu.llembas.android.api.olderThan +import eu.llembas.android.api.onOrigin import eu.llembas.android.api.refusedToken import eu.llembas.android.api.reopened import eu.llembas.android.api.retryAfterSeconds +import eu.llembas.android.api.sameBase import eu.llembas.android.api.userAgent +import eu.llembas.android.api.versionNumbers import eu.llembas.android.auth.Instance import eu.llembas.android.auth.InstanceLogic +import eu.llembas.android.auth.Prefs import eu.llembas.android.ui.Trouble +import eu.llembas.android.ui.signin.newerAppNeeded import eu.llembas.android.ui.signin.pollEnd import eu.llembas.android.ui.signin.refusal import eu.llembas.android.ui.trouble @@ -111,6 +119,153 @@ class ConnectionTest { assertNull(refusal(Address.Base("https://example.org"))) } + // --- Which address is kept, and which instance a sign-in is --------------------------------- + + private val listed = ListSerializer(Instance.serializer()) + + /** What a version of the app before this one stored: the instance's own word for its address, and an id made of it. */ + private val stored = """[ + {"id":"alice@https://home.example","base":"https://home.example","name":"Home","email":"alice","sealedToken":"t1"}, + {"id":"bob@https://Work.example:8443","base":"https://Work.example:8443","name":"Work","email":"bob","sealedToken":"t2"} + ]""" + + @Test + fun anInstanceFromBeforeIsUntouchedByTheUpgrade() { + val read = LembasJson.decodeFromString(listed, stored) + // Nothing is made again on reading: the id, the base and the token are what was stored, to the letter. + assertEquals(listOf("alice@https://home.example", "bob@https://Work.example:8443"), read.map { it.id }) + assertEquals(listOf("https://home.example", "https://Work.example:8443"), read.map { it.base }) + assertEquals(listOf("t1", "t2"), read.map { it.sealedToken }) + assertTrue(read.none { it.signedOut }) + // Which one is in use and which is the default are found by those same ids. + assertEquals(read[1], InstanceLogic.pickActive(read, "bob@https://Work.example:8443", "alice@https://home.example")) + assertEquals(read[0], InstanceLogic.pickDefault(read, "alice@https://home.example")) + // And what is kept per instance is still found under them. + val prefs = Prefs().withInstance(read[1].id) { it.copy(assistantModel = "fast-work") } + assertEquals("fast-work", prefs.forInstance(LembasJson.decodeFromString(listed, stored)[1].id).assistantModel) + } + + @Test + fun aSignInToAnInstanceAlreadyHereRefreshesItAndAddsNoTwin() { + val before = LembasJson.decodeFromString(listed, stored) + // Typed by another name than the one stored; the instance still says the old one of itself. + val again = InstanceLogic.signedIn( + before, + typed = "https://home.example.net", + said = "https://home.example/", + name = "Home", + email = "Alice", + sealedToken = "t9", + ) + assertEquals("alice@https://home.example", again.id) + assertEquals("https://home.example.net", again.base) + assertEquals("t9", again.sealedToken) + assertEquals("alice", again.email) + val (list, active, default) = InstanceLogic.afterAdd(before, again, "bob@https://Work.example:8443") + assertEquals(2, list.size) + assertEquals(setOf("alice@https://home.example", "bob@https://Work.example:8443"), list.map { it.id }.toSet()) + assertEquals("alice@https://home.example", active) + assertEquals("bob@https://Work.example:8443", default) + // Another account at the same address is another instance, as it always was. + val carol = InstanceLogic.signedIn( + before, + typed = "https://home.example", + said = "https://home.example", + name = "Home", + email = "carol", + sealedToken = "t3", + ) + assertEquals("carol@https://home.example", carol.id) + assertEquals(3, InstanceLogic.afterAdd(before, carol, null).first.size) + // And the same account somewhere else is a new one too: its id is made of the typed address. + val elsewhere = InstanceLogic.signedIn(before, typed = "https://other.example", said = "", name = "Other", email = "alice", sealedToken = "t4") + assertEquals("alice@https://other.example", elsewhere.id) + assertEquals("https://other.example", elsewhere.base) + } + + @Test + fun aSignedOutInstanceSignedInToAgainIsItselfAgain() { + val before = LembasJson.decodeFromString(listed, stored).map { it.copy(signedOut = true) } + val again = InstanceLogic.signedIn(before, typed = "https://home.example", said = "", name = "Home", email = "alice", sealedToken = "t9") + assertEquals("alice@https://home.example", again.id) + assertFalse(again.signedOut) + assertTrue(InstanceLogic.afterAdd(before, again, null).first.single { it.id == "bob@https://Work.example:8443" }.signedOut) + } + + @Test + fun anAddressTypedInItsVariantsIsOneInstance() { + val before = LembasJson.decodeFromString(listed, stored) + val variants = listOf("work.example:8443", "HTTPS://WORK.example:8443/", "https://work.example:8443/chat?x=1#y", " https://Work.Example:8443 ") + for (typed in variants) { + val base = (address(typed) as Address.Base).url + assertEquals(typed, "https://work.example:8443", base) + val again = InstanceLogic.signedIn(before, typed = base, said = "", name = "Work", email = "bob", sealedToken = "t9") + // The entry stored with a capital in its base is found, and keeps its id as it was stored. + assertEquals(typed, "bob@https://Work.example:8443", again.id) + assertEquals(typed, 2, InstanceLogic.afterAdd(before, again, null).first.size) + } + assertTrue(sameBase("https://example.org", "https://EXAMPLE.org:443/")) + assertFalse(sameBase("https://example.org", "https://example.org:8443")) + assertFalse(sameBase("https://example.org", "https://www.example.org")) + // A base the rule does not read (an older version stored what the instance said) is compared as it stands. + assertTrue(sameBase("http://inside.example:8000", "http://Inside.example:8000/")) + assertFalse(sameBase("http://inside.example:8000", "https://inside.example:8000")) + } + + @Test + fun theSignInGoesOnlyToTheAddressThatWasTyped() { + assertTrue(onOrigin("https://llm.example.org", "https://llm.example.org/api/device/code")) + assertTrue(onOrigin("https://llm.example.org", "https://LLM.example.org:443/api/device/token")) + assertFalse(onOrigin("https://llm.example.org", "https://other.example.org/api/device/code")) + assertFalse(onOrigin("https://llm.example.org", "http://llm.example.org/api/device/code")) + assertFalse(onOrigin("https://llm.example.org", "https://llm.example.org:8443/api/device/code")) + assertFalse(onOrigin("https://llm.example.org", "")) + } + + // --- An instance that needs a newer app ------------------------------------------------------ + + private fun found(json: String) = LembasJson.decodeFromString(Discovery.serializer(), json) + + @Test + fun versionsCompareByTheirNumbers() { + assertTrue(olderThan("1.0.0-beta.9", "1.0.0-beta.10")) + assertFalse(olderThan("1.0.0-beta.10", "1.0.0-beta.9")) + assertTrue(olderThan("1.0.0-beta.16", "1.0.0")) + assertFalse(olderThan("1.0.0", "1.0.0-beta.99")) + assertFalse(olderThan("1.0.0-beta.16", "1.0.0-beta.16")) + assertTrue(olderThan("1.9.9", "1.10.0")) + assertTrue(olderThan("1.0.0", "2.0.0-beta.1")) + assertFalse(olderThan("2.0.0-beta.1", "1.99.99")) + // A build's own mark is left off: a test build of beta.16 is beta.16. + assertFalse(olderThan("1.0.0-beta.16-debug.412", "1.0.0-beta.16")) + assertTrue(olderThan("1.0.0-beta.16-debug.412", "1.0.0-beta.17")) + assertFalse(olderThan("1.0.0-notifications", "1.0.0")) + assertEquals(versionNumbers("1.0.0"), versionNumbers("v1.0.0")) + // Nonsense locks nobody out. + assertFalse(olderThan("1.0.0", "newest")) + assertFalse(olderThan("dev", "9.9.9")) + assertNull(versionNumbers("1.0")) + } + + @Test + fun anInstanceMaySayWhichAppIsTooOld() { + val says = found("""{"service":"lembas","min_clients":{"android":"1.0.0","desktop":"1.2.0"},"something_new":{"a":[1,2]}}""") + assertEquals("1.0.0", says.minClient()) + assertEquals("1.0.0", newerAppNeeded(says, "1.0.0-beta.16")) + assertNull(newerAppNeeded(says, "1.0.0")) + assertNull(newerAppNeeded(says, "1.0.1-debug.3")) + // Said of other products only, or not at all: nothing is asked of this app. + assertNull(found("""{"service":"lembas","min_clients":{"desktop":"9.0.0"}}""").minClient()) + assertNull(found("""{"service":"lembas"}""").minClient()) + // A shape this app does not expect is "says nothing" -- the document is still read. + assertNull(found("""{"service":"lembas","min_clients":["android"]}""").minClient()) + assertNull(found("""{"service":"lembas","min_clients":{"android":7}}""").minClient()) + assertNull(found("""{"service":"lembas","min_clients":{"android":null}}""").minClient()) + assertNull(found("""{"service":"lembas","min_clients":null}""").minClient()) + // Another service's rule is not a rule. + assertNull(newerAppNeeded(found("""{"service":"other","min_clients":{"android":"9.0.0"}}"""), "1.0.0")) + } + // --- Who asks ------------------------------------------------------------------------------ @Test diff --git a/scripts/strings.py b/scripts/strings.py index 307ad24..a7738aa 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -29,6 +29,8 @@ STRINGS: dict[str, str] = { # when an instance signed this phone out. "signin_not_lembas": "There is no LLeMbas instance at that address.", "signin_failed": "The sign-in could not be completed (%1$s). Try again.", + "signin_app_too_old": "This instance needs LLeMbas for Android %1$s or newer, and this is %2$s. Update the app.", + "signin_other_origin": "This instance names another address for signing in (%1$s) than the one you typed. Its proxy has to pass on the address it is reached by.", "address_needs_https": "This app needs an https:// address: plain http is not supported.", "address_unreadable": "That is not an address this app can use. Type the instance's address, like llm.example.org.", "server_answered": "The server answered %1$s.", diff --git a/scripts/strings_own.json b/scripts/strings_own.json index 25be83c..132e3fa 100644 --- a/scripts/strings_own.json +++ b/scripts/strings_own.json @@ -445,7 +445,9 @@ "signed_out": "%1$s tento telefon odhlásila. Přihlaste se znovu a pokračujte: vaše chaty i zdejší nastavení zůstávají.", "signed_out_again": "Přihlásit se znovu", "signed_out_use": "Použít %1$s", - "signed_out_remove": "Odebrat tuto instanci" + "signed_out_remove": "Odebrat tuto instanci", + "signin_app_too_old": "Tato instance potřebuje LLeMbas pro Android %1$s nebo novější, a toto je %2$s. Aktualizujte aplikaci.", + "signin_other_origin": "Tato instance uvádí pro přihlášení jinou adresu (%1$s), než jakou jste zadali. Její proxy musí předávat adresu, na které je dostupná." }, "de": { "about_version": "LLeMbas für Android %1$s", @@ -894,7 +896,9 @@ "signed_out": "%1$s hat dieses Telefon abgemeldet. Melden Sie sich erneut an, um fortzufahren: Ihre Chats und Ihre Einstellungen hier bleiben erhalten.", "signed_out_again": "Erneut anmelden", "signed_out_use": "%1$s verwenden", - "signed_out_remove": "Diese Instanz entfernen" + "signed_out_remove": "Diese Instanz entfernen", + "signin_app_too_old": "Diese Instanz braucht LLeMbas für Android %1$s oder neuer, und dies ist %2$s. Aktualisieren Sie die App.", + "signin_other_origin": "Diese Instanz nennt für die Anmeldung eine andere Adresse (%1$s) als die eingegebene. Ihr Proxy muss die Adresse weitergeben, unter der sie erreicht wird." }, "es": { "about_version": "LLeMbas para Android %1$s", @@ -1342,7 +1346,9 @@ "signed_out": "%1$s cerró la sesión de este teléfono. Inicie sesión de nuevo para continuar: sus chats y lo que configuró aquí se conservan.", "signed_out_again": "Iniciar sesión de nuevo", "signed_out_use": "Usar %1$s", - "signed_out_remove": "Quitar esta instancia" + "signed_out_remove": "Quitar esta instancia", + "signin_app_too_old": "Esta instancia necesita LLeMbas para Android %1$s o posterior, y esta es la %2$s. Actualice la aplicación.", + "signin_other_origin": "Esta instancia indica para iniciar sesión otra dirección (%1$s) que la que escribió. Su proxy debe transmitir la dirección por la que se accede a ella." }, "fr": { "about_version": "LLeMbas pour Android %1$s", @@ -1791,7 +1797,9 @@ "signed_out": "%1$s a déconnecté ce téléphone. Reconnectez-vous pour continuer : vos discussions et vos réglages ici sont conservés.", "signed_out_again": "Se reconnecter", "signed_out_use": "Utiliser %1$s", - "signed_out_remove": "Retirer cette instance" + "signed_out_remove": "Retirer cette instance", + "signin_app_too_old": "Cette instance nécessite LLeMbas pour Android %1$s ou plus récent, et ceci est la version %2$s. Mettez à jour l'application.", + "signin_other_origin": "Cette instance indique pour la connexion une autre adresse (%1$s) que celle que vous avez saisie. Son proxy doit transmettre l'adresse par laquelle elle est jointe." }, "hu": { "about_version": "LLeMbas Androidra %1$s", @@ -2240,7 +2248,9 @@ "signed_out": "%1$s kijelentkeztette ezt a telefont. A folytatáshoz jelentkezzen be újra: a csevegései és az itteni beállításai megmaradnak.", "signed_out_again": "Bejelentkezés újra", "signed_out_use": "%1$s használata", - "signed_out_remove": "Példány eltávolítása" + "signed_out_remove": "Példány eltávolítása", + "signin_app_too_old": "Ehhez a példányhoz az Androidos LLeMbas %1$s vagy újabb verziója kell, ez pedig a %2$s. Frissítse az alkalmazást.", + "signin_other_origin": "Ez a példány más címet ad meg a bejelentkezéshez (%1$s), mint amit beírt. A proxyjának tovább kell adnia azt a címet, amelyen elérik." }, "it": { "about_version": "LLeMbas per Android %1$s", @@ -2688,7 +2698,9 @@ "signed_out": "%1$s ha disconnesso questo telefono. Accedi di nuovo per continuare: le tue chat e le impostazioni fatte qui restano.", "signed_out_again": "Accedi di nuovo", "signed_out_use": "Usa %1$s", - "signed_out_remove": "Rimuovi questa istanza" + "signed_out_remove": "Rimuovi questa istanza", + "signin_app_too_old": "Questa istanza richiede LLeMbas per Android %1$s o successivo, e questa è la %2$s. Aggiorna l'app.", + "signin_other_origin": "Questa istanza indica per l'accesso un indirizzo diverso (%1$s) da quello che hai scritto. Il suo proxy deve inoltrare l'indirizzo con cui viene raggiunta." }, "pl": { "about_version": "LLeMbas na Androida %1$s", @@ -3136,7 +3148,9 @@ "signed_out": "%1$s wylogowała ten telefon. Zaloguj się ponownie, aby kontynuować: Twoje czaty i tutejsze ustawienia zostają.", "signed_out_again": "Zaloguj się ponownie", "signed_out_use": "Użyj %1$s", - "signed_out_remove": "Usuń tę instancję" + "signed_out_remove": "Usuń tę instancję", + "signin_app_too_old": "Ta instancja wymaga LLeMbas dla Androida %1$s lub nowszego, a to jest %2$s. Zaktualizuj aplikację.", + "signin_other_origin": "Ta instancja podaje do logowania inny adres (%1$s) niż wpisany. Jej proxy musi przekazywać adres, pod którym jest dostępna." }, "sk": { "about_version": "LLeMbas pre Android %1$s", @@ -3584,6 +3598,8 @@ "signed_out": "%1$s tento telefón odhlásila. Prihláste sa znova a pokračujte: vaše chaty aj tunajšie nastavenia zostávajú.", "signed_out_again": "Prihlásiť sa znova", "signed_out_use": "Použiť %1$s", - "signed_out_remove": "Odstrániť túto inštanciu" + "signed_out_remove": "Odstrániť túto inštanciu", + "signin_app_too_old": "Táto inštancia potrebuje LLeMbas pre Android %1$s alebo novší, a toto je %2$s. Aktualizujte aplikáciu.", + "signin_other_origin": "Táto inštancia uvádza na prihlásenie inú adresu (%1$s), než akú ste zadali. Jej proxy musí odovzdávať adresu, na ktorej je dostupná." } }