diff --git a/src/main/kotlin/org/polyfrost/polyplus/client/network/http/PolyAuthorization.kt b/src/main/kotlin/org/polyfrost/polyplus/client/network/http/PolyAuthorization.kt index 5ad0a847..3bedc49c 100644 --- a/src/main/kotlin/org/polyfrost/polyplus/client/network/http/PolyAuthorization.kt +++ b/src/main/kotlin/org/polyfrost/polyplus/client/network/http/PolyAuthorization.kt @@ -1,13 +1,16 @@ package org.polyfrost.polyplus.client.network.http import org.polyfrost.polyplus.libs.ktor.client.plugins.ClientRequestException +import org.polyfrost.polyplus.libs.ktor.client.plugins.ServerResponseException import org.polyfrost.polyplus.libs.ktor.client.plugins.expectSuccess +import org.polyfrost.polyplus.libs.ktor.client.request.HttpRequestBuilder import org.polyfrost.polyplus.libs.ktor.client.request.bearerAuth import org.polyfrost.polyplus.libs.ktor.client.request.parameter import org.polyfrost.polyplus.libs.ktor.client.request.post import org.polyfrost.polyplus.libs.ktor.client.request.put import org.polyfrost.polyplus.libs.ktor.client.request.setBody import org.polyfrost.polyplus.libs.ktor.http.ContentType +import org.polyfrost.polyplus.libs.ktor.http.HttpHeaders import org.polyfrost.polyplus.libs.ktor.http.HttpStatusCode import org.polyfrost.polyplus.libs.ktor.http.contentType import com.mojang.authlib.exceptions.InvalidCredentialsException @@ -49,6 +52,8 @@ object PolyAuthorization { private const val REFRESH_MARGIN_MS = 5 * 60 * 1000L private const val LOGIN_GATE_TIMEOUT_MS = 30 * 1000L private const val JOIN_ATTEMPTS = 3 + private const val DEFAULT_RETRY_AFTER_MS = 60 * 1000L + private const val MAX_RETRY_AFTER_MS = 5 * 60 * 1000L private var cachedResponse: AuthResponse? = null private var cachedExpiresAtMs = 0L @@ -60,28 +65,43 @@ object PolyAuthorization { @Volatile private var rejectedAccessToken: String? = null + // OneLauncher hands over its token for the account it launched; used once, through /account/refresh + private var handoff: Pair? = launcherHandoff() + + @Volatile + private var loginPausedUntilMs = 0L + class SessionRejectedException : Exception("Mojang rejected the current session") + class LoginPausedException(retryInMs: Long) : + Exception("PolyPlus sign-in is rate limited; retrying in ${retryInMs / 1000}s") + fun isSessionRejected(): Boolean = rejectedAccessToken.let { it != null && it == localAccessToken() } suspend fun current(): String { requireOnlineServices() val profileId = localProfileId() - val token = LOCK.withLock { - cachedResponse?.token?.takeIf { - System.currentTimeMillis() < cachedExpiresAtMs && cachedProfileId == profileId - } + val job = LOCK.withLock { + val cached = cachedResponse?.token?.takeIf { cachedProfileId == profileId } + val now = System.currentTimeMillis() + if (cached != null && now < cachedExpiresAtMs) return cached + + val fromLauncher = handoff?.takeIf { it.first == profileId }?.second + if (fromLauncher != null) handoff = null + val renewable = cached?.takeIf { now < cachedExpiresAtMs + REFRESH_MARGIN_MS } ?: fromLauncher + currentJob?.takeIf { currentJobProfileId == profileId } ?: startAuthorization(profileId, renewable) } - return token ?: refresh() + return job.await().response.token } + /** A fresh Mojang-backed login, for when the current token was refused. */ suspend fun refresh(): String { requireOnlineServices() val profileId = localProfileId() val job = LOCK.withLock { - currentJob?.takeIf { currentJobProfileId == profileId } ?: startAuthorization(profileId) + currentJob?.takeIf { currentJobProfileId == profileId } ?: startAuthorization(profileId, null) } return job.await().response.token } @@ -114,11 +134,12 @@ object PolyAuthorization { }.getOrNull() // Must be called with LOCK held - private fun startAuthorization(profileId: UUID?): Deferred { + private fun startAuthorization(profileId: UUID?, renewable: String?): Deferred { lateinit var job: Deferred job = PolyPlusClient.SCOPE.async(start = CoroutineStart.LAZY) { try { - authorize().also { + (renewable?.let { renew(it) } ?: authorize()).also { + signedIn(it) LOCK.withLock { cachedResponse = it.response cachedProfileId = it.profileId @@ -142,7 +163,28 @@ object PolyAuthorization { return job } - private suspend fun authorize(): Authorized = withSessionJoinRetry { joined -> + /** Swaps a still-valid token for a new one without asking Mojang; null when the backend wants a real login. */ + private suspend fun renew(token: String): Authorized? { + val profileId = localProfileId() ?: return null + val response = PolyPlusClient.HTTP.post("${PolyPlusConfig.apiUrl}/account/refresh") { + bearerAuth(token) + clientParameters() + } + // 401 once the login is too old; any 4xx (an older backend without /refresh) falls back too + if (response.status.value in 400..499) { + LOGGER.info("PolyPlus token could not be refreshed (HTTP {}); signing in again", response.status.value) + return null + } + return Authorized(profileId, response.bodyOrThrow()) + } + + private suspend fun authorize(): Authorized { + val pausedForMs = loginPausedUntilMs - System.currentTimeMillis() + if (pausedForMs > 0) throw LoginPausedException(pausedForMs) + return joinAndLogin() + } + + private suspend fun joinAndLogin(): Authorized = withSessionJoinRetry { joined -> val user = Minecraft.getInstance().user val profileId = user.profileId val playerName = user.name @@ -195,28 +237,56 @@ object PolyAuthorization { } private suspend fun login(serverId: String, profileId: UUID, playerName: String): Authorized { - val response = PolyPlusClient.HTTP - .post("${PolyPlusConfig.apiUrl}/account/login") { - expectSuccess = true - if (PolyPlusConfig.apiUrl == BackendUrl.LOCAL) { - parameter("player", profileId.toString()) + val response = try { + PolyPlusClient.HTTP + .post("${PolyPlusConfig.apiUrl}/account/login") { + expectSuccess = true + if (PolyPlusConfig.apiUrl == BackendUrl.LOCAL) { + parameter("player", profileId.toString()) + } + parameter("server_id", serverId) + parameter("username", playerName) + clientParameters() } - parameter("server_id", serverId) - parameter("username", playerName) - parameter("client_version", PolyPlusConstants.VERSION) - parameter("minecraft_version", minecraftVersion()) - parameter("loader", LOADER) - parameter("os", System.getProperty("os.name") ?: "unknown") - parameter("os_version", System.getProperty("os.version") ?: "unknown") - parameter("java_version", System.getProperty("java.version") ?: "unknown") + .bodyOrThrow() + } catch (unavailable: ServerResponseException) { + if (unavailable.response.status == HttpStatusCode.ServiceUnavailable) { + pauseLogins(unavailable.response.headers[HttpHeaders.RetryAfter]) } - .bodyOrThrow() + throw unavailable + } LOGGER.info("Successfully authorized as $playerName") + return Authorized(profileId, response) + } + + private fun pauseLogins(retryAfter: String?) { + val pauseMs = retryAfter?.toLongOrNull()?.times(1000)?.coerceIn(0, MAX_RETRY_AFTER_MS) + ?: DEFAULT_RETRY_AFTER_MS + loginPausedUntilMs = System.currentTimeMillis() + pauseMs + LOGGER.warn("PolyPlus sign-in is rate limited by Mojang; waiting {} ms before trying again", pauseMs) + } + + private fun signedIn(authorized: Authorized) { if (modsReported.compareAndSet(false, true)) { - PolyPlusClient.SCOPE.launch(Dispatchers.IO) { reportMods(response.token) } + PolyPlusClient.SCOPE.launch(Dispatchers.IO) { reportMods(authorized.response.token) } } - SkinLibrary.onSignedIn(profileId) - return Authorized(profileId, response) + SkinLibrary.onSignedIn(authorized.profileId) + } + + private fun HttpRequestBuilder.clientParameters() { + parameter("client_version", PolyPlusConstants.VERSION) + parameter("minecraft_version", minecraftVersion()) + parameter("loader", LOADER) + parameter("os", System.getProperty("os.name") ?: "unknown") + parameter("os_version", System.getProperty("os.version") ?: "unknown") + parameter("java_version", System.getProperty("java.version") ?: "unknown") + } + + private fun launcherHandoff(): Pair? { + val token = System.getenv("POLYPLUS_TOKEN")?.takeIf { it.isNotBlank() } ?: return null + val profile = System.getenv("POLYPLUS_TOKEN_PROFILE") + ?.let { runCatching { UUID.fromString(it) }.getOrNull() } ?: return null + return profile to token } @Serializable