Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Spotify Connect login on Sonos (tokenType authorization_code): once the speaker has loaded, a code minted for its client id by a token exchange at accounts.spotify.com is sent in addUser with its own fields and retries, the subject token tried in turn (the way that worked last, the silent ones, then Spotify's consent page for its desktop client over the device picker, its refresh token sealed with the Keystore and wiped at sign-out), each step logged by name and HTTP status without a token, and a grouped speaker or a refused login said plainly
kota-zof815e6cb2c8f
diff --git a/base/app/src/main/java/com/music/spotui/connect/CodeExchange.kt b/base/app/src/main/java/com/music/spotui/connect/CodeExchange.ktnew file mode 100644index 00000000..b8328b5c--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/connect/CodeExchange.kt@@ -0,0 +1,114 @@+package com.music.spotui.connect++import org.json.JSONObject+import java.net.URI+import java.net.URLDecoder+import java.security.MessageDigest+import java.security.SecureRandom++/**+ * The code a device announcing `authorization_code` (Sonos) takes in its addUser blob: Spotify mints+ * it in a token exchange (RFC 8693) at accounts.spotify.com, from an access token of the account+ * (the subject) for the device's client id (the audience). It lives about 600 s and the device+ * redeems it itself. The one setup reported working (SpotifyPlus, Spotify's desktop app traced) uses+ * a token of Spotify's desktop client as the subject, got by PKCE; the other subjects [ConnectCode]+ * tries first cost one request each. Pure functions: the calls are in [ConnectCode].+ */+object CodeExchange {+ const val TOKEN_URL = "https://accounts.spotify.com/api/token"+ const val AUTHORIZE_URL = "https://accounts.spotify.com/authorize"+ /** Spotify's desktop app, the only client the exchange is known to accept. */+ const val DESKTOP_CLIENT_ID = "65b708073fc0480ea92a077233ca87bd"+ /** Sonos's Spotify app id: the audience when a Sonos does not say its own client id. */+ const val SONOS_CLIENT_ID = "9b377073ea334637b1406f329ce005de"+ /** The redirect registered for the desktop client: nothing listens there, the page is stopped on it. */+ const val DESKTOP_REDIRECT = "http://127.0.0.1:4381/login"+ const val DESKTOP_USER_AGENT = "Spotify/124300420 Win32_x86_64/0 (PC desktop)"+ const val CODE_TYPE = "urn:spotify:params:oauth:authorization_code"+ private const val ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"++ fun audience(info: ZeroconfInfo): String = info.clientId.ifBlank { SONOS_CLIENT_ID }++ /** The exchange of [subjectToken] (a token of [clientId]) for a code [audience] takes. */+ fun exchangeForm(subjectToken: String, audience: String, clientId: String): String = Zeroconf.form(+ "grant_type" to "urn:ietf:params:oauth:grant-type:token-exchange",+ "subject_token" to subjectToken,+ "subject_token_type" to ACCESS_TOKEN_TYPE,+ "requested_token_type" to CODE_TYPE,+ "resource" to "urn:spotify:resources:connect",+ "scope" to "streaming",+ "audience" to audience,+ "client_id" to clientId,+ )++ /** A new desktop token from the refresh token kept since the consent. */+ fun refreshForm(refreshToken: String): String = Zeroconf.form(+ "grant_type" to "refresh_token", "refresh_token" to refreshToken, "client_id" to DESKTOP_CLIENT_ID,+ )++ /** The desktop token for the code the consent page ended on. */+ fun consentForm(code: String, verifier: String): String = Zeroconf.form(+ "grant_type" to "authorization_code", "code" to code, "redirect_uri" to DESKTOP_REDIRECT,+ "client_id" to DESKTOP_CLIENT_ID, "code_verifier" to verifier,+ )++ /** The consent page: Spotify asks the user once to let the desktop client stream (PKCE, S256). */+ fun authorizeUrl(challenge: String, state: String): String = "$AUTHORIZE_URL?" + Zeroconf.form(+ "client_id" to DESKTOP_CLIENT_ID, "response_type" to "code", "redirect_uri" to DESKTOP_REDIRECT,+ "code_challenge_method" to "S256", "code_challenge" to challenge, "scope" to "streaming", "state" to state,+ )++ /** A PKCE verifier (64 URL-safe characters) or a state. */+ fun verifier(random: SecureRandom = SecureRandom()): String =+ java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(ByteArray(48).also { random.nextBytes(it) })++ fun challenge(verifier: String): String =+ java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray(Charsets.US_ASCII)))++ /** The query of [url] when it is the desktop redirect (the consent's end), else null. */+ fun redirected(url: String): Map<String, String>? {+ val u = runCatching { URI(url) }.getOrNull() ?: return null+ if (u.scheme != "http" || u.host != "127.0.0.1" || u.port != 4381 || u.path != "/login") return null+ return u.rawQuery.orEmpty().split('&').filter { it.isNotEmpty() }.associate {+ URLDecoder.decode(it.substringBefore('='), "UTF-8") to URLDecoder.decode(it.substringAfter('=', ""), "UTF-8")+ }+ }++ /** 32 hex characters, the login id Spotify's desktop app sends a Sonos (a variant tried last). */+ fun randomLoginId(random: SecureRandom = SecureRandom()): String =+ ByteArray(16).also { random.nextBytes(it) }.joinToString("") { "%02x".format(it) }++ /** An answer of accounts.spotify.com/api/token. The tokens stay in memory, never in a log line. */+ class Answer(+ val status: Int,+ val accessToken: String?,+ val refreshToken: String?,+ val issuedType: String,+ val expiresIn: Int,+ val error: String,+ val errorDescription: String,+ ) {+ /** A code a device takes: an answer that says it issued anything else is not one. */+ val isCode: Boolean get() = status == 200 && !accessToken.isNullOrBlank() && (issuedType.isBlank() || issuedType == CODE_TYPE)+ val isToken: Boolean get() = status == 200 && !accessToken.isNullOrBlank()++ /** For the log: the status, the error or what was issued, never a token. */+ val summary: String get() = if (isToken)+ "HTTP $status issued=${issuedType.substringAfterLast(':').ifBlank { "?" }} expires=${expiresIn}s len=${accessToken.orEmpty().length}" ++ if (refreshToken.isNullOrBlank()) "" else " +refresh"+ else "HTTP $status ${error.ifBlank { "-" }} ${errorDescription.take(80)}".trimEnd()+ }++ fun parse(status: Int, body: String): Answer {+ val j = runCatching { JSONObject(body) }.getOrNull() ?: JSONObject()+ return Answer(+ status = status,+ accessToken = j.optString("access_token").ifBlank { null },+ refreshToken = j.optString("refresh_token").ifBlank { null },+ issuedType = j.optString("issued_token_type"),+ expiresIn = j.optInt("expires_in", 0),+ error = j.optString("error"),+ errorDescription = j.optString("error_description"),+ )+ }+}diff --git a/base/app/src/main/java/com/music/spotui/connect/ConnectCode.kt b/base/app/src/main/java/com/music/spotui/connect/ConnectCode.ktnew file mode 100644index 00000000..9d3c8d8b--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/connect/ConnectCode.kt@@ -0,0 +1,204 @@+package com.music.spotui.connect++import android.content.Context+import app.myspoti.host.android.Logbook+import app.myspoti.host.android.MyspotiRuntime+import app.myspoti.spotify.bridge.LogMask+import com.music.spotui.di.Graph+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import okhttp3.MediaType.Companion.toMediaType+import okhttp3.OkHttpClient+import okhttp3.Request+import okhttp3.RequestBody.Companion.toRequestBody+import org.json.JSONObject+import java.io.IOException+import java.util.concurrent.TimeUnit+import javax.crypto.Cipher+import javax.crypto.spec.GCMParameterSpec++/**+ * Gets the code a Sonos takes ([CodeExchange]) by trying the subject tokens in turn: the one that+ * worked last time for the account, then the silent ones (one request each), and last Spotify's+ * consent page for its desktop client, shown in the device picker ([DesktopConsent]) and only after a+ * tap on the speaker. The desktop refresh token got there is kept encrypted with the Keystore key of+ * the downloads ([com.music.spotui.data.offline.OfflineCrypto]) and wiped at sign-out ([clear]).+ *+ * Every call is a plain request to accounts.spotify.com: never the raw path, whose web headers+ * (Bearer, client-token) are not the exchange's. Each step is logged as "lan: sonos: …" by name+ * and HTTP status, never a token, a code or the account.+ */+object ConnectCode {+ enum class Strategy(val label: String) {+ DESKTOP_REFRESH("desktop-refresh"),+ DEVICEAUTH_DESKTOP("deviceauth-desktop"),+ WEB_WEB("web-web"),+ WEB_DESKTOP("web-desktop"),+ DEVICEAUTH_DEVICE("deviceauth-device"),+ DESKTOP_CONSENT("desktop-consent"),+ }++ class Minted(val strategy: Strategy, val code: String)++ /** No code, or the device would not take one: [grouped] when it answered as a grouped speaker. */+ class Failure(message: String, val grouped: Boolean = false) : IOException(message)++ /** An access token to exchange, the client it belongs to and how that client calls. */+ private class Subject(val token: String, val clientId: String, val userAgent: String, val web: Boolean = false)++ private const val PREFS = "lan_connect_code"+ private val http by lazy { OkHttpClient.Builder().callTimeout(15, TimeUnit.SECONDS).followRedirects(false).build() }+ private val FORM = "application/x-www-form-urlencoded".toMediaType()++ /**+ * One login of [info]: the subject tokens got so far stay here (in memory) so a fresh code costs+ * one request. [controllerId] is this phone's id for device-auth, [deviceName] the speaker's name+ * for the consent page.+ */+ class Session(private val info: ZeroconfInfo, private val account: String, private val controllerId: String, private val deviceName: String) {+ private val audience = CodeExchange.audience(info)+ private val order: List<Strategy> = run {+ // The consent's token is kept: the next time it is the refresh that is tried first.+ val cached = cachedStrategy(account)?.let { if (it == Strategy.DESKTOP_CONSENT) Strategy.DESKTOP_REFRESH else it }+ listOfNotNull(cached) + Strategy.entries.filter { it != cached }+ }+ private var at = 0+ private val subjects = HashMap<Strategy, Subject>()++ /** A code from the next way that gives one, or null when none is left. */+ suspend fun next(): Minted? {+ while (at < order.size) {+ val s = order[at++]+ val subject = runCatching { subjects[s] ?: subject(s)?.also { subjects[s] = it } }+ .onFailure { log("code ${s.label}: no subject token (${it.javaClass.simpleName})") }.getOrNull() ?: continue+ exchange(s, subject)?.let { return Minted(s, it) }+ }+ return null+ }++ /** A fresh code the way [m] got its own (a code may be good for one addUser only); null when it fails now. */+ suspend fun again(m: Minted): Minted? = subjects[m.strategy]?.let { s -> exchange(m.strategy, s)?.let { Minted(m.strategy, it) } }++ private suspend fun exchange(s: Strategy, subject: Subject): String? {+ val answer = post(CodeExchange.exchangeForm(subject.token, audience, subject.clientId), subject.userAgent, subject.web)+ log("code ${s.label}: ${LogMask.redact(answer.summary)}")+ return answer.accessToken.takeIf { answer.isCode }+ }++ private suspend fun subject(s: Strategy): Subject? = when (s) {+ Strategy.DESKTOP_REFRESH -> refreshed(account)+ Strategy.DEVICEAUTH_DESKTOP -> deviceAuth("desktop", CodeExchange.DESKTOP_CLIENT_ID, controllerId)?.let { Subject(it, CodeExchange.DESKTOP_CLIENT_ID, CodeExchange.DESKTOP_USER_AGENT) }+ Strategy.WEB_WEB -> webToken()?.let { (token, client) -> Subject(token, client, MyspotiRuntime.host.userAgent, web = true) }+ Strategy.WEB_DESKTOP -> webToken()?.let { (token, _) -> Subject(token, CodeExchange.DESKTOP_CLIENT_ID, CodeExchange.DESKTOP_USER_AGENT) }+ Strategy.DEVICEAUTH_DEVICE -> deviceAuth("device", info.clientId, info.deviceId)?.let { Subject(it, CodeExchange.DESKTOP_CLIENT_ID, CodeExchange.DESKTOP_USER_AGENT) }+ Strategy.DESKTOP_CONSENT -> consented(account, deviceName)+ }+ }++ /** The way that logged a device in for [account]: tried first next time. */+ fun remember(account: String, strategy: Strategy) {+ prefs().edit().putString("strategy:${key(account)}", strategy.name).apply()+ }++ /** Sign-out: the desktop refresh token and the ways remembered go. */+ fun clear(context: Context) {+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().clear().apply()+ }++ private fun cachedStrategy(account: String): Strategy? =+ prefs().getString("strategy:${key(account)}", null)?.let { n -> Strategy.entries.firstOrNull { it.name == n } }++ /** The desktop token from the refresh token kept for [account]; a refused one is dropped. */+ private suspend fun refreshed(account: String): Subject? {+ val refresh = storedRefresh(account) ?: return null+ val answer = post(CodeExchange.refreshForm(refresh), CodeExchange.DESKTOP_USER_AGENT)+ log("desktop refresh: ${LogMask.redact(answer.summary)}")+ if (!answer.isToken) {+ if (answer.status in 400..499) storeRefresh(account, null)+ return null+ }+ answer.refreshToken?.let { storeRefresh(account, it) }+ return Subject(answer.accessToken!!, CodeExchange.DESKTOP_CLIENT_ID, CodeExchange.DESKTOP_USER_AGENT)+ }++ /** Spotify's consent page for its desktop client, then its token; its refresh token is kept. */+ private suspend fun consented(account: String, deviceName: String): Subject? {+ val verifier = CodeExchange.verifier()+ val state = CodeExchange.verifier()+ val url = DesktopConsent.ask(CodeExchange.authorizeUrl(CodeExchange.challenge(verifier), state), deviceName) ?: return null+ val query = CodeExchange.redirected(url) ?: return null+ val code = query["code"]+ if (query["state"] != state || code.isNullOrBlank()) {+ log("consent: ended without a code (${query["error"]?.take(40) ?: if (query["state"] != state) "state differs" else "no code"})")+ return null+ }+ log("consent: code received")+ val answer = post(CodeExchange.consentForm(code, verifier), CodeExchange.DESKTOP_USER_AGENT)+ log("consent token: ${LogMask.redact(answer.summary)}")+ if (!answer.isToken) return null+ answer.refreshToken?.let { storeRefresh(account, it) }+ return Subject(answer.accessToken!!, CodeExchange.DESKTOP_CLIENT_ID, CodeExchange.DESKTOP_USER_AGENT)+ }++ /** A token Spotify's device-auth issues for [clientId], as the accesstoken login gets one (through the account's own path). */+ private suspend fun deviceAuth(which: String, clientId: String, deviceId: String): String? {+ if (clientId.isBlank()) return null+ val auth = MyspotiRuntime.spotify.raw.request("POST", "https://spclient.wg.spotify.com/device-auth/v1/refresh",+ JSONObject().put("clientId", clientId).put("deviceId", deviceId).toString().toByteArray(),+ mapOf("content-type" to "text/plain;charset=UTF-8"))+ log("device-auth $which: HTTP ${auth.status}")+ return if (auth.status == 200) runCatching { JSONObject(auth.body).optString("accessToken").ifBlank { null } }.getOrNull() else null+ }++ /** The Web Player's token and its client id, from the page; null for an anonymous one. */+ private suspend fun webToken(): Pair<String, String>? {+ val t = MyspotiRuntime.spotify.bridge.call("token.get").jsonObject+ if (t["isAnonymous"]?.jsonPrimitive?.contentOrNull == "true") return null+ val token = t["accessToken"]?.jsonPrimitive?.contentOrNull ?: return null+ val client = t["clientId"]?.jsonPrimitive?.contentOrNull ?: return null+ return token to client+ }++ /** A form POST to accounts.spotify.com/api/token with no cookie and no credential header. */+ private suspend fun post(form: String, userAgent: String, web: Boolean = false): CodeExchange.Answer = withContext(Dispatchers.IO) {+ val request = Request.Builder().url(CodeExchange.TOKEN_URL).post(form.toRequestBody(FORM))+ .header("user-agent", userAgent).header("accept", "application/json")+ .apply { if (web) header("origin", "https://open.spotify.com").header("referer", "https://open.spotify.com/") }+ .build()+ runCatching { http.newCall(request).execute().use { r -> CodeExchange.parse(r.code, r.body.string()) } }+ .getOrElse { e -> log("token call failed: ${e.javaClass.simpleName}"); CodeExchange.parse(-1, "") }+ }++ // The refresh token, sealed with the downloads' Keystore key (AES-GCM) and kept for one account only.++ private fun storedRefresh(account: String): String? {+ val p = prefs()+ if (p.getString("refresh_for", null) != key(account)) return null+ val sealed = p.getString("refresh", null) ?: return null+ return runCatching {+ val raw = android.util.Base64.decode(sealed, android.util.Base64.NO_WRAP)+ val c = Cipher.getInstance("AES/GCM/NoPadding")+ c.init(Cipher.DECRYPT_MODE, com.music.spotui.data.offline.OfflineCrypto.key(Graph.app), GCMParameterSpec(128, raw.copyOfRange(0, 12)))+ String(c.doFinal(raw, 12, raw.size - 12), Charsets.UTF_8)+ }.getOrNull()+ }++ private fun storeRefresh(account: String, token: String?) {+ if (token == null) { prefs().edit().remove("refresh").remove("refresh_for").apply(); return }+ runCatching {+ val c = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, com.music.spotui.data.offline.OfflineCrypto.key(Graph.app)) }+ val sealed = c.iv + c.doFinal(token.toByteArray(Charsets.UTF_8))+ prefs().edit().putString("refresh", android.util.Base64.encodeToString(sealed, android.util.Base64.NO_WRAP)).putString("refresh_for", key(account)).apply()+ }.onFailure { log("desktop token not kept: ${it.javaClass.simpleName}") }+ }++ /** The account as stored: a hash, never the name. */+ private fun key(account: String) = Zeroconf.sha1Hex("lan-code:$account").take(16)++ private fun prefs() = Graph.app.getSharedPreferences(PREFS, Context.MODE_PRIVATE)++ fun log(line: String) = Logbook.log("lan: sonos: $line")+}diff --git a/base/app/src/main/java/com/music/spotui/connect/DesktopConsent.kt b/base/app/src/main/java/com/music/spotui/connect/DesktopConsent.ktnew file mode 100644index 00000000..92cee7be--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/connect/DesktopConsent.kt@@ -0,0 +1,175 @@+package com.music.spotui.connect++import android.annotation.SuppressLint+import android.graphics.Bitmap+import android.webkit.WebResourceError+import android.webkit.WebResourceRequest+import android.webkit.WebView+import android.webkit.WebViewClient+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.imePadding+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.statusBarsPadding+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Close+import androidx.compose.material.icons.rounded.Lock+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.key+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.compose.ui.viewinterop.AndroidView+import androidx.compose.ui.window.Dialog+import androidx.compose.ui.window.DialogProperties+import app.myspoti.engine.R+import app.myspoti.host.android.MyspotiRuntime+import com.music.spotui.ui.theme.AppMuted+import com.music.spotui.ui.theme.AppText+import com.music.spotui.ui.theme.tone+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.withTimeoutOrNull++/**+ * Spotify's consent page for its desktop client ([CodeExchange.authorizeUrl]), the last way to a+ * Sonos code: shown full screen over the device picker (both looks share it), in a web view of the+ * default profile, so accounts.spotify.com sees the session the Web Player signed in and the user+ * only allows. Nothing in the page is touched or read but its address: when it goes to the desktop+ * redirect, it closes on that address. Closed, refused, a page that cannot load, or the picker gone:+ * no code.+ */+object DesktopConsent {+ class Open(val url: String, val deviceName: String) {+ val result = CompletableDeferred<String?>()+ }++ val open = MutableStateFlow<Open?>(null)+ /** Pickers on screen to show the page in (changed on the main thread). */+ @Volatile private var hosts = 0+ private const val TIMEOUT_MS = 5 * 60_000L++ /** The address the page ended on once the user allowed, or null. */+ suspend fun ask(url: String, deviceName: String): String? {+ if (hosts == 0) { ConnectCode.log("consent: no device picker on screen"); return null }+ val o = Open(url, deviceName)+ open.value = o+ ConnectCode.log("consent: shown")+ return try {+ withTimeoutOrNull(TIMEOUT_MS) { o.result.await() }.also { if (it == null) ConnectCode.log("consent: cancelled") }+ } finally {+ open.compareAndSet(o, null)+ }+ }++ fun finish(o: Open, url: String?) {+ o.result.complete(url)+ open.compareAndSet(o, null)+ }++ internal fun hosted(on: Boolean) {+ hosts += if (on) 1 else -1+ if (hosts == 0) open.value?.let { finish(it, null) }+ }+}++/** In the device picker: the consent page while one is asked. */+@Composable+fun DesktopConsentHost() {+ DisposableEffect(Unit) {+ DesktopConsent.hosted(true)+ onDispose { DesktopConsent.hosted(false) }+ }+ val o by DesktopConsent.open.collectAsState()+ val current = o ?: return+ key(current) {+ Dialog(+ onDismissRequest = { DesktopConsent.finish(current, null) },+ properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),+ ) { ConsentPage(current) }+ }+}++@Composable+private fun ConsentPage(o: DesktopConsent.Open) {+ var host by remember { mutableStateOf(runCatching { java.net.URI(o.url).host }.getOrNull().orEmpty()) }+ Column(Modifier.fillMaxSize().background(tone(0xFF121212)).statusBarsPadding().navigationBarsPadding().imePadding()) {+ Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {+ IconButton(onClick = { DesktopConsent.finish(o, null) }) {+ Icon(Icons.Rounded.Close, stringResource(R.string.ext_auth_close), tint = AppText)+ }+ Column(Modifier.weight(1f)) {+ Text(o.deviceName, color = AppText, fontSize = 15.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Row(verticalAlignment = Alignment.CenterVertically) {+ Icon(Icons.Rounded.Lock, null, tint = AppMuted, modifier = Modifier.padding(end = 4.dp))+ Text(host, color = AppMuted, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+ }+ Text(stringResource(R.string.lan_sonos_consent, o.deviceName), color = AppMuted, fontSize = 12.sp, modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp))+ AndroidView(+ modifier = Modifier.weight(1f).fillMaxWidth(),+ factory = { ctx -> consentView(ctx, o) { h -> host = h } },+ onRelease = { it.stopLoading(); it.destroy() },+ )+ }+}++@SuppressLint("SetJavaScriptEnabled")+private fun consentView(ctx: android.content.Context, o: DesktopConsent.Open, onHost: (String) -> Unit): WebView {+ // The default profile, on purpose: its cookies are the Web Player's, so the account is signed in already.+ val view = WebView(ctx)+ view.settings.apply {+ javaScriptEnabled = true+ domStorageEnabled = true+ allowFileAccess = false+ allowContentAccess = false+ setGeolocationEnabled(false)+ // The same browser as the Web Player's page, for accounts.spotify.com.+ userAgentString = MyspotiRuntime.host.userAgent+ }+ if (androidx.webkit.WebViewFeature.isFeatureSupported(androidx.webkit.WebViewFeature.REQUESTED_WITH_HEADER_ALLOW_LIST))+ androidx.webkit.WebSettingsCompat.setRequestedWithHeaderOriginAllowList(view.settings, emptySet())++ /** The desktop redirect, reached by a redirect or a link: the page closes on it (nothing listens there). */+ fun reached(url: String): Boolean {+ if (CodeExchange.redirected(url) == null) return false+ ConnectCode.log("consent: redirect reached")+ DesktopConsent.finish(o, url)+ return true+ }++ view.webViewClient = object : WebViewClient() {+ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean =+ reached(request.url.toString()) || request.url.scheme != "https"++ override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {+ if (reached(url)) { view.stopLoading(); return }+ runCatching { java.net.URI(url).host }.getOrNull()?.let(onHost)+ }++ override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {+ if (!request.isForMainFrame || reached(request.url.toString())) return+ ConnectCode.log("consent: page error ${request.url.host} ${error.errorCode}")+ DesktopConsent.finish(o, null)+ }+ }+ view.loadUrl(o.url)+ return view+}diff --git a/base/app/src/main/java/com/music/spotui/connect/LanDeviceRows.kt b/base/app/src/main/java/com/music/spotui/connect/LanDeviceRows.ktindex 4a8372a1..1258f40c 100644--- a/base/app/src/main/java/com/music/spotui/connect/LanDeviceRows.kt+++ b/base/app/src/main/java/com/music/spotui/connect/LanDeviceRows.kt@@ -40,6 +40,8 @@ fun LanDeviceRows() {LanDiscovery.start(context)onDispose { LanDiscovery.stop() }}+ // Spotify's consent page, when a Sonos needs it (asked by the login, over the picker).+ DesktopConsentHost()val listed = MyspotiRuntime.spotify.devices.devices.collectAsState().value.filter { !it.local }val ids = listed.map { it.id }.toSet()val names = listed.map { it.name }.toSet()diff --git a/base/app/src/main/java/com/music/spotui/connect/LanDiscovery.kt b/base/app/src/main/java/com/music/spotui/connect/LanDiscovery.ktindex 576be1d4..f36fd2f7 100644--- a/base/app/src/main/java/com/music/spotui/connect/LanDiscovery.kt+++ b/base/app/src/main/java/com/music/spotui/connect/LanDiscovery.kt@@ -94,7 +94,8 @@ object LanDiscovery {if (info == null) { log("a device on the network did not answer getInfo"); return@launch }// Brand, model and the kind of login only: no name, id or account.log("found ${info.brand.ifBlank { "?" }} ${info.model.ifBlank { "" }} (login ${info.tokenType.ifBlank { "?" }}, zeroconf ${info.version.ifBlank { "?" }}, " +- "${if (info.activeUser.isBlank()) "no user" else "a user"} logged in)")+ "${if (info.activeUser.isBlank()) "no user" else "a user"} logged in, availability ${info.availability.ifBlank { "-" }}, " ++ "key ${if (info.publicKey == Zeroconf.INVALID_KEY) "INVALID" else if (info.publicKey.isBlank()) "none" else "valid"}, spotifyError ${info.spotifyError})")val d = LanDevice(s.serviceName, host, s.port, Zeroconf.path(cpath), info)main.post {val at = devices.indexOfFirst { it.info.deviceId == info.deviceId }diff --git a/base/app/src/main/java/com/music/spotui/connect/LanLogin.kt b/base/app/src/main/java/com/music/spotui/connect/LanLogin.ktindex e472e91d..198ae8d8 100644--- a/base/app/src/main/java/com/music/spotui/connect/LanLogin.kt+++ b/base/app/src/main/java/com/music/spotui/connect/LanLogin.kt@@ -21,7 +21,8 @@ import java.io.IOException* speaker is tapped: Spotify's device-auth issues a token for the device's client id (from the web* token), `addUser` hands it to the device, the device joins the account's Connect devices, and* the song is transferred to it like to any other. Tried for every device that announces its ids- * ([ZeroconfInfo.loginable]), Sonos included; the answer of each is in the log.+ * ([ZeroconfInfo.loginable]); the answer of each is in the log. A device that wants a code (Sonos)+ * gets one minted for it ([ConnectCode]) instead of the token, with its own retries.*/object LanLogin {/** The device being logged in (the picker shows it connecting). Main thread. */@@ -38,7 +39,12 @@ object LanLogin {busy.value = nulldevice.onSuccess { SongPlayer.transferTo(it) }.onFailure {log("failed: ${it.javaClass.simpleName} ${it.message.orEmpty().take(80)}")- android.widget.Toast.makeText(Graph.app, Graph.app.getString(app.myspoti.engine.R.string.lan_failed, d.info.name.ifBlank { d.service }), android.widget.Toast.LENGTH_LONG).show()+ val message = when {+ it is ConnectCode.Failure && it.grouped -> app.myspoti.engine.R.string.lan_sonos_group+ it is ConnectCode.Failure -> app.myspoti.engine.R.string.lan_sonos_refused+ else -> app.myspoti.engine.R.string.lan_failed+ }+ android.widget.Toast.makeText(Graph.app, Graph.app.getString(message, d.info.name.ifBlank { d.service }), android.widget.Toast.LENGTH_LONG).show()}}}@@ -48,25 +54,113 @@ object LanLogin {connectDevice(d)?.let { log("already a Spotify Connect device"); return it }val spotify = MyspotiRuntime.spotifyval user = (spotify.raw.service("UserAPI", "getUser") as? JsonObject)?.get("username")?.jsonPrimitive?.contentOrNull.orEmpty()+ val me = android.os.Build.MODEL.ifBlank { "Android" }+ if (d.info.wantsCode) return loginWithCode(d, user, me)val auth = spotify.raw.request("POST", "https://spclient.wg.spotify.com/device-auth/v1/refresh",JSONObject().put("clientId", d.info.clientId).put("deviceId", d.info.deviceId).toString().toByteArray(),mapOf("content-type" to "text/plain;charset=UTF-8"))// The token is never logged.val token = (if (auth.status == 200) runCatching { JSONObject(auth.body).optString("accessToken").ifBlank { null } }.getOrNull() else null)?: throw IOException("device-auth ${auth.status}")- val me = android.os.Build.MODEL.ifBlank { "Android" }val request = Zeroconf.addUserRequest(d.host.hostAddress.orEmpty(), d.port, d.cpath, user, token, d.info, me, controllerId(me))val answer = withContext(Dispatchers.IO) { LanDiscovery.call(d.host, d.port, request, 10_000) } ?: throw IOException("no answer to addUser")log("addUser answered ${answer.first}, ${Zeroconf.answerSummary(answer.second)} (device says ${d.info.tokenType.ifBlank { "?" }})")if (!Zeroconf.addUserAccepted(answer.first, answer.second)) throw IOException("addUser refused ${answer.first}")- // It joins the account's devices a moment after (it logs in to Spotify first).- for (k in 0 until 10) {+ return joined(d, 10) ?: throw IOException("the device did not show up")+ }++ /**+ * The login of a device that wants a code (Sonos): once it is ready, a code ([ConnectCode]) in+ * addUser, sent again on 202 (Sonos often says ERROR-LOGIN-FAILED first; a fresh code from the+ * third try on), once more after 203 once it is ready, then with the next way to a code and with+ * the random login id Spotify's desktop app sends. Ends with one line that says which link failed.+ */+ private suspend fun loginWithCode(d: LanDevice, user: String, me: String): SongPlayer.ConnectDevice {+ var info = ready(d, d.info)+ ConnectCode.log("login: audience is ${if (CodeExchange.audience(info) == CodeExchange.SONOS_CLIENT_ID) "the Sonos id" else "the device's own id ${info.clientId.take(8)}"}")+ val session = ConnectCode.Session(info, user, controllerId(me), d.info.name.ifBlank { d.service })+ var minted: ConnectCode.Minted? = null+ var last = "none"+ var listed = false+ try {+ minted = session.next() ?: throw ConnectCode.Failure("no code")+ var loginId = user+ var left = MAX_LOGIN_FAILED+ var keyRetried = false+ var nextTried = false+ var attempt = 0+ while (true) {+ val m = minted!!+ attempt+++ val answer = withContext(Dispatchers.IO) {+ LanDiscovery.call(d.host, d.port, Zeroconf.addUserCodeRequest(d.host.hostAddress.orEmpty(), d.port, d.cpath, user, loginId, m.code, info, me), 10_000)+ }+ last = answer?.let { "HTTP ${it.first}, ${Zeroconf.answerSummary(it.second)}" } ?: "no answer"+ ConnectCode.log("addUser #$attempt (${m.strategy.label}, loginId=${if (loginId == user) "username" else "random"}): $last")+ if (answer == null) throw IOException("no answer to addUser")+ when (Zeroconf.codeAnswer(answer.first, answer.second)) {+ Zeroconf.CodeAnswer.ACCEPTED -> {+ // A Sonos takes longer than a Bose to join: it redeems the code first.+ val device = joined(d, 20) ?: throw IOException("the device did not show up")+ listed = true+ ConnectCode.remember(user, m.strategy)+ return device+ }+ Zeroconf.CodeAnswer.GROUPED -> throw ConnectCode.Failure("grouped speaker?", grouped = true)+ Zeroconf.CodeAnswer.REFUSED -> throw ConnectCode.Failure("addUser refused ${answer.first}")+ Zeroconf.CodeAnswer.INVALID_KEY -> {+ if (keyRetried) throw ConnectCode.Failure("addUser refused: public key")+ keyRetried = true+ info = ready(d, info.copy(availability = "NOT-LOADED"))+ minted = session.again(m) ?: m+ }+ Zeroconf.CodeAnswer.LOGIN_FAILED -> {+ delay(250)+ if (--left > 0) {+ // A code may be good for one try only.+ if (left <= MAX_LOGIN_FAILED - 2) minted = session.again(m) ?: m+ } else {+ val other = if (nextTried) null else session.next()+ nextTried = true+ when {+ other != null -> { minted = other; left = MAX_LOGIN_FAILED }+ loginId == user -> { loginId = CodeExchange.randomLoginId(); left = 1; minted = session.again(m) ?: m }+ else -> throw ConnectCode.Failure("addUser login failed")+ }+ }+ }+ }+ }+ } finally {+ ConnectCode.log("result code=${minted?.strategy?.label ?: "none"} addUser=$last joined=${if (listed) "yes" else "no"}")+ }+ }++ /** [info] once the device's Spotify part is loaded (it answers getInfo again every second, 5 s at most). */+ private suspend fun ready(d: LanDevice, info: ZeroconfInfo): ZeroconfInfo {+ var now = info+ for (k in 1..5) {+ if (!now.starting) return now.also { if (k > 1) ConnectCode.log("loaded after ${k - 1}s") }+ delay(1000)+ now = withContext(Dispatchers.IO) { LanDiscovery.getInfo(d.host, d.port, d.cpath) } ?: now+ }+ if (now.starting) ConnectCode.log("still not loaded after 5s, trying anyway")+ return now+ }++ /** [d] once it joined the account's devices ([tries] × 1.5 s): it logs in to Spotify first. */+ private suspend fun joined(d: LanDevice, tries: Int): SongPlayer.ConnectDevice? {+ for (k in 1..tries) {delay(1500)- connectDevice(d)?.let { log("joined the Spotify Connect devices"); return it }+ connectDevice(d)?.let { log("joined the Spotify Connect devices after ${k * 3 / 2}s"); return it }}- throw IOException("the device did not show up")+ log("not in the device list after ${tries * 3 / 2}s")+ return null}+ /** 202 answers taken before the next way to a code. */+ private const val MAX_LOGIN_FAILED = 5+/** [d] among the account's Connect devices: by the id it announced, else by its name. */private suspend fun connectDevice(d: LanDevice): SongPlayer.ConnectDevice? {val api = MyspotiRuntime.spotify.devicesdiff --git a/base/app/src/main/java/com/music/spotui/connect/Zeroconf.kt b/base/app/src/main/java/com/music/spotui/connect/Zeroconf.ktindex aa96ee71..19b6dc54 100644--- a/base/app/src/main/java/com/music/spotui/connect/Zeroconf.kt+++ b/base/app/src/main/java/com/music/spotui/connect/Zeroconf.kt@@ -16,14 +16,25 @@ data class ZeroconfInfo(val activeUser: String,val brand: String,val model: String,+ /** "NOT-LOADED" while its Spotify part is still starting (Sonos after a wake), else "" or "AVAILABLE". */+ val availability: String = "",+ /** Its Diffie-Hellman key; [Zeroconf.INVALID_KEY] while it is still starting. Not used by either login. */+ val publicKey: String = "",+ /** Spotify's own error code on the device (0: none), for the log. */+ val spotifyError: Int = 0,) {/*** Worth a login attempt: it announced the ids Spotify's device-auth needs. A device that says* "accesstoken" takes the token as it is (Bose, Onkyo, Yamaha, Audio Pro reported); one that- * says "authorization_code" (Sonos, reported once, no source says how its blob is made) is tried- * the same way, and the answer is logged, since nothing here can tell beforehand.+ * says "authorization_code" (Sonos) takes a code Spotify mints for its client id ([CodeExchange]).*/val loginable: Boolean get() = deviceId.isNotBlank() && clientId.isNotBlank()++ /** It wants an authorization code in the blob, not a token. */+ val wantsCode: Boolean get() = tokenType == Zeroconf.AUTHORIZATION_CODE++ /** Still starting: an addUser now is answered 203 (invalid public key). */+ val starting: Boolean get() = availability == "NOT-LOADED" || publicKey == Zeroconf.INVALID_KEY}/**@@ -32,11 +43,16 @@ data class ZeroconfInfo(* `addUser`. Devices whose getInfo says `tokenType=accesstoken` (Bose, Onkyo, Yamaha, Audio Pro* firmware reported) take a token in the blob as it is; the token is the one Spotify's* device-auth issues for the device's client id (the same one the Cast receiver gets), so- * the account's web token never leaves the phone. Sonos announces `authorization_code`. Pure functions: the sockets are in [ZeroconfClient].+ * the account's web token never leaves the phone. Sonos announces `authorization_code`: its blob is+ * a short-lived code from a token exchange at accounts.spotify.com ([CodeExchange]), sent with an+ * empty client key ([addUserCodeRequest]). Pure functions: the sockets are in [LanDiscovery.call].*/object Zeroconf {const val SERVICE_TYPE = "_spotify-connect._tcp"const val ACCESS_TOKEN = "accesstoken"+ const val AUTHORIZATION_CODE = "authorization_code"+ /** The public key of a device whose Spotify part is not loaded yet ("INVALID" in base64). */+ const val INVALID_KEY = "SU5WQUxJRA=="/** The ZeroConf version announced to the device (the one reported working with accesstoken devices). */const val VERSION = "2.7.1"@@ -49,15 +65,36 @@ object Zeroconf {/** The `addUser` POST: the action in the query, the fields in the body (form encoded), as Spotify's partners' firmware reads it. */fun addUserRequest(host: String, port: Int, cpath: String?, userName: String, token: String, info: ZeroconfInfo, controllerName: String, controllerId: String): ByteArray {- val body = form(+ val fields = form("userName" to userName, "blob" to token, "clientKey" to info.clientId, "tokenType" to ACCESS_TOKEN,"loginId" to userName, "deviceName" to controllerName, "deviceId" to controllerId, "version" to VERSION,- ).toByteArray(Charsets.UTF_8)+ )+ return addUserPost(host, port, cpath, fields)+ }++ /**+ * The `addUser` POST of a device that wants a code (Sonos), with the fields Spotify's desktop app+ * sends it: the action in the body too, an empty client key, the code as the blob, the device's+ * own ZeroConf version, and this phone's id as the SHA-1 of its name.+ */+ fun addUserCodeRequest(host: String, port: Int, cpath: String?, userName: String, loginId: String, code: String, info: ZeroconfInfo, controllerName: String): ByteArray {+ val fields = form(+ "action" to "addUser", "version" to info.version.ifBlank { VERSION }, "tokenType" to AUTHORIZATION_CODE, "clientKey" to "",+ "userName" to userName, "loginId" to loginId, "blob" to code, "deviceName" to controllerName, "deviceId" to sha1Hex(controllerName),+ )+ return addUserPost(host, port, cpath, fields)+ }++ private fun addUserPost(host: String, port: Int, cpath: String?, form: String): ByteArray {+ val body = form.toByteArray(Charsets.UTF_8)val head = "POST ${path(cpath)}?action=addUser HTTP/1.1\r\nHost: $host:$port\r\nContent-Type: application/x-www-form-urlencoded\r\n" +"Content-Length: ${body.size}\r\nAccept: */*\r\nConnection: close\r\n\r\n"return head.toByteArray(Charsets.UTF_8) + body}+ fun sha1Hex(text: String): String =+ java.security.MessageDigest.getInstance("SHA-1").digest(text.toByteArray(Charsets.UTF_8)).joinToString("") { "%02x".format(it) }+fun form(vararg fields: Pair<String, String>): String =fields.joinToString("&") { (k, v) -> URLEncoder.encode(k, "UTF-8") + "=" + URLEncoder.encode(v, "UTF-8") }@@ -75,12 +112,44 @@ object Zeroconf {activeUser = j.optString("activeUser"),brand = j.optString("brandDisplayName"),model = j.optString("modelDisplayName"),+ availability = j.optString("availability"),+ publicKey = j.optString("publicKey"),+ spotifyError = j.optInt("spotifyError", 0),)}/** The status and its name from an addUser answer, for the log (no token is ever in one). */fun answerSummary(body: String): String =- runCatching { JSONObject(body) }.getOrNull()?.let { "status ${it.optInt("status", -1)} ${it.optString("statusString").take(40)}" } ?: "not JSON"+ runCatching { JSONObject(body) }.getOrNull()?.let { j ->+ "status ${j.optInt("status", -1)} ${j.optString("statusString").take(40)}" ++ j.optInt("spotifyError", 0).let { if (it != 0) " spotifyError $it" else "" }+ } ?: "not JSON len=${body.length}"++ /** What to do after an addUser answer of a device that wants a code. */+ enum class CodeAnswer { ACCEPTED, LOGIN_FAILED, INVALID_KEY, GROUPED, REFUSED }++ /**+ * 101 is accepted, and so is a 200 that is not JSON (Sonos answers some actions with a bare "}"):+ * only the device list tells then. 202 (ERROR-LOGIN-FAILED) is worth a few tries, 203+ * (ERROR-INVALID-PUBLICKEY) one once the device is ready; a speaker grouped under another+ * answers HTTP 500.+ */+ fun codeAnswer(status: Int, body: String): CodeAnswer {+ val j = runCatching { JSONObject(body) }.getOrNull()+ if (j == null) return when (status) {+ 200 -> CodeAnswer.ACCEPTED+ 500 -> CodeAnswer.GROUPED+ else -> CodeAnswer.REFUSED+ }+ val s = j.optString("statusString")+ return when {+ j.optInt("status", -1) == 101 -> CodeAnswer.ACCEPTED+ j.optInt("status", -1) == 202 || s == "ERROR-LOGIN-FAILED" -> CodeAnswer.LOGIN_FAILED+ j.optInt("status", -1) == 203 || s == "ERROR-INVALID-PUBLICKEY" -> CodeAnswer.INVALID_KEY+ status == 500 -> CodeAnswer.GROUPED+ else -> CodeAnswer.REFUSED+ }+ }/** The answer to addUser: accepted (101), already in that state (404 with no body, as Bose does), or refused. */fun addUserAccepted(status: Int, body: String): Boolean {diff --git a/base/app/src/main/java/com/music/spotui/di/SessionActions.kt b/base/app/src/main/java/com/music/spotui/di/SessionActions.ktindex 81f93fa0..13939c77 100644--- a/base/app/src/main/java/com/music/spotui/di/SessionActions.kt+++ b/base/app/src/main/java/com/music/spotui/di/SessionActions.kt@@ -42,6 +42,8 @@ object SessionActions {// Likes kept for later stay this account's, sent when it signs in again; the next account gets none.com.music.spotui.data.LibraryOutbox.signedOut()SongPlayer.clearSession()+ // The desktop token a Sonos login kept, and the way that logged one in.+ com.music.spotui.connect.ConnectCode.clear(app)// The last track, likes, albums and followed artists of older builds are never read// again: cleared too, so no ids of this account outlive it.listOf("LibraryCache", "RecentItems", "PlaybackState", "LikedSongs",diff --git a/base/app/src/test/java/com/music/spotui/connect/CodeExchangeTest.kt b/base/app/src/test/java/com/music/spotui/connect/CodeExchangeTest.ktnew file mode 100644index 00000000..035cae95--- /dev/null+++ b/base/app/src/test/java/com/music/spotui/connect/CodeExchangeTest.kt@@ -0,0 +1,93 @@+package com.music.spotui.connect++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import java.net.URLDecoder++class CodeExchangeTest {+ private fun fields(form: String) = form.split('&').associate { URLDecoder.decode(it.substringBefore('='), "UTF-8") to URLDecoder.decode(it.substringAfter('='), "UTF-8") }++ @Test fun theExchangeAsksACodeForTheSpeaker() {+ val f = fields(CodeExchange.exchangeForm("tok+/=", "9b37", CodeExchange.DESKTOP_CLIENT_ID))+ assertEquals("urn:ietf:params:oauth:grant-type:token-exchange", f["grant_type"])+ assertEquals("tok+/=", f["subject_token"])+ assertEquals("urn:ietf:params:oauth:token-type:access_token", f["subject_token_type"])+ assertEquals("urn:spotify:params:oauth:authorization_code", f["requested_token_type"])+ assertEquals("urn:spotify:resources:connect", f["resource"])+ assertEquals("streaming", f["scope"])+ assertEquals("9b37", f["audience"])+ assertEquals("65b708073fc0480ea92a077233ca87bd", f["client_id"])+ assertEquals(8, f.size)+ }++ @Test fun theAudienceIsTheDevicesClientElseSonos() {+ val info = Zeroconf.parseInfo("""{"status":101,"deviceID":"d","clientID":"abc","tokenType":"authorization_code"}""")!!+ assertEquals("abc", CodeExchange.audience(info))+ assertEquals(CodeExchange.SONOS_CLIENT_ID, CodeExchange.audience(info.copy(clientId = "")))+ }++ @Test fun refreshAndConsentForms() {+ val r = fields(CodeExchange.refreshForm("r1"))+ assertEquals(mapOf("grant_type" to "refresh_token", "refresh_token" to "r1", "client_id" to CodeExchange.DESKTOP_CLIENT_ID), r)+ val c = fields(CodeExchange.consentForm("c1", "v1"))+ assertEquals("authorization_code", c["grant_type"])+ assertEquals("c1", c["code"])+ assertEquals("http://127.0.0.1:4381/login", c["redirect_uri"])+ assertEquals("v1", c["code_verifier"])+ assertEquals(CodeExchange.DESKTOP_CLIENT_ID, c["client_id"])+ }++ @Test fun theConsentPageIsPkceForTheDesktopClient() {+ val url = CodeExchange.authorizeUrl("ch", "st")+ assertTrue(url.startsWith("https://accounts.spotify.com/authorize?"))+ val q = fields(url.substringAfter('?'))+ assertEquals(CodeExchange.DESKTOP_CLIENT_ID, q["client_id"])+ assertEquals("code", q["response_type"])+ assertEquals("http://127.0.0.1:4381/login", q["redirect_uri"])+ assertEquals("S256", q["code_challenge_method"])+ assertEquals("ch", q["code_challenge"])+ assertEquals("streaming", q["scope"])+ assertEquals("st", q["state"])+ }++ @Test fun pkceChallengeIsSha256InBase64Url() {+ assertEquals("qjrzSW9gMiUgpUvqgEPE4_-8swvyCtfOVvg55o5S_es", CodeExchange.challenge("M25iVXpKU3puUjFaYWg3T1NDTDQtcW1ROUY5YXlwalNoc0hhakxifmZHag"))+ val v = CodeExchange.verifier()+ assertEquals(64, v.length)+ assertTrue(v.all { it.isLetterOrDigit() || it == '-' || it == '_' })+ assertTrue(CodeExchange.randomLoginId().matches(Regex("[0-9a-f]{32}")))+ }++ @Test fun onlyTheDesktopRedirectEndsTheConsent() {+ assertEquals(mapOf("code" to "a b", "state" to "s"), CodeExchange.redirected("http://127.0.0.1:4381/login?code=a%20b&state=s"))+ assertEquals("access_denied", CodeExchange.redirected("http://127.0.0.1:4381/login?error=access_denied&state=s")!!["error"])+ assertNull(CodeExchange.redirected("https://accounts.spotify.com/login?code=x"))+ assertNull(CodeExchange.redirected("http://127.0.0.1:4382/login?code=x"))+ assertNull(CodeExchange.redirected("http://127.0.0.1:4381/other?code=x"))+ }++ @Test fun answersOfTheTokenEndpoint() {+ val ok = CodeExchange.parse(200, """{"access_token":"AQC123","expires_in":600,"issued_token_type":"urn:spotify:params:oauth:authorization_code","scope":"streaming","token_type":"Bearer"}""")+ assertTrue(ok.isCode)+ assertEquals("AQC123", ok.accessToken)+ assertEquals("HTTP 200 issued=authorization_code expires=600s len=6", ok.summary)+ assertFalse(ok.summary.contains("AQC123"))++ val token = CodeExchange.parse(200, """{"access_token":"BQ1","refresh_token":"R","expires_in":3600,"issued_token_type":"urn:ietf:params:oauth:token-type:access_token"}""")+ assertTrue(token.isToken)+ assertFalse(token.isCode)+ assertEquals("R", token.refreshToken)+ assertTrue(token.summary.endsWith("+refresh"))++ val refused = CodeExchange.parse(400, """{"error":"unauthorized_client","error_description":"Client not allowed"}""")+ assertFalse(refused.isCode)+ assertEquals("HTTP 400 unauthorized_client Client not allowed", refused.summary)++ val garbage = CodeExchange.parse(502, "<html>")+ assertFalse(garbage.isToken)+ assertEquals("HTTP 502 -", garbage.summary)+ }+}diff --git a/base/app/src/test/java/com/music/spotui/connect/ZeroconfTest.kt b/base/app/src/test/java/com/music/spotui/connect/ZeroconfTest.ktindex bb5afd59..20daf61b 100644--- a/base/app/src/test/java/com/music/spotui/connect/ZeroconfTest.kt+++ b/base/app/src/test/java/com/music/spotui/connect/ZeroconfTest.kt@@ -49,6 +49,53 @@ class ZeroconfTest {assertEquals("Pixel", fields["deviceName"])}+ @Test fun aCodeDeviceIsToldWhatSonosIsSent() {+ val info = Zeroconf.parseInfo(sonosInfo.replace("2.7.1", "2.9.0"))!!+ assertTrue(info.wantsCode)+ val text = String(Zeroconf.addUserCodeRequest("192.168.1.5", 1400, "/spotifyzc", "me", "me", "AQC+/=", info, "Pixel"), Charsets.UTF_8)+ val (head, body) = text.split("\r\n\r\n")+ assertTrue(head.startsWith("POST /spotifyzc?action=addUser HTTP/1.1"))+ assertTrue(head.contains("Content-Length: ${body.toByteArray().size}"))+ val fields = body.split('&').associate { it.substringBefore('=') to java.net.URLDecoder.decode(it.substringAfter('='), "UTF-8") }+ assertEquals("addUser", fields["action"])+ assertEquals("2.9.0", fields["version"])+ assertEquals("authorization_code", fields["tokenType"])+ assertEquals("", fields["clientKey"])+ assertEquals("me", fields["userName"])+ assertEquals("me", fields["loginId"])+ assertEquals("AQC+/=", fields["blob"])+ assertEquals("Pixel", fields["deviceName"])+ assertEquals("e51f224d70d3df8c10d5e456b6ab98229715fe7e", fields["deviceId"])+ assertEquals("2.7.1", fields(Zeroconf.addUserCodeRequest("h", 1, "/", "u", "u", "c", info.copy(version = ""), "P"))["version"])+ }++ private fun fields(request: ByteArray) = String(request, Charsets.UTF_8).substringAfter("\r\n\r\n").split('&')+ .associate { it.substringBefore('=') to java.net.URLDecoder.decode(it.substringAfter('='), "UTF-8") }++ @Test fun aDeviceStillStartingIsSeen() {+ val i = Zeroconf.parseInfo("""{"status":101,"deviceID":"d","clientID":"c","tokenType":"authorization_code","availability":"NOT-LOADED","publicKey":"SU5WQUxJRA==","spotifyError":0}""")!!+ assertEquals("NOT-LOADED", i.availability)+ assertEquals(Zeroconf.INVALID_KEY, i.publicKey)+ assertTrue(i.starting)+ assertFalse(i.copy(availability = "", publicKey = "abc").starting)+ assertTrue(i.copy(availability = "").starting)+ assertEquals(0, Zeroconf.parseInfo(sonosInfo)!!.spotifyError)+ assertFalse(Zeroconf.parseInfo("""{"status":101,"deviceID":"d","tokenType":"accesstoken"}""")!!.wantsCode)+ }++ @Test fun codeAnswers() {+ assertEquals(Zeroconf.CodeAnswer.ACCEPTED, Zeroconf.codeAnswer(200, """{"status":101,"statusString":"OK"}"""))+ assertEquals(Zeroconf.CodeAnswer.ACCEPTED, Zeroconf.codeAnswer(200, "}"))+ assertEquals(Zeroconf.CodeAnswer.LOGIN_FAILED, Zeroconf.codeAnswer(200, """{"status":202,"statusString":"ERROR-LOGIN-FAILED","spotifyError":0}"""))+ assertEquals(Zeroconf.CodeAnswer.INVALID_KEY, Zeroconf.codeAnswer(200, """{"status":203,"statusString":"ERROR-INVALID-PUBLICKEY"}"""))+ assertEquals(Zeroconf.CodeAnswer.GROUPED, Zeroconf.codeAnswer(500, ""))+ assertEquals(Zeroconf.CodeAnswer.GROUPED, Zeroconf.codeAnswer(500, """{"status":102}"""))+ assertEquals(Zeroconf.CodeAnswer.REFUSED, Zeroconf.codeAnswer(200, """{"status":103,"statusString":"ERROR-INVALID-ARGUMENTS"}"""))+ assertEquals(Zeroconf.CodeAnswer.REFUSED, Zeroconf.codeAnswer(404, ""))+ assertEquals("status 202 ERROR-LOGIN-FAILED spotifyError 7", Zeroconf.answerSummary("""{"status":202,"statusString":"ERROR-LOGIN-FAILED","spotifyError":7}"""))+ assertEquals("not JSON len=1", Zeroconf.answerSummary("}"))+ }+@Test fun responsesAreReadWithAndWithoutChunks() {val plain = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello".toByteArray()assertEquals(200 to "hello", Zeroconf.parseResponse(plain))