HubLogin.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubLogin.kt
1package eu.friedcutlet.yokan.services.sync23import dev.whyoleg.cryptography.DelicateCryptographyApi4import dev.whyoleg.cryptography.random.CryptographyRandom5import eu.friedcutlet.yokan.database.DbSyncPreference6import eu.friedcutlet.yokan.database.SyncServerProvider7import eu.friedcutlet.yokan.database.YokanDatabase8import eu.friedcutlet.yokan.database.sync.SyncPaths9import eu.friedcutlet.yokan.services.catchingNonCancellation10import eu.friedcutlet.yokan.services.http.HttpRequest11import eu.friedcutlet.yokan.services.http.HttpResponse12import eu.friedcutlet.yokan.services.http.HttpService13import eu.friedcutlet.yokan.services.http.normalizeHubServer14import eu.friedcutlet.yokan.util.PlatformLock15import io.ktor.http.URLBuilder16import io.ktor.http.Url17import io.ktor.http.parseQueryString18import kotlinx.coroutines.currentCoroutineContext19import kotlinx.coroutines.ensureActive20import kotlinx.serialization.Serializable21import kotlinx.serialization.json.jsonObject22import kotlinx.serialization.json.jsonPrimitive23import kotlin.random.Random2425/** Password and browser login for [HubSyncService]; owns the pending browser attempts. */26internal class HubLogin(27 private val database: YokanDatabase,28 private val http: HttpService,29 private val leases: SyncAccountLeases,30) {31 private val json = SyncPaths.json32 private val browserAttemptLock = PlatformLock()33 private val browserAttempts = mutableMapOf<Long, PendingBrowserAttempt>()3435 suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult {36 invalidate(syncId)37 val capturedPreference = preference(syncId)38 if ((capturedPreference?.serverProvider ?: SyncServerProvider.YokanHub) != SyncServerProvider.YokanHub) return SyncLoginResult(false, "Yokan Hub is not the selected sync provider.")39 val base = normalizeHubServer(server) ?: return SyncLoginResult(false, "Server URL is required.")40 unsupportedHub(base)?.let { return it }41 val device = capturedPreference?.deviceId ?: newDeviceId()42 val response = catchingNonCancellation {43 http.request(44 HttpRequest(45 url = "$base/api/v1/login",46 method = "POST",47 headers = mapOf("Content-Type" to "application/json", "X-Device" to device),48 body = json.encodeToString(LoginReq.serializer(), LoginReq(email.trim(), password)),49 ),50 )51 }.getOrElse { return SyncLoginResult(false, it.message ?: "Login failed") }52 when (response.statusCode) {53 401 -> return SyncLoginResult(false, "Wrong email or password.")54 403 -> return SyncLoginResult(false, errorOf(response) ?: "Account disabled.")55 503 -> return SyncLoginResult(false, "The hub is in maintenance mode. Try again later.")56 !in 200..299 -> return SyncLoginResult(false, "Hub returned HTTP ${response.statusCode}")57 }58 val token = runCatching { json.decodeFromString(TokenResp.serializer(), response.body).token }.getOrNull()59 ?: return SyncLoginResult(false, "Hub response did not include a token.")60 browserAttemptLock.withLock { browserAttempts.remove(syncId) }61 return saveLogin(syncId, capturedPreference, base, email.trim(), token, device)62 }6364 @OptIn(DelicateCryptographyApi::class)65 fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? {66 val base = normalizeHubServer(server) ?: return null67 val parsedBase = runCatching { Url(base) }.getOrNull() ?: return null68 if (parsedBase.protocol.name !in setOf("http", "https") || parsedBase.host.isBlank() ||69 parsedBase.user != null ||70 base.contains('?') || base.contains('#')71 ) return null72 val capturedPreference = preference(syncId)73 if ((capturedPreference?.serverProvider ?: SyncServerProvider.YokanHub) != SyncServerProvider.YokanHub) return null74 val device = capturedPreference?.deviceId ?: newDeviceId()75 val state = CryptographyRandom.Default.nextBytes(32).joinToString("") { byte ->76 val value = byte.toInt() and 0xff77 "0123456789abcdef"[value ushr 4].toString() + "0123456789abcdef"[value and 0x0f]78 }79 val url = URLBuilder("$base/login/").apply {80 parameters.append("app", "yokan")81 parameters.append("device", device)82 parameters.append("state", state)83 }.build().toString()84 val attempt = BrowserLoginAttempt(syncId, base, url, device, state)85 browserAttemptLock.withLock { browserAttempts[syncId] = PendingBrowserAttempt(attempt, capturedPreference) }86 return attempt87 }8889 suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? {90 if (loadedUrl.length > MAX_BROWSER_CALLBACK_LENGTH || loadedUrl.any(Char::isISOControl)) return null91 val callback = runCatching { Url(loadedUrl) }.getOrNull() ?: return null92 val configured = runCatching { Url(attempt.server) }.getOrNull() ?: return null93 val callbackPath = rawPath(attempt.server)?.trimEnd('/') + "/login/done"94 val loadedPath = rawPath(loadedUrl.substringBefore('#'))95 if (!sameOrigin(configured, callback) || loadedPath !in setOf(callbackPath, "$callbackPath/") || callback.user != null ||96 loadedUrl.substringBefore('#').contains('?')97 ) return null98 val handoff = parseQueryString(loadedUrl.substringAfter('#', ""))99 if (handoff.entries().any { (name, values) -> name.any(Char::isISOControl) || values.any { value -> value.any(Char::isISOControl) } }) {100 return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE)101 }102 fun one(name: String, maxLength: Int): String? = handoff.getAll(name)?.singleOrNull()103 ?.takeIf { it.isNotBlank() && it.length <= maxLength && it.none(Char::isISOControl) }104 val state = one("state", MAX_STATE_LENGTH)105 ?: return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE)106 val token = one("token", MAX_TOKEN_LENGTH)107 ?: return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE)108 val device = one("device", MAX_DEVICE_LENGTH)109 ?.takeIf { it.all { char -> char.isLetterOrDigit() || char == '-' || char == '_' } }110 ?: return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE)111 val emailValues = handoff.getAll("email")112 if (emailValues != null && (emailValues.size != 1 || emailValues.single().length > MAX_EMAIL_LENGTH)) {113 return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE)114 }115 val email = emailValues?.singleOrNull().orEmpty().trim()116 val pending = browserAttemptLock.withLock {117 browserAttempts[attempt.syncId]?.takeIf { it.attempt === attempt && !it.completing }?.also { it.completing = true }118 } ?: return null119 if (state != attempt.state || device != attempt.device) {120 browserAttemptLock.withLock {121 if (browserAttempts[attempt.syncId] === pending) pending.completing = false122 }123 return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE)124 }125 unsupportedHub(attempt.server)?.let { error ->126 browserAttemptLock.withLock {127 if (browserAttempts[attempt.syncId] === pending) pending.completing = false128 }129 return error130 }131 val completionContext = currentCoroutineContext()132 completionContext.ensureActive()133 val stillPending = browserAttemptLock.withLock {134 browserAttempts[attempt.syncId] === pending && pending.attempt === attempt && pending.completing135 }136 if (!stillPending) return null137 completionContext.ensureActive()138 val result = saveLogin(139 attempt.syncId, pending.capturedPreference, attempt.server, email, token, device,140 ) {141 browserAttemptLock.withLock { browserAttempts[attempt.syncId] === pending && pending.completing }142 }143 browserAttemptLock.withLock {144 if (browserAttempts[attempt.syncId] === pending) {145 if (result.success) browserAttempts.remove(attempt.syncId) else pending.completing = false146 }147 }148 return result149 }150151 fun cancelBrowserLogin(attempt: BrowserLoginAttempt) {152 browserAttemptLock.withLock {153 if (browserAttempts[attempt.syncId]?.attempt === attempt) browserAttempts.remove(attempt.syncId)154 }155 }156157 fun invalidate(syncId: Long) {158 browserAttemptLock.withLock { browserAttempts.remove(syncId) }159 }160161 fun clear() = browserAttemptLock.withLock { browserAttempts.clear() }162163 private fun preference(syncId: Long): DbSyncPreference? =164 database.syncPreferences().firstOrNull { it.syncId == syncId }165166 private fun sameOrigin(first: Url, second: Url): Boolean =167 first.protocol.name.equals(second.protocol.name, ignoreCase = true) &&168 first.host.equals(second.host, ignoreCase = true) && first.port == second.port169170 private fun rawPath(url: String): String? {171 val schemeEnd = url.indexOf("://")172 if (schemeEnd < 0) return null173 val pathStart = url.indexOf('/', schemeEnd + 3)174 return if (pathStart < 0) "" else url.substring(pathStart).substringBefore('?').substringBefore('#')175 }176177 private class PendingBrowserAttempt(val attempt: BrowserLoginAttempt, val capturedPreference: DbSyncPreference?, var completing: Boolean = false)178179 /** Null when [base] is a hub speaking [HubSyncService.PROTOCOL_VERSION]; otherwise the failure to show. */180 private suspend fun unsupportedHub(base: String): SyncLoginResult? {181 val version = catchingNonCancellation { http.request(HttpRequest(url = "$base/api/version")) }182 .getOrElse { return SyncLoginResult(false, it.message ?: "Hub is unreachable.") }183 val supported = runCatching { json.decodeFromString(VersionResp.serializer(), version.body).supported }.getOrNull()184 if (version.statusCode !in 200..299 || supported == null || HubSyncService.PROTOCOL_VERSION !in supported) {185 return SyncLoginResult(false, "$base is not a yokan-hub speaking sync protocol v${HubSyncService.PROTOCOL_VERSION}. Check the URL or update the hub.")186 }187 return null188 }189190 private suspend fun saveLogin(191 syncId: Long,192 captured: DbSyncPreference?,193 base: String,194 email: String,195 token: String,196 device: String,197 extraGuard: () -> Boolean = { true },198 ): SyncLoginResult {199 currentCoroutineContext().ensureActive()200 val failure = leases.commitClaimed(captured, DbSyncPreference(server = base, email = email, authToken = token)) {201 database.upsertSyncPreferenceIf(202 syncId = syncId,203 accepts = { current ->204 val unchanged = if (captured == null) current == null else current != null &&205 current.serverProvider == captured.serverProvider && current.server == captured.server &&206 current.email == captured.email && current.authToken == captured.authToken && current.deviceId == captured.deviceId207 unchanged && (current?.serverProvider ?: SyncServerProvider.YokanHub) == SyncServerProvider.YokanHub && extraGuard()208 },209 transform = { current ->210 (current ?: DbSyncPreference(syncId = syncId)).copy(211 server = base,212 email = email,213 authToken = token,214 syncOn = true,215 serverProvider = SyncServerProvider.YokanHub,216 hubHead = 0,217 hubEpoch = 0,218 hubRecoveryPending = false,219 deviceId = device,220 )221 },222 )223 }224 if (failure != null) return SyncLoginResult(false, failure)225 return SyncLoginResult(true, "Logged in to $base")226 }227228 private fun errorOf(response: HttpResponse): String? =229 runCatching { json.parseToJsonElement(response.body).jsonObject["error"]?.jsonPrimitive?.content }.getOrNull()230231 private fun newDeviceId(): String = buildString(32) {232 repeat(16) { append(Random.nextInt(256).toString(16).padStart(2, '0')) }233 }234235 @Serializable236 private data class LoginReq(val email: String, val password: String)237238 @Serializable239 private data class TokenResp(val token: String)240241 @Serializable242 private data class VersionResp(val supported: List<String> = emptyList())243244 private companion object {245 const val MAX_BROWSER_CALLBACK_LENGTH = 16_384246 const val MAX_STATE_LENGTH = 256247 const val MAX_TOKEN_LENGTH = 4_096248 const val MAX_DEVICE_LENGTH = 64249 const val MAX_EMAIL_LENGTH = 320250 const val BROWSER_LOGIN_PROTOCOL_MESSAGE = "The hub did not securely hand over a session. Update the hub or use email/password sign-in."251 }252}253