Skip to content

Native Android client for Spotify, built with Jetpack Compose

On WebViews without web message listeners, the page's messages to the app through the fallback interface (reachable from every frame) now carry a random secret, new at each page start and given only to the top document, so a message from another frame is ignored and counted in the diagnostic [skip ci]

kota-zo9d5eeee3aa89
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
index 30f7d503..d960b808 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
@@ -43,6 +43,9 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:
@Volatile var onDeviceRegistered: (() -> Unit)? = null
private val main = Handler(Looper.getMainLooper())
+ /** The guarded fallback channel of a WebView without web message listeners (see [PlayerChannel]). */
+ internal var channel: PlayerChannel? = null
+
/** The same client ([http]), pinned to one address family (see RelayRoutes); same pool. */
private val v4Client by lazy { http.newBuilder().dns(FamilyDns(IpFamily.V4)).build() }
private val v6Client by lazy { http.newBuilder().dns(FamilyDns(IpFamily.V6)).build() }
@@ -52,7 +55,7 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:
NetworkReport.logOnce(view.context.applicationContext)
// Before Android 14: Cronet from Play services, ready before any refusal needs it.
CronetStack.prepare(view.context)
- view.exposeToPlayer("MyspotiNet", ::onMessage)
+ channel = view.exposeToPlayer("MyspotiNet", ::onMessage)
val documentStart = androidx.webkit.WebViewFeature.isFeatureSupported(androidx.webkit.WebViewFeature.DOCUMENT_START_SCRIPT)
if (documentStart) androidx.webkit.WebViewCompat.addDocumentStartJavaScript(view, SCRIPT, setOf("https://open.spotify.com"))
Logbook.log("control relay installed (document start: $documentStart)")
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlayerChannel.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlayerChannel.kt
index 960c8187..b80058f5 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlayerChannel.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlayerChannel.kt
@@ -12,24 +12,60 @@ import androidx.webkit.WebViewFeature
* An `addJavascriptInterface` object is injected into every frame of the WebView, whatever its
* origin: the player page embeds a google.com reCAPTCHA iframe, which could then post to the
* app. A web message listener is only injected into frames of [PLAYER_ORIGIN], and only the
- * main frame's messages are taken. WebViews without the feature fall back to the interface;
- * the page calls the same `postMessage` either way.
+ * main frame's messages are taken. WebViews without the feature fall back to the interface,
+ * guarded by a secret (see [PlayerChannel]); the page calls the same `postMessage` either way.
+ * Returns the fallback channel to arm at each page start, or null when the listener is used.
*/
@SuppressLint("JavascriptInterface")
-internal fun WebView.exposeToPlayer(name: String, onMessage: (String) -> Unit) {
+internal fun WebView.exposeToPlayer(name: String, onMessage: (String) -> Unit): PlayerChannel? {
if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
WebViewCompat.addWebMessageListener(this, name, setOf(PLAYER_ORIGIN)) { _, message, _, isMainFrame, _ ->
if (isMainFrame) message.data?.let(onMessage)
}
- } else {
- addJavascriptInterface(PlayerChannel(onMessage), name)
+ return null
}
+ return PlayerChannel(name, onMessage).also { addJavascriptInterface(it, name) }
}
private const val PLAYER_ORIGIN = "https://open.spotify.com"
-/** Fallback channel for WebViews without web message listeners. */
-internal class PlayerChannel(private val onMessage: (String) -> Unit) {
+/**
+ * Fallback channel for WebViews without web message listeners, where the interface object is
+ * reachable from every frame. A message is only taken when it starts with the page's secret:
+ * a random token, new at each page start ([newPage]), that [shim] hands to the main frame's
+ * script only. The shim replaces `window.<name>` in the top document by a wrapper that keeps the
+ * raw interface and the token in its closure, so the scripts of the app go on calling
+ * `postMessage(json)` unchanged; a frame of another origin cannot read the top document's
+ * closure and its messages carry no valid token. Refused messages are dropped and counted in the log.
+ */
+internal class PlayerChannel(private val name: String, private val onMessage: (String) -> Unit) {
+ @Volatile private var token = ""
+ private val refused = java.util.concurrent.atomic.AtomicInteger()
+
+ /** A fresh secret for the page that starts now; the previous one stops working. */
+ fun newPage() {
+ token = ByteArray(16).also { java.security.SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
+ }
+
+ /** The script that installs the wrapper in the top document with the current secret; harmless twice. */
+ fun shim(): String = """
+ (() => {
+ if (window !== window.top) return;
+ const raw = window.$name;
+ if (!raw || raw.__msp) return;
+ const wrapper = { __msp: true, postMessage: (m) => raw.postMessage('$token.' + m) };
+ try { Object.defineProperty(window, '$name', { value: wrapper }); } catch (e) { window.$name = wrapper; }
+ })();
+ """.trimIndent()
+
@JavascriptInterface
- fun postMessage(message: String) = onMessage(message)
+ fun postMessage(message: String) {
+ val t = token
+ if (t.isEmpty() || message.length <= t.length || !message.startsWith(t) || message[t.length] != '.') {
+ val n = refused.incrementAndGet()
+ Logbook.logEvery("channel-refused-$name", 60_000, "$name message without the page's secret ignored ($n so far)")
+ return
+ }
+ onMessage(message.substring(t.length + 1))
+ }
}