Modern Apps git

← Modern-Apps.git

youpipe: fix SABR stall with home-page attestation bootstrap (#565)

Commit
5902326ff4b9a17957c9a5f0d13bba72365d984f
Author
vayun-mathur <[email protected]>
When
2026-09-14 01:17 UTC (2 months ago)
Parents
6404d06

Diff

youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSession.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSession.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSession.ktindex da787d9db5..66f681352c 100644--- a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSession.kt+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSession.kt@@ -369,6 +369,10 @@ class YoutubeSabrSession @JvmOverloads constructor(     @Synchronized     fun setPoToken(value: ByteArray?) {         poToken = value?.clone()+        // A fresh token starts a fresh attestation epoch: "pending" responses observed so far+        // belonged to the rejected identity, not this one. Without this reset the pending+        // counter survives rotation and the new token trips the threshold on arrival (#565).+        consecutiveAttestationPendingResponses = 0     }      internal fun getRawPoToken(): ByteArray? = poToken
youpipe/extractor/src/test/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSessionAttestationTest.kt
diff --git a/youpipe/extractor/src/test/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSessionAttestationTest.kt b/youpipe/extractor/src/test/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSessionAttestationTest.ktnew file mode 100644index 0000000000..77bc3c5166--- /dev/null+++ b/youpipe/extractor/src/test/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSessionAttestationTest.kt@@ -0,0 +1,52 @@+package org.schabi.newpipe.extractor.services.youtube.sabrng++import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Regression test for #565: a fresh PO token starts a fresh attestation epoch.+ *+ * The issue log showed "attestation remained pending without media for 6 consecutive responses"+ * against a threshold of 3: the pending counter survived PO-token rotation, so the retried+ * token tripped the threshold on arrival. [YoutubeSabrSession.setPoToken] must reset the+ * counter.+ */+class YoutubeSabrSessionAttestationTest {++    private fun session(): YoutubeSabrSession {+        val info = YoutubeSabrInfo(+            videoId = "GZVfNMVYYRY",+            cpn = "test-cpn-0123456789",+            clientVersion = "1.02",+            visitorData = "test-visitor",+            serverAbrStreamingUrl = "https://redirector.googlevideo.com/videoplayback",+            videoPlaybackUstreamerConfig = null,+            formats = emptyList(),+        )+        return YoutubeSabrSession(info, null)+    }++    @Test+    fun `setPoToken resets consecutive attestation pending count`() {+        val session = session()+        val counter = YoutubeSabrSession::class.java.getDeclaredField(+            "consecutiveAttestationPendingResponses"+        ).apply { isAccessible = true }++        counter.setInt(session, 2)+        session.setPoToken(byteArrayOf(1, 2, 3))+        assertEquals(0, counter.getInt(session))+    }++    @Test+    fun `setPoToken with null still resets the counter`() {+        val session = session()+        val counter = YoutubeSabrSession::class.java.getDeclaredField(+            "consecutiveAttestationPendingResponses"+        ).apply { isAccessible = true }++        counter.setInt(session, 2)+        session.setPoToken(null)+        assertEquals(0, counter.getInt(session))+    }+}
youpipe/src/main/assets/sabr_po_token.js
diff --git a/youpipe/src/main/assets/sabr_po_token.js b/youpipe/src/main/assets/sabr_po_token.jsindex 129945404f..e630443637 100644--- a/youpipe/src/main/assets/sabr_po_token.js+++ b/youpipe/src/main/assets/sabr_po_token.js@@ -46,13 +46,19 @@ function loadBotGuard(root, challengeData, onReady, onError) {       };     }; +    var noOp = function () {};+    var loggerFunctions = [noOp, noOp, noOp, noOp, noOp];+     root.syncSnapshotFunction = root.vm.a(       root.program,       vmFunctionsCallback,       true,       root.userInteractionElement,-      function () {},-      [[], []]+      noOp,+      [[], []],+      undefined,+      false,+      loggerFunctions     )[0];      root._botGuardPolls = 0;@@ -167,9 +173,12 @@ function obtainPoToken(mintCallback, identifier) {   return result; } -function pipepipeSabrRunBotguard(sessionId, challengeData) {+function pipepipeSabrRunBotguard(sessionId, eventId, challengeData) {   var bridge = pipepipeBridge();   try {+    window.yt = window.yt || {};+    window.yt.config_ = window.yt.config_ || {};+    window.yt.config_.EVENT_ID = eventId;     runBotGuard(       challengeData,       function (result) {
youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayerPlaybackEffects.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayerPlaybackEffects.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayerPlaybackEffects.ktindex 646d3f602c..d9c4f57efe 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayerPlaybackEffects.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/ui/VideoPlayerPlaybackEffects.kt@@ -12,6 +12,7 @@ import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource import androidx.core.net.toUri import androidx.media3.common.C import androidx.media3.common.MediaItem@@ -25,6 +26,8 @@ import androidx.media3.common.util.UnstableApi import androidx.media3.session.MediaController import androidx.media3.session.SessionToken import com.google.common.util.concurrent.MoreExecutors+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.youpipe.R import com.vayunmathur.youpipe.data.HistoryVideo import com.vayunmathur.youpipe.findActivity import com.vayunmathur.youpipe.platform.CastPlayback@@ -96,6 +99,9 @@ internal fun VideoPlayerTransportObserver(     val context = LocalContext.current     var aspectRatio by aspectRatioState     var cues by cuesState+    // #565: a mid-playback SABR failure used to surface as a silent stall (the spinner spins,+    // nothing says why). Surface ExoPlayer errors as a message so the user knows playback died.+    val playbackErrorMessage = stringResource(R.string.playback_error)     DisposableEffect(controller) {         val player = controller ?: return@DisposableEffect onDispose {}         // Sync initial playing state once controller is available@@ -114,6 +120,10 @@ internal fun VideoPlayerTransportObserver(                     }                 }             }+            override fun onPlayerError(error: androidx.media3.common.PlaybackException) {+                android.util.Log.e("YouPipePlayer", "Playback error", error)+                AppMessages.show(playbackErrorMessage)+            }             override fun onIsPlayingChanged(isPlayingNow: Boolean) {                 CastPlayback.update { it.copy(playing = isPlayingNow) }                 context.findActivity().setPictureInPictureParams(PictureInPictureParams.Builder().apply {
youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.ktindex 03b3b0a07b..67a091df41 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.kt@@ -120,7 +120,7 @@ class PlaybackService : MediaSessionService() {                         val vAudioItag = audioItag                         val vAudioTrackId = audioTrackIdOverride                         val tokenMinter: (Boolean) -> ByteArray? = { force ->-                            provider.getPoTokenBytes(videoId, info.getVisitorData(), force)+                            provider.getPoTokenBytes(videoId, force)                         }                         val specSupplier: () -> com.vayunmathur.youpipe.util.sabr.SabrNgSourceSpec = {                             val poToken = tokenMinter(false)
youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeImportExport.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeImportExport.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeImportExport.ktindex 7e70133ffa..3642ce5f9a 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeImportExport.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeImportExport.kt@@ -4,6 +4,8 @@ import android.app.Application import android.net.Uri import android.util.Log import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.youpipe.R import com.vayunmathur.youpipe.data.HistoryVideo import com.vayunmathur.youpipe.data.Subscription import com.vayunmathur.youpipe.ui.VideoInfo@@ -159,17 +161,38 @@ fun YouPipeViewModel.restoreSubscriptions(uri: Uri) {         _isImporting.value = true         try {             val json = ctx.contentResolver.openInputStream(uri)!!.bufferedReader().readText()-            val subs = Json.decodeFromString<List<Subscription>>(json)-            repository.clearAllSubscriptions()-            repository.upsertSubscriptions(subs)+            val subs = decodeSubscriptionBackup(json)+            if (subs == null) {+                // #565: files shaped like {"version":1,"salt":"..."} are an encrypted/salted+                // envelope written by another client, not a plain subscription list. There is no+                // password UI to decrypt with, so report it instead of crashing on the decode.+                Log.e(TAG, "Unsupported subscription backup format")+                AppMessages.show(ctx.getString(R.string.restore_unsupported_format))+            } else {+                repository.clearAllSubscriptions()+                repository.upsertSubscriptions(subs)+            }         } catch (e: Exception) {             Log.e(TAG, "Error restoring subscriptions", e)+            AppMessages.show(ctx.getString(R.string.restore_unsupported_format))         }         _isImporting.value = false         setupHourlyTask(ctx)     } } +/**+ * Decodes a YouPipe subscription backup: a plain JSON array of [Subscription].+ * Returns null when the file is a non-array envelope (e.g. an encrypted+ * `{"version":..,"salt":..}` backup from another client) rather than throwing, so callers can+ * report an unsupported-format message.+ */+internal fun decodeSubscriptionBackup(json: String): List<Subscription>? {+    val trimmed = json.trimStart()+    if (!trimmed.startsWith("[")) return null+    return Json.decodeFromString<List<Subscription>>(json)+}+ fun YouPipeViewModel.importNewPipe(uri: Uri) {     val ctx = getApplication<Application>()     viewModelScope.launch(Dispatchers.IO) {
youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/LocalDomPoTokenGenerator.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/LocalDomPoTokenGenerator.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/LocalDomPoTokenGenerator.ktindex 3f6fb81e1b..616ab744db 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/LocalDomPoTokenGenerator.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/LocalDomPoTokenGenerator.kt@@ -9,9 +9,18 @@ import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference +/**+ * Mints PO tokens inside the shared WebView runtime from a home-page attestation bootstrap.+ *+ * Port of PipePipe's `PersistentMintSession`: the BotGuard challenge comes from the YouTube home+ * page (`window.ytAtN`, parsed by [parseYoutubePageAttestationBootstrap]) and the run is bound+ * to the page's EVENT_ID. The previous `youtubei/v1/att/get` UNBOUND flow minted tokens the+ * server leaves at attestation-pending forever (#565).+ */ internal class LocalDomPoTokenGenerator private constructor(     context: Context,     private val initialization: InitWaiter,+    private val bootstrap: YoutubePageAttestationBootstrap, ) : Closeable {     private val appContext = context.applicationContext     private val runtime = SharedWebViewRuntime.get(appContext)@@ -37,7 +46,7 @@ internal class LocalDomPoTokenGenerator private constructor(      @Synchronized     @Throws(SabrProtocolException::class)-    fun generateRawPoToken(identifier: String): ByteArray {+    fun mint(identifier: String): ByteArray {         if (closed) {             throw SabrProtocolException("Local DOM PO token generator is closed")         }@@ -115,7 +124,7 @@ internal class LocalDomPoTokenGenerator private constructor(                 val response = downloader.post(                     url,                     mapOf(-                        "User-Agent" to listOf(USER_AGENT),+                        "User-Agent" to listOf(SharedWebViewRuntime.USER_AGENT),                         "Accept" to listOf("application/json"),                         "Content-Type" to listOf(contentType),                         "x-goog-api-key" to listOf(GOOGLE_API_KEY),@@ -146,7 +155,7 @@ internal class LocalDomPoTokenGenerator private constructor(                 val response = downloader.get(                     url,                     mapOf(-                        "User-Agent" to listOf(USER_AGENT),+                        "User-Agent" to listOf(SharedWebViewRuntime.USER_AGENT),                         "Accept" to listOf("*/*"),                     ),                 )@@ -195,34 +204,33 @@ internal class LocalDomPoTokenGenerator private constructor(     }      private fun downloadAndRunBotguard() {-        makeBotguardServiceRequest(-            "https://www.youtube.com/youtubei/v1/att/get?prettyPrint=false",-            """{"context":{"client":{"clientName":"WEB","clientVersion":"$ATT_CLIENT_VERSION"}},"engagementType":"ENGAGEMENT_TYPE_UNBOUND"}""",-            contentType = "application/json",-            onSuccess = { body ->-                try {-                    val challenge = parseSabrAttChallengeData(body)-                    makeBotguardGetRequest(-                        challenge.interpreterUrl,-                        onSuccess = { interpreterJavascript ->-                            val challengeData = buildSabrAttChallengeData(-                                challenge,-                                interpreterJavascript,-                            )-                            runtime.evaluateJavascript(-                                "pipepipeSabrRunBotguard(" + jsString(sessionId)-                                    + ", " + challengeData + ");",-                                null,-                            ) { error -> failInitialization(error) }-                        },-                        onError = ::failInitialization,-                    )-                } catch (error: Throwable) {-                    failInitialization(error)-                }-            },-            onError = ::failInitialization,-        )+        val challenge = bootstrap.challenge+        val inlineInterpreter = challenge.interpreterJavascript+        if (inlineInterpreter != null) {+            runBotguard(challenge, inlineInterpreter)+        } else {+            val url = challenge.interpreterUrl+                ?: return failInitialization(+                    SabrProtocolException("Attestation challenge has no interpreter script or URL")+                )+            makeBotguardGetRequest(+                url,+                onSuccess = { runBotguard(challenge, it) },+                onError = ::failInitialization,+            )+        }+    }++    private fun runBotguard(+        challenge: SabrAttChallengeData,+        interpreterJavascript: String,+    ) {+        val challengeData = buildSabrAttChallengeData(challenge, interpreterJavascript)+        runtime.evaluateJavascript(+            "pipepipeSabrRunBotguard(" + jsString(sessionId) + ", "+                + jsString(bootstrap.eventId) + ", " + challengeData + ");",+            null,+        ) { error -> failInitialization(error) }     }      private fun onRunBotguardResult(botguardResponse: String) {@@ -286,14 +294,14 @@ internal class LocalDomPoTokenGenerator private constructor(         private const val INIT_TIMEOUT_MS = 60_000L         private const val GOOGLE_API_KEY = "AIzaSyDyT5W0Jh49F30Pqqtyfdf7pDLFKLJoAnw"         private const val REQUEST_KEY = "O43z0dpjhgX20SCx4KAo"-        private const val ATT_CLIENT_VERSION = "2.20260227.01.00"-        private const val USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +-            "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.3"          @Throws(SabrProtocolException::class)-        fun create(context: Context): LocalDomPoTokenGenerator {+        fun create(+            context: Context,+            bootstrap: YoutubePageAttestationBootstrap,+        ): LocalDomPoTokenGenerator {             val init = InitWaiter()-            val generator = LocalDomPoTokenGenerator(context, init)+            val generator = LocalDomPoTokenGenerator(context, init, bootstrap)             generator.loadScriptAndInitialize()             try {                 if (!init.latch.await(INIT_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/LocalDomPoTokenProvider.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/LocalDomPoTokenProvider.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/LocalDomPoTokenProvider.ktindex ab26009a4c..ce987e4a1d 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/LocalDomPoTokenProvider.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/LocalDomPoTokenProvider.kt@@ -1,420 +1,222 @@ package com.vayunmathur.youpipe.util.sabr  import android.content.Context-import android.os.Handler-import android.os.Looper import android.util.Log-import androidx.core.content.edit-import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException+import org.schabi.newpipe.extractor.NewPipe import org.schabi.newpipe.extractor.localization.ContentCountry import org.schabi.newpipe.extractor.localization.Localization-import org.schabi.newpipe.extractor.services.youtube.InnertubeClientRequestInfo-import org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper import org.schabi.newpipe.extractor.services.youtube.YoutubeSessionPoToken import org.schabi.newpipe.extractor.services.youtube.YoutubeSessionPoTokenProvider-import java.security.MessageDigest+import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException import java.util.Base64-import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ExecutionException import java.util.concurrent.Executors import java.util.concurrent.FutureTask -internal fun youtubeCredentialIdentity(loggedIn: Boolean, tokens: String?): String {-    val digest = MessageDigest.getInstance("SHA-256")-    digest.update(if (loggedIn) 1.toByte() else 0.toByte())-    if (loggedIn) {-        digest.update(0.toByte())-        digest.update(tokens.orEmpty().toByteArray(Charsets.UTF_8))-    }-    return Base64.getUrlEncoder().withoutPadding().encodeToString(digest.digest())-}--internal class CredentialIdentityTracker(private val onChanged: () -> Unit) {-    private var observedIdentity: String? = null--    @Synchronized-    fun observe(identity: String) {-        val previous = observedIdentity-        if (previous != null && previous != identity) {-            onChanged()-        }-        observedIdentity = identity-    }-}--class LocalDomPoTokenProvider(context: Context) :-    YoutubeSessionPoTokenProvider {-    private data class CachedToken(-        val token: ByteArray,-        val mintedAtMs: Long,-        val visitorData: String,-        val credentialIdentity: String,+/**+ * Global PO-token minter for the session-based SABR stack.+ *+ * Port of PipePipe's `LocalDomPoTokenProvider` (post-#84 rewrite): a single mint session is+ * bootstrapped from the YouTube home page ([parseYoutubePageAttestationBootstrap]) and every+ * token — per-video content tokens for SABR playback/downloads and the session token for the+ * WEB player fetch — is minted from that one BotGuard session. The previous design minted each+ * video's token from its own `youtubei/v1/att/get` UNBOUND attestation, whose tokens the server+ * leaves at attestation-pending forever (#565: playback stalls mid-video after 6 no-media+ * responses).+ *+ * When the server rejects the attestation identity, [invalidate] tears the whole session down+ * and re-bootstraps from a fresh home page (upstream `invalidate()`), so the next mint comes+ * from a new identity instead of re-minting from the burned one.+ */+class LocalDomPoTokenProvider(context: Context) : YoutubeSessionPoTokenProvider {+    private data class MintState(+        val bootstrap: YoutubePageAttestationBootstrap,+        val generator: LocalDomPoTokenGenerator,+        val sessionPoToken: ByteArray?,     )      private val appContext = context.applicationContext-    private val prefs = appContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)-    private val cache = ConcurrentHashMap<String, CachedToken>()-    private val mintLocks = ConcurrentHashMap<String, Any>()-    private val generatorLock = Any()-    private val mainHandler = Handler(Looper.getMainLooper())-    private var generatorVisitorData: String? = null-    private var generatorCredentialIdentity: String? = null-    private var generator: LocalDomPoTokenGenerator? = null-    private var rawSessionPoToken: ByteArray? = null-    private val visitorDataLock = Any()-    private var fetchedVisitorData: String? = null-    private var fetchedVisitorDataLoggedIn: Boolean? = null-    private var fetchedVisitorDataCredentialIdentity: String? = null-    private var visitorDataFetchedAtMs: Long = 0-    private val credentialIdentityTracker = CredentialIdentityTracker(-        onChanged = ::invalidateCredentialBoundState,-    )-    private val prewarmLock = Any()-    private val prewarmExecutor = Executors.newSingleThreadExecutor { runnable ->-        Thread(runnable, "YoutubeSessionPoTokenPrewarm")-    }-    private var prewarmCredentialIdentity: String? = null-    private var prewarmTask: FutureTask<YoutubeSessionPoToken?>? = null--    override fun getSessionPoToken(-        clientName: String,-        localization: Localization,-        contentCountry: ContentCountry,-        loggedIn: Boolean,-    ): YoutubeSessionPoToken? {-        val credentialIdentity = currentCredentialIdentity(loggedIn)-        val inFlightPrewarm = synchronized(prewarmLock) {-            prewarmTask?.takeIf {-                prewarmCredentialIdentity == credentialIdentity && !it.isDone-            }-        }-        if (inFlightPrewarm != null) {-            try {-                return inFlightPrewarm.get()-            } catch (error: InterruptedException) {-                Thread.currentThread().interrupt()-                throw SabrProtocolException(-                    "Interrupted waiting for session PO token prewarm",-                    error,-                )-            } catch (error: ExecutionException) {-                throw SabrProtocolException(-                    "Session PO token prewarm failed",-                    error.cause ?: error,-                )-            }-        }-        return getSessionPoTokenNow(-            clientName,-            localization,-            contentCountry,-            loggedIn,-            credentialIdentity,-        )+    private val initializationExecutor = Executors.newSingleThreadExecutor { runnable ->+        Thread(runnable, "YoutubePoTokenWarmup").apply { isDaemon = true }     }+    private val initializationLock = Any() -    fun prewarmSessionPoToken(-        localization: Localization,-        contentCountry: ContentCountry,-        loggedIn: Boolean,-    ) {-        val credentialIdentity = currentCredentialIdentity(loggedIn)-        synchronized(prewarmLock) {-            val current = prewarmTask-            if (prewarmCredentialIdentity == credentialIdentity && current != null &&-                !current.isDone-            ) {-                return-            }-            val task = FutureTask {-                val startMs = android.os.SystemClock.elapsedRealtime()-                if (currentCredentialIdentity(currentlyLoggedIn()) !=-                    credentialIdentity-                ) {-                    Log.i(TAG, "session token prewarm skipped after credentials changed")-                    return@FutureTask null-                }-                try {-                    getSessionPoTokenNow(-                        PREWARM_CLIENT_NAME,-                        localization,-                        contentCountry,-                        loggedIn,-                        credentialIdentity,-                    ).also {-                        Log.i(-                            TAG,-                            "session token prewarm ready in " +-                                "${android.os.SystemClock.elapsedRealtime() - startMs}ms",-                        )-                    }-                } catch (error: Throwable) {-                    Log.w(TAG, "session token prewarm failed", error)-                    throw error-                }-            }-            prewarmCredentialIdentity = credentialIdentity-            prewarmTask = task-            prewarmExecutor.execute(task)-        }-    }+    @Volatile+    private var initializationTask: FutureTask<MintState>? = null -    private fun getSessionPoTokenNow(-        clientName: String,-        localization: Localization,-        contentCountry: ContentCountry,-        loggedIn: Boolean,-        credentialIdentity: String,-    ): YoutubeSessionPoToken? {-        credentialIdentityTracker.observe(credentialIdentity)-        val visitorData = getOrFetchVisitorData(-            localization,-            contentCountry,-            loggedIn,-            credentialIdentity,-        )-        val rawToken = getRawSessionPoToken(visitorData, credentialIdentity)-        val encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(rawToken)-        Log.i(-            TAG,-            "session token ready client=$clientName loggedIn=$loggedIn bytes=${rawToken.size}",-        )-        return YoutubeSessionPoToken(visitorData, encoded)+    fun warmUp() {+        ensureInitializationTask()     }      /**-     * Raw PO token bytes for the session-based SABR stack ([SabrNgSession]); takes the-     * videoId/visitorData directly so it does not depend on the legacy `sabr` package types.+     * Raw PO token bytes for the session-based SABR stack ([SabrNgSession]), minted from the+     * global home-page session for [videoId].      */     @JvmOverloads     fun getPoTokenBytes(         videoId: String,-        visitorDataHint: String?,         forceRefresh: Boolean = false,     ): ByteArray? {-        val credentialIdentity = currentCredentialIdentity(currentlyLoggedIn())-        credentialIdentityTracker.observe(credentialIdentity)-        val visitorData = visitorDataHint ?: synchronized(visitorDataLock) {-            fetchedVisitorData-        } ?: throw SabrProtocolException("Missing visitorData for Local DOM PO token")         if (forceRefresh) {-            cache.remove(videoId)-            prefs.edit { remove(videoId) }-        }-        synchronized(mintLocks.computeIfAbsent(videoId) { Any() }) {-            val now = System.currentTimeMillis()-            val cached = cache[videoId]-                ?: diskLoad(videoId)?.also { cache[videoId] = it }-            if (cached != null && cached.visitorData == visitorData &&-                cached.credentialIdentity == credentialIdentity &&-                now - cached.mintedAtMs < TOKEN_TTL_MS-            ) {-                Log.i(TAG, "cache hit video=$videoId bytes=${cached.token.size}")-                return cached.token-            }-            val token = ensureGenerator(visitorData, credentialIdentity)-                .generateRawPoToken(videoId)-            cache[videoId] = CachedToken(token, now, visitorData, credentialIdentity)-            diskSave(videoId, token, now, visitorData, credentialIdentity)-            Log.i(TAG, "mint complete video=$videoId bytes=${token.size}")-            return token-        }-    }--    fun hasCachedToken(videoId: String): Boolean {-        val credentialIdentity = currentCredentialIdentity(currentlyLoggedIn())-        credentialIdentityTracker.observe(credentialIdentity)-        val mem = cache[videoId]-        if (mem != null && mem.credentialIdentity == credentialIdentity &&-            System.currentTimeMillis() - mem.mintedAtMs < TOKEN_TTL_MS-        ) {-            return true-        }-        return diskLoad(videoId)?.credentialIdentity == credentialIdentity-    }--    fun clearCachedToken(videoId: String) {-        synchronized(mintLocks.computeIfAbsent(videoId) { Any() }) {-            cache.remove(videoId)-            prefs.edit(commit = true) { remove(videoId) }+            invalidate()+        }+        val state = getState()+        return when (state.bootstrap.binding) {+            YoutubePoTokenBinding.CONTENT -> state.generator.mint(videoId)+            YoutubePoTokenBinding.SESSION ->+                requireNotNull(state.sessionPoToken).clone()+            YoutubePoTokenBinding.NONE -> throw SabrProtocolException(+                "YouTube home does not enable a supported PO token binding",+            )         }     } -    private fun ensureGenerator(-        visitorData: String,-        credentialIdentity: String,-    ): LocalDomPoTokenGenerator {-        synchronized(generatorLock) {-            val current = generator-            if (current != null && !current.isExpired() &&-                generatorVisitorData == visitorData &&-                generatorCredentialIdentity == credentialIdentity &&-                rawSessionPoToken != null-            ) {-                return current-            }-            if (!credentialsStillMatch(credentialIdentity)) {-                throw SabrProtocolException(-                    "YouTube credentials changed before PO token generator initialization",-                )-            }-            current?.let { mainHandler.post { it.close() } }-            val fresh = LocalDomPoTokenGenerator.create(appContext)-            val freshSessionPoToken = fresh.generateRawPoToken(visitorData)-            if (!credentialsStillMatch(credentialIdentity)) {-                mainHandler.post { fresh.close() }-                throw SabrProtocolException(-                    "YouTube credentials changed during PO token generator initialization",-                )+    /**+     * Closes the rejected mint session and re-bootstraps from a fresh home page. Called when+     * the server rejects the attestation identity so the next mint does not come from the+     * burned session. Port of upstream `LocalDomPoTokenProvider.invalidate()`.+     */+    fun invalidate() {+        val sessionToClose: LocalDomPoTokenGenerator+        synchronized(initializationLock) {+            val task = initializationTask ?: return+            if (!task.isDone || task.isCancelled) return+            val state = try {+                task.get()+            } catch (_: Exception) {+                return             }-            generator = fresh-            generatorVisitorData = visitorData-            generatorCredentialIdentity = credentialIdentity-            rawSessionPoToken = freshSessionPoToken-            return fresh+            initializationTask = null+            sessionToClose = state.generator         }+        sessionToClose.close()+        Log.i(TAG, "Invalidated rejected PO token minter")+        warmUp()     } -    private fun getRawSessionPoToken(-        visitorData: String,-        credentialIdentity: String,-    ): ByteArray {-        synchronized(generatorLock) {-            ensureGenerator(visitorData, credentialIdentity)-            return rawSessionPoToken?.clone()-                ?: throw SabrProtocolException("Local DOM session PO token is missing")+    override fun getSessionPoToken(+        clientName: String,+        localization: Localization,+        contentCountry: ContentCountry,+        loggedIn: Boolean,+    ): YoutubeSessionPoToken? {+        val state = getState()+        if (state.bootstrap.binding == YoutubePoTokenBinding.NONE) {+            throw SabrProtocolException(+                "YouTube home does not enable a supported PO token binding",+            )         }+        // Token for the WEB player request's serviceIntegrityDimensions, bound to the same+        // BotGuard session as the per-video SABR tokens.+        val rawToken = state.sessionPoToken+            ?: state.generator.mint(state.bootstrap.visitorData)+        val encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(rawToken)+        Log.i(+            TAG,+            "session token ready client=$clientName loggedIn=$loggedIn bytes=${rawToken.size}",+        )+        return YoutubeSessionPoToken(state.bootstrap.visitorData, encoded)     } -    private fun getOrFetchVisitorData(+    fun prewarmSessionPoToken(         localization: Localization,         contentCountry: ContentCountry,         loggedIn: Boolean,-        credentialIdentity: String,-    ): String {-        synchronized(visitorDataLock) {-            val now = System.currentTimeMillis()-            val cached = fetchedVisitorData-            if (cached != null && fetchedVisitorDataLoggedIn == loggedIn &&-                fetchedVisitorDataCredentialIdentity == credentialIdentity &&-                now - visitorDataFetchedAtMs < VISITOR_DATA_TTL_MS-            ) {-                return cached-            }+    ) {+        warmUp()+    } -            val headers = HashMap<String, List<String>>()-            headers.putAll(YoutubeParsingHelper.getYouTubeHeaders())-            headers["Content-Type"] = listOf("application/json")-            if (loggedIn) {-                YoutubeParsingHelper.addLoggedInHeaders(headers)-            }-            val fresh = YoutubeParsingHelper.getVisitorDataFromInnertube(-                InnertubeClientRequestInfo.ofWebClient(),-                localization,-                contentCountry,-                headers,-                YoutubeParsingHelper.YOUTUBEI_V1_URL,-                null,-                false,-            )-            if (!credentialsStillMatch(credentialIdentity)) {+    private fun getState(): MintState {+        while (true) {+            val task = ensureInitializationTask()+            val state = try {+                task.get()+            } catch (error: InterruptedException) {+                Thread.currentThread().interrupt()+                throw SabrProtocolException("Global PO token initialization interrupted", error)+            } catch (error: ExecutionException) {+                synchronized(initializationLock) {+                    if (initializationTask === task) {+                        initializationTask = null+                    }+                }+                val cause = error.cause ?: error                 throw SabrProtocolException(-                    "YouTube credentials changed while fetching visitorData",+                    "Global PO token initialization failed: ${cause.message}",+                    cause,                 )             }-            fetchedVisitorData = fresh-            fetchedVisitorDataLoggedIn = loggedIn-            fetchedVisitorDataCredentialIdentity = credentialIdentity-            visitorDataFetchedAtMs = now-            return fresh-        }-    }--    // This fork does not support an authenticated YouTube session.-    private fun currentlyLoggedIn(): Boolean = false--    private fun currentCredentialIdentity(loggedIn: Boolean): String {-        return youtubeCredentialIdentity(loggedIn, null)-    }--    private fun credentialsStillMatch(credentialIdentity: String): Boolean {-        return currentCredentialIdentity(currentlyLoggedIn()) == credentialIdentity-    }--    private fun invalidateCredentialBoundState() {-        synchronized(visitorDataLock) {-            fetchedVisitorData = null-            fetchedVisitorDataLoggedIn = null-            fetchedVisitorDataCredentialIdentity = null-            visitorDataFetchedAtMs = 0-        }-        synchronized(generatorLock) {-            generator?.let { mainHandler.post { it.close() } }-            generator = null-            generatorVisitorData = null-            generatorCredentialIdentity = null-            rawSessionPoToken = null+            if (!state.generator.isExpired()) {+                return state+            }+            synchronized(initializationLock) {+                if (initializationTask === task) {+                    initializationTask = null+                    state.generator.close()+                }+            }         }-        cache.clear()-        prefs.edit(commit = true) { clear() }-        Log.i(TAG, "YouTube credentials changed; cleared credential-bound PO token state")     } -    private fun diskLoad(videoId: String): CachedToken? {-        val value = prefs.getString(videoId, null) ?: return null-        val parts = value.split('|', limit = 4)-        if (parts.size != 4) {-            prefs.edit { remove(videoId) }-            return null-        }-        return try {-            val mintedAt = parts[0].toLong()-            if (System.currentTimeMillis() - mintedAt >= TOKEN_TTL_MS) {-                prefs.edit { remove(videoId) }-                null-            } else {-                val visitorData = String(-                    Base64.getUrlDecoder().decode(parts[2]),-                    Charsets.UTF_8,-                )-                CachedToken(-                    Base64.getUrlDecoder().decode(parts[3]),-                    mintedAt,-                    visitorData,-                    parts[1],-                )+    private fun ensureInitializationTask(): FutureTask<MintState> {+        initializationTask?.let { return it }+        synchronized(initializationLock) {+            initializationTask?.let { return it }+            val task = FutureTask {+                val bootstrap = fetchHomeBootstrap()+                if (bootstrap.binding == YoutubePoTokenBinding.NONE) {+                    throw SabrProtocolException(+                        "YouTube home does not enable a supported PO token binding",+                    )+                }+                val generator = LocalDomPoTokenGenerator.create(appContext, bootstrap)+                try {+                    val sessionPoToken =+                        if (bootstrap.binding == YoutubePoTokenBinding.SESSION) {+                            generator.mint(bootstrap.visitorData)+                        } else {+                            null+                        }+                    Log.i(+                        TAG,+                        "Global PO minter ready client=${bootstrap.clientName} " ++                            "version=${bootstrap.clientVersion} " ++                            "binding=${bootstrap.binding}",+                    )+                    MintState(bootstrap, generator, sessionPoToken)+                } catch (error: Throwable) {+                    generator.close()+                    throw error+                }             }-        } catch (error: IllegalArgumentException) {-            null+            initializationTask = task+            initializationExecutor.execute(task)+            return task         }     } -    private fun diskSave(-        videoId: String,-        token: ByteArray,-        mintedAt: Long,-        visitorData: String,-        credentialIdentity: String,-    ) {-        val encoder = Base64.getUrlEncoder().withoutPadding()-        val encodedVisitorData = encoder.encodeToString(-            visitorData.toByteArray(Charsets.UTF_8),+    private fun fetchHomeBootstrap(): YoutubePageAttestationBootstrap {+        val downloader = NewPipe.getDownloader()+        val response = downloader.get(+            YOUTUBE_HOME,+            mapOf(+                "Accept-Language" to listOf("en-US"),+                "Cookie" to listOf(ANONYMOUS_COOKIE),+                "User-Agent" to listOf(SharedWebViewRuntime.USER_AGENT),+            ),         )-        val encodedToken = encoder.encodeToString(token)-        prefs.edit(commit = true) {-            putString(-                videoId,-                "$mintedAt|$credentialIdentity|$encodedVisitorData|$encodedToken",+        if (response.responseCode() != 200) {+            throw SabrProtocolException(+                "YouTube home initialization failed: ${response.responseCode()}",             )         }+        return parseYoutubePageAttestationBootstrap(response.responseBody())     }      companion object {         private const val TAG = "SabrLocalDomPoToken"-        private const val PREFS = "sabr_local_dom_video_token_cache"-        private const val TOKEN_TTL_MS = 6L * 60L * 60L * 1000L-        private const val VISITOR_DATA_TTL_MS = 6L * 60L * 60L * 1000L-        private const val PREWARM_CLIENT_NAME = "WEB"+        private const val YOUTUBE_HOME = "https://www.youtube.com"+        private const val ANONYMOUS_COOKIE = "PREF=hl=en&gl=US"          @Volatile         private var sharedInstance: LocalDomPoTokenProvider? = null
youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrAttestationRetryHandler.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrAttestationRetryHandler.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrAttestationRetryHandler.ktindex 4ca525b689..fbbb185d93 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrAttestationRetryHandler.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrAttestationRetryHandler.kt@@ -5,12 +5,17 @@ import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrAttest  /**  * Maintains the PO-token recovery budget for one SABR media acquisition. On a rejected attestation- * identity it mints a fresh PO token and injects it into the session, mirroring PipePipe's- * `SabrAttestationRetryHandler` (the #92 "rotate rejected SABR attestation identities" fix).+ * identity it mints a fresh PO token and injects it into the session.+ *+ * The [tokenMinter] is invoked with `force=true`: [LocalDomPoTokenProvider] then tears down the+ * burned BotGuard session and re-bootstraps from a fresh home page before minting, so every+ * retry comes from a new attestation identity. Because each retry refreshes the global session,+ * the identity is always fresh again after a rejection episode, including for the next+ * acquisition — no separate exhaustion hook is needed.  */ internal class SabrAttestationRetryHandler(     private val videoId: String,-    private val tokenMinter: ((Boolean) -> ByteArray?)?+    private val tokenMinter: ((Boolean) -> ByteArray?)?, ) {     private var retriesRemaining = MAX_RETRIES 
youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrLocalDomPoTokenUtil.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrLocalDomPoTokenUtil.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrLocalDomPoTokenUtil.ktindex 66e1684b9b..9c4771951d 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrLocalDomPoTokenUtil.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrLocalDomPoTokenUtil.kt@@ -6,32 +6,13 @@ import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonObject import org.schabi.newpipe.extractor.utils.JsonUtils-import org.schabi.newpipe.extractor.utils.getObject-import org.schabi.newpipe.extractor.utils.getString import java.util.Base64 -internal data class SabrAttChallengeData(-    val program: String,-    val globalName: String,-    val interpreterUrl: String,-)--internal fun parseSabrAttChallengeData(rawAttestationData: String): SabrAttChallengeData {-    val challenge = JsonUtils.toJsonObject(rawAttestationData).getObject("bgChallenge")-        ?: throw IllegalArgumentException("Missing bgChallenge in attestation data")-    val interpreterUrl = challenge.getObject("interpreterUrl")-        ?.getString("privateDoNotAccessOrElseTrustedResourceUrlWrappedValue").orEmpty()-    return SabrAttChallengeData(-        program = challenge.getString("program").orEmpty(),-        globalName = challenge.getString("globalName").orEmpty(),-        interpreterUrl = if (interpreterUrl.startsWith("//")) {-            "https:$interpreterUrl"-        } else {-            interpreterUrl-        },-    )-}-+/**+ * Builds the challenge payload handed to `pipepipeSabrRunBotguard` in `sabr_po_token.js`.+ * Only the interpreter payload the page actually inlined is sent; the trusted URL is a hint+ * the JS does not consume.+ */ internal fun buildSabrAttChallengeData(     challengeData: SabrAttChallengeData,     interpreterJavascript: String,@@ -39,10 +20,6 @@ internal fun buildSabrAttChallengeData(     return buildJsonObject {         putJsonObject("interpreterJavascript") {             put("privateDoNotAccessOrElseSafeScriptWrappedValue", interpreterJavascript)-            put(-                "privateDoNotAccessOrElseTrustedResourceUrlWrappedValue",-                challengeData.interpreterUrl,-            )         }         put("program", challengeData.program)         put("globalName", challengeData.globalName)
youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrNgDownloadHelper.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrNgDownloadHelper.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrNgDownloadHelper.ktindex 43de3f20e0..39f5867fac 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrNgDownloadHelper.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrNgDownloadHelper.kt@@ -37,7 +37,7 @@ internal object SabrNgDownloadHelper {         }         val provider = LocalDomPoTokenProvider.shared(context.applicationContext)         val tokenMinter: (Boolean) -> ByteArray? = { force ->-            provider.getPoTokenBytes(videoId, info.getVisitorData(), force)+            provider.getPoTokenBytes(videoId, force)         }         val poToken = tokenMinter(false)         val spec = SabrNgSessionStore.createSourceSpec(
youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SharedWebViewRuntime.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SharedWebViewRuntime.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SharedWebViewRuntime.ktindex a6971313af..a95279e867 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SharedWebViewRuntime.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SharedWebViewRuntime.kt@@ -505,7 +505,7 @@ class SharedWebViewRuntime private constructor(context: Context) {         private const val DEFAULT_TIMEOUT_MS = 30_000L         private const val READY_CALLBACK_ATTEMPT_TIMEOUT_MS = 5_000L         private const val MAX_READY_CALLBACK_ATTEMPTS = 2-        private const val USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " ++        internal const val USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +             "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.3"          @Volatile private var instance: SharedWebViewRuntime? = null
youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/YoutubePageAttestationBootstrap.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/YoutubePageAttestationBootstrap.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/YoutubePageAttestationBootstrap.ktnew file mode 100644index 0000000000..ed9936c1f7--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/YoutubePageAttestationBootstrap.kt@@ -0,0 +1,266 @@+package com.vayunmathur.youpipe.util.sabr++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException+import org.schabi.newpipe.extractor.utils.getObject+import org.schabi.newpipe.extractor.utils.getString++internal enum class YoutubePoTokenBinding {+    CONTENT,+    SESSION,+    NONE,+}++internal data class YoutubePageAttestationBootstrap(+    val visitorData: String,+    val clientName: String,+    val clientVersion: String,+    val binding: YoutubePoTokenBinding,+    val eventId: String,+    val challenge: SabrAttChallengeData,+)++internal data class SabrAttChallengeData(+    val program: String,+    val globalName: String,+    val interpreterJavascript: String?,+    val interpreterUrl: String?,+)++private val bootstrapJson = Json { ignoreUnknownKeys = true; isLenient = true }++/**+ * Parses the attestation bootstrap from YouTube home page HTML (`https://www.youtube.com`).+ *+ * Port of PipePipe's `parseYoutubePageAttestationBootstrap`: the `ytcfg.set({...})` calls carry+ * the visitor data, client version and EVENT_ID, and the `window.ytAtN({...})` call carries the+ * initial BotGuard attestation challenge. Minting against this page-bound challenge (instead of+ * the old `youtubei/v1/att/get` UNBOUND flow) is what makes the server accept the PO token+ * (#565: without it every SABR response stays `status=2` attestation-pending).+ */+@Throws(SabrProtocolException::class)+internal fun parseYoutubePageAttestationBootstrap(pageHtml: String): YoutubePageAttestationBootstrap {+    val configCalls = extractObjectCallArguments(pageHtml, YTCFG_CALLEE)+        .mapNotNull { call ->+            try {+                call to bootstrapJson.parseToJsonElement(call.argument).jsonObject+            } catch (_: Exception) {+                null+            }+        }+    val challengeCall = extractObjectCallArguments(pageHtml, INITIAL_ATTESTATION_CALLEE)+        .asSequence()+        .mapNotNull { call -> parseInitialAttestationChallenge(call.argument)?.let { call to it } }+        .firstOrNull()+        ?: throw SabrProtocolException("YouTube home has no initial attestation challenge")+    val configs = configCalls+        .filter { (call) -> call.start < challengeCall.first.start }+        .map { (_, config) -> config }+    val clientConfig = configs.lastOrNull { it.has("INNERTUBE_CONTEXT") }+        ?: throw SabrProtocolException("YouTube home has no client context")+    val eventId = configs.asSequence()+        .mapNotNull { it.getString("EVENT_ID")?.takeIf(String::isNotEmpty) }+        .lastOrNull()+        ?: throw SabrProtocolException("YouTube home has no EVENT_ID")+    val visitorData = (+        clientConfig.getString("EOM_VISITOR_DATA")?.takeIf(String::isNotEmpty)+            ?: clientConfig.getString("VISITOR_DATA")?.takeIf(String::isNotEmpty)+        )?.replace("%3D", "=", ignoreCase = true)+        ?: throw SabrProtocolException("YouTube home has no anonymous visitor data")+    val client = clientConfig.getObject("INNERTUBE_CONTEXT")?.getObject("client")+        ?: throw SabrProtocolException("YouTube home has no Innertube client context")+    val clientName = client.getString("clientName")?.takeIf(String::isNotEmpty)+        ?: throw SabrProtocolException("YouTube home has no client name")+    if (clientName != "WEB") {+        throw SabrProtocolException("Unsupported YouTube home client: $clientName")+    }+    val clientVersion = client.getString("clientVersion")?.takeIf(String::isNotEmpty)+        ?: throw SabrProtocolException("YouTube home has no client version")+    val watchConfig = clientConfig.getObject("WEB_PLAYER_CONTEXT_CONFIGS")+        ?.getObject("WEB_PLAYER_CONTEXT_CONFIG_ID_KEVLAR_WATCH")+    val experimentFlags = watchConfig?.getString("serializedExperimentFlags")+        ?.let(::parseExperimentFlags)+        .orEmpty()+    val binding = when {+        experimentFlags["html5_generate_content_po_token"] == "true" -> YoutubePoTokenBinding.CONTENT+        experimentFlags["html5_generate_session_po_token"] == "true" -> YoutubePoTokenBinding.SESSION+        watchConfig == null -> YoutubePoTokenBinding.CONTENT+        else -> YoutubePoTokenBinding.NONE+    }+    return YoutubePageAttestationBootstrap(+        visitorData,+        clientName,+        clientVersion,+        binding,+        eventId,+        challengeCall.second,+    )+}++private fun parseInitialAttestationChallenge(argument: String): SabrAttChallengeData? {+    val responseProperty = INITIAL_ATTESTATION_RESPONSE.find(argument) ?: return null+    val quote = responseProperty.groupValues[1].single()+    val rawChallenge = try {+        decodeJavascriptString(argument, responseProperty.range.last + 1, quote)+    } catch (_: IllegalArgumentException) {+        return null+    }+    return try {+        parseSabrAttChallengeData(rawChallenge)+    } catch (_: Exception) {+        null+    }+}++internal fun parseSabrAttChallengeData(rawAttestationData: String): SabrAttChallengeData {+    val challenge = try {+        bootstrapJson.parseToJsonElement(rawAttestationData).jsonObject.getObject("bgChallenge")+    } catch (e: Exception) {+        throw SabrProtocolException("Attestation response has no BotGuard challenge", e)+    } ?: throw SabrProtocolException("Attestation response has no BotGuard challenge")+    val interpreterJavascript = challenge.getObject("interpreterJavascript")+        ?.getString("privateDoNotAccessOrElseSafeScriptWrappedValue")+        ?.takeIf(String::isNotEmpty)+    val rawInterpreterUrl = challenge.getObject("interpreterUrl")+        ?.getString("privateDoNotAccessOrElseTrustedResourceUrlWrappedValue")+        ?.takeIf(String::isNotEmpty)+    val interpreterUrl = rawInterpreterUrl?.let {+        if (it.startsWith("//")) "https:$it" else it+    }+    if (interpreterJavascript == null && interpreterUrl == null) {+        throw SabrProtocolException("Attestation challenge has no interpreter script or URL")+    }+    val program = challenge.getString("program")?.takeIf(String::isNotEmpty)+        ?: throw SabrProtocolException("Attestation challenge has no program")+    val globalName = challenge.getString("globalName")?.takeIf(String::isNotEmpty)+        ?: throw SabrProtocolException("Attestation challenge has no global name")+    return SabrAttChallengeData(program, globalName, interpreterJavascript, interpreterUrl)+}++private data class JavascriptObjectCall(+    val start: Int,+    val argument: String,+)++private fun extractObjectCallArguments(+    source: String,+    callee: String,+): List<JavascriptObjectCall> {+    val arguments = ArrayList<JavascriptObjectCall>()+    var searchFrom = 0+    while (true) {+        val callStart = source.indexOf(callee, searchFrom)+        if (callStart < 0) return arguments+        var openingParenthesis = callStart + callee.length+        while (openingParenthesis < source.length && source[openingParenthesis].isWhitespace()) {+            openingParenthesis+++        }+        if (openingParenthesis >= source.length || source[openingParenthesis] != '(') {+            searchFrom = callStart + callee.length+            continue+        }+        var objectStart = openingParenthesis + 1+        while (objectStart < source.length && source[objectStart].isWhitespace()) objectStart+++        if (objectStart >= source.length || source[objectStart] != '{') {+            searchFrom = openingParenthesis + 1+            continue+        }+        val objectEnd = findJavascriptObjectEnd(source, objectStart)+        if (objectEnd < 0) {+            searchFrom = objectStart + 1+            continue+        }+        arguments.add(JavascriptObjectCall(callStart, source.substring(objectStart, objectEnd + 1)))+        searchFrom = objectEnd + 1+    }+}++private fun findJavascriptObjectEnd(source: String, start: Int): Int {+    var depth = 0+    var quote = '\u0000'+    var escaped = false+    for (index in start until source.length) {+        val character = source[index]+        if (quote != '\u0000') {+            if (escaped) {+                escaped = false+            } else if (character == '\\') {+                escaped = true+            } else if (character == quote) {+                quote = '\u0000'+            }+            continue+        }+        when (character) {+            '\'', '"' -> quote = character+            '{' -> depth+++            '}' -> {+                depth--+                if (depth == 0) return index+            }+        }+    }+    return -1+}++private fun parseExperimentFlags(serializedFlags: String): Map<String, String> {+    return serializedFlags.split('&').associate { part ->+        val separator = part.indexOf('=')+        if (separator < 0) part to "true"+        else part.substring(0, separator) to part.substring(separator + 1)+    }+}++private fun decodeJavascriptString(source: String, start: Int, quote: Char): String {+    val result = StringBuilder()+    var index = start+    while (index < source.length) {+        val character = source[index++]+        if (character == quote) return result.toString()+        if (character != '\\') {+            result.append(character)+            continue+        }+        require(index < source.length) { "Incomplete JavaScript string escape" }+        when (val escaped = source[index++]) {+            'b' -> result.append('\b')+            'f' -> result.append('\u000C')+            'n' -> result.append('\n')+            'r' -> result.append('\r')+            't' -> result.append('\t')+            'v' -> result.append('\u000B')+            'x' -> {+                result.append(readJavascriptHex(source, index, 2).toChar())+                index += 2+            }+            'u' -> {+                result.append(readJavascriptHex(source, index, 4).toChar())+                index += 4+            }+            '\n' -> Unit+            '\r' -> if (index < source.length && source[index] == '\n') index+++            else -> result.append(escaped)+        }+    }+    throw IllegalArgumentException("Unterminated JavaScript string")+}++private fun readJavascriptHex(source: String, start: Int, length: Int): Int {+    require(start + length <= source.length) { "Incomplete hexadecimal escape" }+    var value = 0+    repeat(length) { offset ->+        val digit = source[start + offset].digitToIntOrNull(16)+            ?: throw IllegalArgumentException("Invalid hexadecimal escape")+        value = value * 16 + digit+    }+    return value+}++private fun JsonObject.has(key: String): Boolean = containsKey(key)++private const val YTCFG_CALLEE = "ytcfg.set"+private const val INITIAL_ATTESTATION_CALLEE = "window.ytAtN"+private val INITIAL_ATTESTATION_RESPONSE = Regex("['\"]R['\"]\\s*:\\s*(['\"])")
youpipe/src/main/res/values/strings.xml
diff --git a/youpipe/src/main/res/values/strings.xml b/youpipe/src/main/res/values/strings.xmlindex 3e23297ed7..64b4d34da3 100644--- a/youpipe/src/main/res/values/strings.xml+++ b/youpipe/src/main/res/values/strings.xml@@ -37,6 +37,10 @@      <!-- Video load error dialog text explaining YouTube may have blocked anonymous watch from IP -->     <string name="video_load_error">Video load error - Youtube may have blocked anonymous watch access from this IP</string>+    <!-- Snackbar: playback stopped mid-video (e.g. the stream could not be fetched). Sentence -->+    <string name="playback_error">Playback stopped unexpectedly. Please try again.</string>+    <!-- Snackbar: a subscription backup file is in an unsupported (e.g. encrypted) format. Sentence -->+    <string name="restore_unsupported_format">This backup file format is not supported.</string>     <!-- Button: go back from error dialog. Verb phrase -->     <string name="action_go_back">Go Back</string>     <!-- Tab label: comments section under video. Noun plural -->
youpipe/src/test/java/com/vayunmathur/youpipe/util/AttestationBootstrapTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/AttestationBootstrapTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/AttestationBootstrapTest.ktnew file mode 100644index 0000000000..d27e75a0cc--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/AttestationBootstrapTest.kt@@ -0,0 +1,106 @@+package com.vayunmathur.youpipe.util++import com.vayunmathur.youpipe.util.sabr.YoutubePoTokenBinding+import com.vayunmathur.youpipe.util.sabr.parseSabrAttChallengeData+import com.vayunmathur.youpipe.util.sabr.parseYoutubePageAttestationBootstrap+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNull++/**+ * Offline regression tests for the home-page attestation bootstrap (#565).+ *+ * The fixtures reproduce the shape of `https://www.youtube.com` HTML that matters here:+ * `ytcfg.set({...})` configs (visitor data, client version, EVENT_ID, experiment flags) and+ * the `window.ytAtN({...})` initial attestation challenge. Minting against this page-bound+ * challenge is what makes the server accept SABR PO tokens; the old `att/get` UNBOUND flow+ * left every response attestation-pending.+ */+class AttestationBootstrapTest {++    private fun homeHtml(+        visitorData: String = "CgtWMuc2hlbGxvIBD bundle",+        eventId: String = "EVENT123",+        flags: String = "html5_generate_content_po_token=true&other_flag=false",+        program: String = "PROG",+        globalName: String = "GLOB",+        interpreter: String = "https://www.youtube.com/s/desktop/abc/botguard.js",+    ): String {+        val config = """{"INNERTUBE_CONTEXT":{"client":{"clientName":"WEB","clientVersion":"2.20250901.00.00"}},"VISITOR_DATA":"$visitorData","EVENT_ID":"$eventId","WEB_PLAYER_CONTEXT_CONFIGS":{"WEB_PLAYER_CONTEXT_CONFIG_ID_KEVLAR_WATCH":{"serializedExperimentFlags":"$flags"}}}"""+        val challengeInner = """{"bgChallenge":{"program":"$program","globalName":"$globalName","interpreterUrl":{"privateDoNotAccessOrElseTrustedResourceUrlWrappedValue":"$interpreter"}}}"""+        // window.ytAtN({"R":"<challenge-json>"}) with the challenge JSON JS-escaped.+        val escaped = challengeInner.replace("\\", "\\\\").replace("\"", "\\\"")+        return "<html><head><script>ytcfg.set($config);</script></head>" ++            "<body><script>window.ytAtN({\"R\":\"$escaped\"});</script></body></html>"+    }++    @Test+    fun `parses content binding bootstrap`() {+        val bootstrap = parseYoutubePageAttestationBootstrap(homeHtml())+        assertEquals("CgtWMuc2hlbGxvIBD bundle", bootstrap.visitorData)+        assertEquals("WEB", bootstrap.clientName)+        assertEquals("2.20250901.00.00", bootstrap.clientVersion)+        assertEquals(YoutubePoTokenBinding.CONTENT, bootstrap.binding)+        assertEquals("EVENT123", bootstrap.eventId)+        assertEquals("PROG", bootstrap.challenge.program)+        assertEquals("GLOB", bootstrap.challenge.globalName)+        assertEquals(+            "https://www.youtube.com/s/desktop/abc/botguard.js",+            bootstrap.challenge.interpreterUrl+        )+        assertNull(bootstrap.challenge.interpreterJavascript)+    }++    @Test+    fun `parses session binding bootstrap`() {+        val bootstrap = parseYoutubePageAttestationBootstrap(+            homeHtml(flags = "html5_generate_session_po_token=true")+        )+        assertEquals(YoutubePoTokenBinding.SESSION, bootstrap.binding)+    }++    @Test+    fun `missing watch config defaults to content binding`() {+        val config = """{"INNERTUBE_CONTEXT":{"client":{"clientName":"WEB","clientVersion":"1.0"}},"VISITOR_DATA":"V","EVENT_ID":"E"}"""+        val html = "<script>ytcfg.set($config);</script>" ++            "<script>window.ytAtN({\"R\":\"{\\\"bgChallenge\\\":{\\\"program\\\":\\\"P\\\",\\\"globalName\\\":\\\"G\\\",\\\"interpreterUrl\\\":{\\\"privateDoNotAccessOrElseTrustedResourceUrlWrappedValue\\\":\\\"https://x/y.js\\\"}}}\"});</script>"+        assertEquals(+            YoutubePoTokenBinding.CONTENT,+            parseYoutubePageAttestationBootstrap(html).binding+        )+    }++    @Test+    fun `no supported binding flag yields NONE`() {+        val bootstrap = parseYoutubePageAttestationBootstrap(+            homeHtml(flags = "other_flag=false")+        )+        assertEquals(YoutubePoTokenBinding.NONE, bootstrap.binding)+    }++    @Test+    fun `missing challenge throws`() {+        assertFailsWith<Exception> {+            parseYoutubePageAttestationBootstrap("<html><body>no challenge here</body></html>")+        }+    }++    @Test+    fun `inline interpreter javascript is preferred when present`() {+        val challenge = parseSabrAttChallengeData(+            """{"bgChallenge":{"program":"P","globalName":"G",”interpreterJavascript”:{"privateDoNotAccessOrElseSafeScriptWrappedValue":"var x=1;"}}}"""+                .replace("”", "\"")+        )+        assertEquals("var x=1;", challenge.interpreterJavascript)+        assertNull(challenge.interpreterUrl)+    }++    @Test+    fun `protocol-relative interpreter url is absolutized`() {+        val challenge = parseSabrAttChallengeData(+            """{"bgChallenge":{"program":"P","globalName":"G","interpreterUrl":{"privateDoNotAccessOrElseTrustedResourceUrlWrappedValue":"//www.youtube.com/x.js"}}}"""+        )+        assertEquals("https://www.youtube.com/x.js", challenge.interpreterUrl)+    }+}
youpipe/src/test/java/com/vayunmathur/youpipe/util/SubscriptionBackupTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/SubscriptionBackupTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/SubscriptionBackupTest.ktnew file mode 100644index 0000000000..42f4b85fd6--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/SubscriptionBackupTest.kt@@ -0,0 +1,29 @@+package com.vayunmathur.youpipe.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class SubscriptionBackupTest {++    @Test+    fun `plain subscription array decodes`() {+        val json = """[{"id":3,"name":"Some Channel","channelID":"UC123","avatarURL":"https://x/y.jpg"}]"""+        val subs = decodeSubscriptionBackup(json)+        assertEquals(1, subs!!.size)+        assertEquals("Some Channel", subs[0].name)+        assertEquals("UC123", subs[0].channelID)+    }++    @Test+    fun `salted envelope returns null instead of throwing`() {+        // #565: encrypted/salted envelope written by another client.+        val json = """{"version":1,"salt":"fOK43kW1Xabc==","data":"..."}"""+        assertNull(decodeSubscriptionBackup(json))+    }++    @Test+    fun `empty object returns null instead of throwing`() {+        assertNull(decodeSubscriptionBackup("""{}"""))+    }+}