|
| 1 | +package pl.syntaxdevteam.syntaxlauncher.core.account |
| 2 | + |
| 3 | +import io.ktor.client.HttpClient |
| 4 | +import io.ktor.client.plugins.ResponseException |
| 5 | +import io.ktor.client.request.post |
| 6 | +import io.ktor.client.request.setBody |
| 7 | +import io.ktor.client.statement.bodyAsText |
| 8 | +import io.ktor.http.ContentType |
| 9 | +import io.ktor.http.contentType |
| 10 | +import java.net.URLEncoder |
| 11 | +import java.nio.charset.StandardCharsets |
| 12 | +import java.security.MessageDigest |
| 13 | +import java.security.SecureRandom |
| 14 | +import java.util.Base64 |
| 15 | +import java.util.UUID |
| 16 | +import kotlinx.coroutines.CancellationException |
| 17 | +import kotlinx.serialization.SerialName |
| 18 | +import kotlinx.serialization.Serializable |
| 19 | +import kotlinx.serialization.json.Json |
| 20 | + |
| 21 | +/** Fresh state and PKCE verifier for a single native-browser authorization request. */ |
| 22 | +class MicrosoftOAuthRequest( |
| 23 | + val url: String, val redirectUri: String, val state: String, val codeVerifier: String, |
| 24 | +) { |
| 25 | + override fun toString() = "MicrosoftOAuthRequest([REDACTED])" |
| 26 | +} |
| 27 | + |
| 28 | +/** Tokens must never be printed or persisted without an OS-backed secrets vault. */ |
| 29 | +class MicrosoftOAuthTokens(val accessToken: String, val refreshToken: String?) { |
| 30 | + override fun toString() = "MicrosoftOAuthTokens([REDACTED])" |
| 31 | +} |
| 32 | + |
| 33 | +@Serializable private data class OAuthResponse( |
| 34 | + @SerialName("access_token") val access: String, |
| 35 | + @SerialName("refresh_token") val refresh: String? = null, |
| 36 | +) |
| 37 | + |
| 38 | +class MicrosoftOAuth(private val client: HttpClient, val applicationId: String) { |
| 39 | + private val random = SecureRandom() |
| 40 | + private val json = Json { ignoreUnknownKeys = true } |
| 41 | + init { require(runCatching { UUID.fromString(applicationId) }.isSuccess) { |
| 42 | + "Provide your own Microsoft native public-client application ID." |
| 43 | + } } |
| 44 | + |
| 45 | + fun begin(redirectUri: String): MicrosoftOAuthRequest { |
| 46 | + require(Regex("http://localhost:[0-9]{1,5}/callback").matches(redirectUri)) { |
| 47 | + "Only an ephemeral localhost callback is accepted." |
| 48 | + } |
| 49 | + val verifier = nonce() |
| 50 | + val state = nonce() |
| 51 | + val challenge = Base64.getUrlEncoder().withoutPadding().encodeToString( |
| 52 | + MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray(StandardCharsets.US_ASCII))) |
| 53 | + val data = linkedMapOf( |
| 54 | + "client_id" to applicationId, "response_type" to "code", |
| 55 | + "redirect_uri" to redirectUri, "response_mode" to "query", |
| 56 | + "scope" to "XboxLive.signin offline_access", |
| 57 | + "code_challenge_method" to "S256", "code_challenge" to challenge, "state" to state, |
| 58 | + ) |
| 59 | + val query = data.entries.joinToString("&") { enc(it.key) + "=" + enc(it.value) } |
| 60 | + return MicrosoftOAuthRequest( |
| 61 | + "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?" + query, |
| 62 | + redirectUri, state, verifier, |
| 63 | + ) |
| 64 | + } |
| 65 | + |
| 66 | + suspend fun exchange(code: String, request: MicrosoftOAuthRequest): MicrosoftOAuthTokens { |
| 67 | + require(code.isNotBlank()) |
| 68 | + return token(mapOf("grant_type" to "authorization_code", "code" to code, |
| 69 | + "redirect_uri" to request.redirectUri, "code_verifier" to request.codeVerifier)) |
| 70 | + } |
| 71 | + |
| 72 | + suspend fun refresh(refreshToken: String): MicrosoftOAuthTokens { |
| 73 | + require(refreshToken.isNotBlank()) |
| 74 | + return token(mapOf("grant_type" to "refresh_token", "refresh_token" to refreshToken)) |
| 75 | + } |
| 76 | + |
| 77 | + private suspend fun token(fields: Map<String, String>): MicrosoftOAuthTokens { |
| 78 | + val values = linkedMapOf( |
| 79 | + "client_id" to applicationId, "scope" to "XboxLive.signin offline_access") |
| 80 | + values.putAll(fields) |
| 81 | + return try { |
| 82 | + val result = client.post("https://login.microsoftonline.com/consumers/oauth2/v2.0/token") { |
| 83 | + contentType(ContentType.Application.FormUrlEncoded) |
| 84 | + setBody(values.entries.joinToString("&") { enc(it.key) + "=" + enc(it.value) }) |
| 85 | + } |
| 86 | + val parsed = json.decodeFromString<OAuthResponse>(result.bodyAsText()) |
| 87 | + MicrosoftOAuthTokens(parsed.access, parsed.refresh) |
| 88 | + } catch (cancelled: CancellationException) { |
| 89 | + throw cancelled |
| 90 | + } catch (_: ResponseException) { |
| 91 | + throw IllegalStateException("Microsoft rejected this authentication request. Sign in again.") |
| 92 | + } catch (_: Exception) { |
| 93 | + throw IllegalStateException("Microsoft authentication failed. Check the connection and app registration.") |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + private fun nonce(): String = ByteArray(32).also(random::nextBytes).let { |
| 98 | + Base64.getUrlEncoder().withoutPadding().encodeToString(it) |
| 99 | + } |
| 100 | + private fun enc(s: String) = URLEncoder.encode(s, StandardCharsets.UTF_8) |
| 101 | +} |
0 commit comments