package eu.friedcutlet.yokan.services.sync import dev.whyoleg.cryptography.DelicateCryptographyApi import dev.whyoleg.cryptography.random.CryptographyRandom import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.SyncServerProvider import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.database.sync.SyncPaths import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.normalizeHubServer import eu.friedcutlet.yokan.util.PlatformLock import io.ktor.http.URLBuilder import io.ktor.http.Url import io.ktor.http.parseQueryString import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.serialization.Serializable import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlin.random.Random /** Password and browser login for [HubSyncService]; owns the pending browser attempts. */ internal class HubLogin( private val database: YokanDatabase, private val http: HttpService, private val leases: SyncAccountLeases, ) { private val json = SyncPaths.json private val browserAttemptLock = PlatformLock() private val browserAttempts = mutableMapOf() suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult { invalidate(syncId) val capturedPreference = preference(syncId) if ((capturedPreference?.serverProvider ?: SyncServerProvider.YokanHub) != SyncServerProvider.YokanHub) return SyncLoginResult(false, "Yokan Hub is not the selected sync provider.") val base = normalizeHubServer(server) ?: return SyncLoginResult(false, "Server URL is required.") unsupportedHub(base)?.let { return it } val device = capturedPreference?.deviceId ?: newDeviceId() val response = catchingNonCancellation { http.request( HttpRequest( url = "$base/api/v1/login", method = "POST", headers = mapOf("Content-Type" to "application/json", "X-Device" to device), body = json.encodeToString(LoginReq.serializer(), LoginReq(email.trim(), password)), ), ) }.getOrElse { return SyncLoginResult(false, it.message ?: "Login failed") } when (response.statusCode) { 401 -> return SyncLoginResult(false, "Wrong email or password.") 403 -> return SyncLoginResult(false, errorOf(response) ?: "Account disabled.") 503 -> return SyncLoginResult(false, "The hub is in maintenance mode. Try again later.") !in 200..299 -> return SyncLoginResult(false, "Hub returned HTTP ${response.statusCode}") } val token = runCatching { json.decodeFromString(TokenResp.serializer(), response.body).token }.getOrNull() ?: return SyncLoginResult(false, "Hub response did not include a token.") browserAttemptLock.withLock { browserAttempts.remove(syncId) } return saveLogin(syncId, capturedPreference, base, email.trim(), token, device) } @OptIn(DelicateCryptographyApi::class) fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? { val base = normalizeHubServer(server) ?: return null val parsedBase = runCatching { Url(base) }.getOrNull() ?: return null if (parsedBase.protocol.name !in setOf("http", "https") || parsedBase.host.isBlank() || parsedBase.user != null || base.contains('?') || base.contains('#') ) return null val capturedPreference = preference(syncId) if ((capturedPreference?.serverProvider ?: SyncServerProvider.YokanHub) != SyncServerProvider.YokanHub) return null val device = capturedPreference?.deviceId ?: newDeviceId() val state = CryptographyRandom.Default.nextBytes(32).joinToString("") { byte -> val value = byte.toInt() and 0xff "0123456789abcdef"[value ushr 4].toString() + "0123456789abcdef"[value and 0x0f] } val url = URLBuilder("$base/login/").apply { parameters.append("app", "yokan") parameters.append("device", device) parameters.append("state", state) }.build().toString() val attempt = BrowserLoginAttempt(syncId, base, url, device, state) browserAttemptLock.withLock { browserAttempts[syncId] = PendingBrowserAttempt(attempt, capturedPreference) } return attempt } suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? { if (loadedUrl.length > MAX_BROWSER_CALLBACK_LENGTH || loadedUrl.any(Char::isISOControl)) return null val callback = runCatching { Url(loadedUrl) }.getOrNull() ?: return null val configured = runCatching { Url(attempt.server) }.getOrNull() ?: return null val callbackPath = rawPath(attempt.server)?.trimEnd('/') + "/login/done" val loadedPath = rawPath(loadedUrl.substringBefore('#')) if (!sameOrigin(configured, callback) || loadedPath !in setOf(callbackPath, "$callbackPath/") || callback.user != null || loadedUrl.substringBefore('#').contains('?') ) return null val handoff = parseQueryString(loadedUrl.substringAfter('#', "")) if (handoff.entries().any { (name, values) -> name.any(Char::isISOControl) || values.any { value -> value.any(Char::isISOControl) } }) { return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE) } fun one(name: String, maxLength: Int): String? = handoff.getAll(name)?.singleOrNull() ?.takeIf { it.isNotBlank() && it.length <= maxLength && it.none(Char::isISOControl) } val state = one("state", MAX_STATE_LENGTH) ?: return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE) val token = one("token", MAX_TOKEN_LENGTH) ?: return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE) val device = one("device", MAX_DEVICE_LENGTH) ?.takeIf { it.all { char -> char.isLetterOrDigit() || char == '-' || char == '_' } } ?: return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE) val emailValues = handoff.getAll("email") if (emailValues != null && (emailValues.size != 1 || emailValues.single().length > MAX_EMAIL_LENGTH)) { return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE) } val email = emailValues?.singleOrNull().orEmpty().trim() val pending = browserAttemptLock.withLock { browserAttempts[attempt.syncId]?.takeIf { it.attempt === attempt && !it.completing }?.also { it.completing = true } } ?: return null if (state != attempt.state || device != attempt.device) { browserAttemptLock.withLock { if (browserAttempts[attempt.syncId] === pending) pending.completing = false } return SyncLoginResult(false, BROWSER_LOGIN_PROTOCOL_MESSAGE) } unsupportedHub(attempt.server)?.let { error -> browserAttemptLock.withLock { if (browserAttempts[attempt.syncId] === pending) pending.completing = false } return error } val completionContext = currentCoroutineContext() completionContext.ensureActive() val stillPending = browserAttemptLock.withLock { browserAttempts[attempt.syncId] === pending && pending.attempt === attempt && pending.completing } if (!stillPending) return null completionContext.ensureActive() val result = saveLogin( attempt.syncId, pending.capturedPreference, attempt.server, email, token, device, ) { browserAttemptLock.withLock { browserAttempts[attempt.syncId] === pending && pending.completing } } browserAttemptLock.withLock { if (browserAttempts[attempt.syncId] === pending) { if (result.success) browserAttempts.remove(attempt.syncId) else pending.completing = false } } return result } fun cancelBrowserLogin(attempt: BrowserLoginAttempt) { browserAttemptLock.withLock { if (browserAttempts[attempt.syncId]?.attempt === attempt) browserAttempts.remove(attempt.syncId) } } fun invalidate(syncId: Long) { browserAttemptLock.withLock { browserAttempts.remove(syncId) } } fun clear() = browserAttemptLock.withLock { browserAttempts.clear() } private fun preference(syncId: Long): DbSyncPreference? = database.syncPreferences().firstOrNull { it.syncId == syncId } private fun sameOrigin(first: Url, second: Url): Boolean = first.protocol.name.equals(second.protocol.name, ignoreCase = true) && first.host.equals(second.host, ignoreCase = true) && first.port == second.port private fun rawPath(url: String): String? { val schemeEnd = url.indexOf("://") if (schemeEnd < 0) return null val pathStart = url.indexOf('/', schemeEnd + 3) return if (pathStart < 0) "" else url.substring(pathStart).substringBefore('?').substringBefore('#') } private class PendingBrowserAttempt(val attempt: BrowserLoginAttempt, val capturedPreference: DbSyncPreference?, var completing: Boolean = false) /** Null when [base] is a hub speaking [HubSyncService.PROTOCOL_VERSION]; otherwise the failure to show. */ private suspend fun unsupportedHub(base: String): SyncLoginResult? { val version = catchingNonCancellation { http.request(HttpRequest(url = "$base/api/version")) } .getOrElse { return SyncLoginResult(false, it.message ?: "Hub is unreachable.") } val supported = runCatching { json.decodeFromString(VersionResp.serializer(), version.body).supported }.getOrNull() if (version.statusCode !in 200..299 || supported == null || HubSyncService.PROTOCOL_VERSION !in supported) { return SyncLoginResult(false, "$base is not a yokan-hub speaking sync protocol v${HubSyncService.PROTOCOL_VERSION}. Check the URL or update the hub.") } return null } private suspend fun saveLogin( syncId: Long, captured: DbSyncPreference?, base: String, email: String, token: String, device: String, extraGuard: () -> Boolean = { true }, ): SyncLoginResult { currentCoroutineContext().ensureActive() val failure = leases.commitClaimed(captured, DbSyncPreference(server = base, email = email, authToken = token)) { database.upsertSyncPreferenceIf( syncId = syncId, accepts = { current -> val unchanged = if (captured == null) current == null else current != null && current.serverProvider == captured.serverProvider && current.server == captured.server && current.email == captured.email && current.authToken == captured.authToken && current.deviceId == captured.deviceId unchanged && (current?.serverProvider ?: SyncServerProvider.YokanHub) == SyncServerProvider.YokanHub && extraGuard() }, transform = { current -> (current ?: DbSyncPreference(syncId = syncId)).copy( server = base, email = email, authToken = token, syncOn = true, serverProvider = SyncServerProvider.YokanHub, hubHead = 0, hubEpoch = 0, hubRecoveryPending = false, deviceId = device, ) }, ) } if (failure != null) return SyncLoginResult(false, failure) return SyncLoginResult(true, "Logged in to $base") } private fun errorOf(response: HttpResponse): String? = runCatching { json.parseToJsonElement(response.body).jsonObject["error"]?.jsonPrimitive?.content }.getOrNull() private fun newDeviceId(): String = buildString(32) { repeat(16) { append(Random.nextInt(256).toString(16).padStart(2, '0')) } } @Serializable private data class LoginReq(val email: String, val password: String) @Serializable private data class TokenResp(val token: String) @Serializable private data class VersionResp(val supported: List = emptyList()) private companion object { const val MAX_BROWSER_CALLBACK_LENGTH = 16_384 const val MAX_STATE_LENGTH = 256 const val MAX_TOKEN_LENGTH = 4_096 const val MAX_DEVICE_LENGTH = 64 const val MAX_EMAIL_LENGTH = 320 const val BROWSER_LOGIN_PROTOCOL_MESSAGE = "The hub did not securely hand over a session. Update the hub or use email/password sign-in." } }