Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
78e150e
feat(profiles): send stale PIN profiles back to profile selection
Rhainland Oct 1, 2026
dcd7805
fix(notifications): resume realtime after the profile is re-verified
Rhainland Oct 1, 2026
e910c0d
feat(realtime): refresh access-dependent screens when access changes
Rhainland Oct 1, 2026
d737d4e
test(auth): cover the quiet refresh on token_refresh_required
Rhainland Oct 1, 2026
e02c0e0
fix(realtime): refresh once when both events sockets report one acces…
Rhainland Oct 1, 2026
02ad28a
fix(profiles): log only the exception class when recovery init fails
Rhainland Oct 2, 2026
348998c
fix(detail): show the unavailable state when an access change hides t…
Rhainland Oct 2, 2026
2fd8178
fix(profiles): re-check a deferred profile prompt when remote playbac…
Rhainland Oct 2, 2026
b92fb7e
fix(tv): refresh library pages when the viewer's access changes
Rhainland Oct 2, 2026
a356013
fix(tv): re-probe library collections after an access change
Rhainland Oct 2, 2026
df797b6
fix(detail): reload a refused title when access changes again
Rhainland Oct 2, 2026
0716126
fix(detail): keep a refused title hidden when the full load runs again
Rhainland Oct 2, 2026
f23df3a
fix(realtime): apply access changes a screen missed while away
Rhainland Oct 5, 2026
1afcbfd
fix(detail): reload past a pre-change warm-up after an access change
Rhainland Oct 5, 2026
094daf9
fix(tv): skip a pre-change warm-up when an access change reruns the f…
Rhainland Oct 6, 2026
0cb7b76
fix(realtime): check the library list for an access change after the …
Rhainland Oct 6, 2026
b7498ff
fix(realtime): refresh for a change reported by a socket opened after…
Rhainland Oct 7, 2026
e61a69b
fix(detail): keep an older quiet refresh from overwriting a newer one
Rhainland Oct 7, 2026
159dd68
fix(tv): let only the newest library-list, filters, and collections l…
Rhainland Oct 7, 2026
bb10943
fix(tv): keep a watched change from restoring an older resume position
Rhainland Oct 7, 2026
9025078
Merge branch 'main' into fix/profile-verification-recovery
Quick104 Oct 10, 2026
5d34946
fix(profiles): return to the server list from a picker opened while a…
Quick104 Oct 10, 2026
9181a20
fix(search): keep an older search from overwriting the access-change …
Quick104 Oct 10, 2026
f2e3aa8
fix(collections): let only the newest collections load publish
Quick104 Oct 10, 2026
5805bc6
fix(libraries): keep a pending facet load from refilling facets after…
Quick104 Oct 10, 2026
32e759c
fix(tv): declare the library page's load jobs before init
Quick104 Oct 10, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package org.siloserver.silo.common.ui

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import org.siloserver.silo.network.AccessChangeCursor
import org.siloserver.silo.network.AccessChangeSignals

/**
* Runs [onChanged] each time the server reports that the viewer's access
* changed (access group, permissions, or playback-quality override) while this
* composable is on screen, or, with a [AccessChangeCursor], since it was last
* on screen. Screens use it to refetch libraries, search results,
* details, and collections the new policy may have added or removed.
*
* Inert against a server that never reports access changes.
*/
@Composable
fun OnViewerAccessChanged(
signals: AccessChangeSignals,
/**
* The retained ViewModel's cursor. With it, a change reported while this
* screen was out of composition (another destination in front, another
* tab showing) runs [onChanged] as soon as the screen returns.
*/
cursor: AccessChangeCursor? = null,
onChanged: () -> Unit,
) {
val latest by rememberUpdatedState(onChanged)
LaunchedEffect(signals, cursor) {
val changes = if (cursor != null) signals.changes(cursor) else signals.changes
changes.collect { latest() }
}
}

/**
* A key that moves on each reported access change, for `produceState` and
* `LaunchedEffect` loaders that should re-run under the new policy.
*/
@Composable
fun rememberViewerAccessKey(signals: AccessChangeSignals): Int {
var key by remember(signals) { mutableIntStateOf(0) }
OnViewerAccessChanged(signals) { key++ }
return key
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package org.siloserver.silo.common.network

import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.siloserver.silo.network.AccessChangeSignals
import org.siloserver.silo.network.AuthScopeSnapshot
import org.siloserver.silo.network.CleartextOriginConsent
import org.siloserver.silo.network.TokenManager
import org.siloserver.silo.network.TokenManagerImpl
import org.siloserver.silo.network.apiv2.ApiV2Gate
import org.siloserver.silo.network.apiv2.EventsSocketV2Api
import org.siloserver.silo.network.canonicalHttpOrigin
import org.siloserver.silo.network.createSiloClient
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

/**
* The events socket's access-change notice (a frame, then close code 4001)
* reaches [AccessChangeSignals] once per connection, and a server that never
* sends it leaves the signals untouched.
*/
class EventsSocketAccessChangeTest {

@Test
fun `access_changed frame and 4001 close report one access change`() = runBlocking {
val frames = connectOnce { socket ->
socket.send("""{"type":"access_changed"}""")
socket.close(4001, "access_changed")
}

assertEquals(1L, frames.signals.revision.value)
assertTrue(frames.received.any { it.contains("access_changed") })
}

@Test
fun `a 4001 close alone reports the access change`() = runBlocking {
val frames = connectOnce { socket -> socket.close(4001, "access_changed") }

assertEquals(1L, frames.signals.revision.value)
}

@Test
fun `an ordinary close reports nothing`() = runBlocking {
val frames = connectOnce { socket ->
socket.send("""{"type":"subscribed","channel":"catalog"}""")
socket.close(1000, "bye")
}

assertEquals(0L, frames.signals.revision.value)
}

private class Outcome(val signals: AccessChangeSignals, val received: List<String>)

/** [afterSubscribe] runs once the client's subscribe frame arrives, as the server's recheck would. */
private suspend fun connectOnce(afterSubscribe: (WebSocket) -> Unit): Outcome {
val server = MockWebServer()
server.enqueue(
MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json")
.setBody("""{"ticket":"opaque-proof","expires_in":20,"max_connection_seconds":300,"protocol":"silo.events.v2"}"""),
)
server.enqueue(
MockResponse()
.withWebSocketUpgrade(
object : WebSocketListener() {
override fun onMessage(webSocket: WebSocket, text: String) = afterSubscribe(webSocket)
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
webSocket.close(code, reason)
}
},
)
.addHeader("Sec-WebSocket-Protocol", "silo.events.v2"),
)
server.start()
val signals = AccessChangeSignals()
val tokens = scopedTokens(server.url("/").toString())
val approvedOrigin = canonicalHttpOrigin(server.url("/").toString())
val httpClient = createSiloClient(
tokenManager = tokens,
cleartextOriginConsent = object : CleartextOriginConsent {
override suspend fun isApproved(origin: String): Boolean = origin == approvedOrigin
},
accessChangeSignals = signals,
)
try {
val received = withTimeout(10_000) {
EventsSocketV2Api(httpClient, tokens, ApiV2Gate.Unrestricted, signals)
.frames(listOf("catalog"))
.toList()
}
return Outcome(signals, received)
} finally {
httpClient.close()
server.shutdown()
}
}

private suspend fun scopedTokens(serverUrl: String): TokenManager {
val delegate = TokenManagerImpl().apply {
setServerUrl(serverUrl)
saveTokens("ACCESS", "refresh", 3_600)
setProfileIdentity("profile-1", "PROFILE_TOKEN")
}
val active = AuthScopeSnapshot(
serverId = "server-1",
profileId = "profile-1",
serverUrl = serverUrl,
profileToken = "PROFILE_TOKEN",
)
return object : TokenManager by delegate {
override suspend fun snapshotCurrentScope(): AuthScopeSnapshot = active
override suspend fun getAccessTokenForScope(scope: AuthScopeSnapshot): String? =
"ACCESS".takeIf { scope == active }
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,15 @@ class SiloApplication : Application(), Configuration.Provider, SingletonImageLoa
koinApp.koin.get<org.siloserver.silo.repository.ImageCapabilitiesSession>().start(
kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.IO),
)
// Profile-verification recovery: clears a profile whose PIN token the
// server stopped accepting (after an access change), including when
// background work hits it first. Guarded — never load-bearing.
runCatching {
koinApp.koin.get<org.siloserver.silo.repository.ProfileVerificationRecovery>()
}.onFailure {
// Class name only: the exception chain can carry auth or server data.
android.util.Log.w("SiloApplication", "Profile verification recovery init failed: ${it::class.simpleName}")
}
// Drive notifications realtime off the app foreground lifecycle. Guarded:
// it's a foreground accelerator, never load-bearing for cold start.
runCatching {
Expand Down Expand Up @@ -99,6 +108,7 @@ class SiloApplication : Application(), Configuration.Provider, SingletonImageLoa
org.siloserver.silo.android.home.HomeRealtimeForegroundStarter(
coordinator = koinApp.koin.get(),
profileRepository = koinApp.koin.get(),
accessCheck = koinApp.koin.getOrNull(),
).register()
}.onFailure {
android.util.Log.w("SiloApplication", "Home realtime starter init failed", it)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,7 @@ val androidModule = module {
viewModel { SignupViewModel(get()) }
viewModel { InviteClaimViewModel(get(), get()) }
viewModel { OnboardingTourViewModel(get(), get(), get(), get(), get()) }
viewModel { ProfileSelectionViewModel(get(), get()) }
viewModel { ProfileSelectionViewModel(get(), get(), profileVerificationRecovery = getOrNull()) }
viewModel { CreateProfileViewModel(get()) }
viewModel { EditProfileViewModel(get()) }
viewModel { ServerListViewModel(get(), get(), get()) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import org.siloserver.silo.repository.ForegroundAccessCheck
import org.siloserver.silo.repository.HomeRealtimeCoordinator
import org.siloserver.silo.repository.ProfileRepository

Expand All @@ -18,14 +19,18 @@ import org.siloserver.silo.repository.ProfileRepository
* (ProfileRepository.profileSwitches)
* reconnects so the coordinator's profile filter tracks the new session.
* REST stays the source of truth; a dead socket just means pull behavior.
* Returning from the background runs [accessCheck], because a socket that was
* closed while stopped cannot report an access change made in that time.
*/
class HomeRealtimeForegroundStarter(
private val coordinator: HomeRealtimeCoordinator,
private val profileRepository: ProfileRepository,
private val accessCheck: ForegroundAccessCheck? = null,
) : DefaultLifecycleObserver {

private var realtimeScope: CoroutineScope? = null
private var foregroundScope: CoroutineScope? = null
private var stoppedSinceStart = false

fun register() {
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
Expand All @@ -34,9 +39,14 @@ class HomeRealtimeForegroundStarter(
override fun onStart(owner: LifecycleOwner) {
startRealtime()
observeProfileSwitches()
if (stoppedSinceStart) {
stoppedSinceStart = false
foregroundScope?.launch { accessCheck?.afterReturnToForeground() }
}
}

override fun onStop(owner: LifecycleOwner) {
stoppedSinceStart = true
stopRealtime()
foregroundScope?.cancel()
foregroundScope = null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ import org.siloserver.silo.common.player.video.VideoPlayerRouteArgs
import org.siloserver.silo.common.settings.CardPresentationStore
import org.siloserver.silo.common.settings.OverlayPrefsStore
import org.siloserver.silo.network.TokenManager
import org.siloserver.silo.repository.ProfilePromptAction
import org.siloserver.silo.repository.ProfileVerificationRecovery
import org.koin.compose.koinInject
import org.koin.compose.viewmodel.koinViewModel

Expand All @@ -135,6 +137,33 @@ import org.koin.compose.viewmodel.koinViewModel
*/
private const val DisplayedDetailContentIdKey = "displayedDetailContentId"

/** The profile picker and its screens, where a prompt has nothing to add. */
private val ProfilePromptPickerRoutes: Set<String> = setOf(
Route.ProfileSelection.route,
Route.CreateProfile.route,
Route.EditProfile.ROUTE,
)

/**
* Destinations a profile-verification prompt waits behind: playback and reading
* keep going on the session they started with, and the sign-in and server
* screens have no profile in use.
*/
private val ProfilePromptDeferredRoutes: Set<String> = setOf(
Route.Player.ROUTE,
Route.AudiobookPlayer.ROUTE,
Route.BookReader.ROUTE,
Route.SiloCastRemote.route,
Route.Login.route,
Route.ServerSetup.route,
Route.ServerSetupPrefilled.ROUTE,
Route.ServerList.route,
Route.Setup.route,
Route.Signup.route,
Route.PairDevice.ROUTE,
Route.InviteClaim.ROUTE,
)

/** Page-to-page cross-fade duration (ms). Snappier than Compose Nav's 700ms default. */
private const val PageFadeDurationMs = 200

Expand Down Expand Up @@ -266,6 +295,55 @@ fun AppNavigation(
}
}

// The server stopped accepting the active profile's PIN proof (an admin
// changed the account's access). The recovery has already cleared the
// stale profile selection, but not the sign-in; send the user to the
// profile picker to choose a profile and enter its PIN again. Playback and
// the sign-in screens are not interrupted: the prompt waits until the user
// leaves them (or a remote-playback overlay ends), and is dropped after a
// sign-out, a server switch, or a profile pick.
val profileVerificationRecovery: ProfileVerificationRecovery = koinInject()
LaunchedEffect(Unit) {
// promptChecks re-emits when a remote-playback overlay ends, so a
// prompt deferred behind it does not wait for the next navigation.
kotlinx.coroutines.flow.combine(
profileVerificationRecovery.promptChecks,
navController.currentBackStackEntryFlow,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
) { prompt, entry -> prompt to entry.destination.route }
.collect { (prompt, route) ->
if (prompt == null) return@collect
when (
profileVerificationRecovery.actionFor(
prompt = prompt,
currentRoute = route,
deferRoutes = ProfilePromptDeferredRoutes,
pickerRoutes = ProfilePromptPickerRoutes,
)
) {
ProfilePromptAction.Defer -> Unit
// Already on the picker: it reloads itself, and a PIN
// being typed is kept.
ProfilePromptAction.AlreadyThere,
Comment thread
Quick104 marked this conversation as resolved.
Resolved
ProfilePromptAction.Drop,
-> profileVerificationRecovery.consume(prompt)
ProfilePromptAction.Navigate -> {
profileVerificationRecovery.consume(prompt)
navController.navigate(Route.ProfileSelection.route) {
popUpTo(0) { inclusive = true }
launchSingleTop = true
}
// Same per-profile teardown as Switch Profile, after
// leaving the shell so it does not repaint first.
overlayPrefsStore.clear()
activeProfileStore.reset()
cardPresentationStore.clear()
seekIntervalStore.clear()
titleArtStore.clear()
}
}
}
}

fun navigateExternalRoute(route: String) {
// An external link to a TAB (silo://downloads) must switch tabs,
// not push a second copy of that tab. A duplicate tab entry also
Expand Down Expand Up @@ -827,6 +905,23 @@ fun AppNavigation(

// ---- Profile selection ----
composable(Route.ProfileSelection.route) {
// Switch Profile opens the picker above Main so Back can cancel it.
// Once profile recovery has cleared the selection (a stale PIN
// proof), Main has no profile to return to and every request there
// would fail, so Back leaves the app, as it does when the picker is
// the first screen. A picker opened from the server list or a
// sign-in screen (adding a server) has no profile yet either; Back
// there still returns to that screen.
val pickerActivity = androidx.activity.compose.LocalActivity.current
val selectedProfileId = serverRegistry.activeEntry.collectAsState().value?.profileId
val previousRoute = navController.previousBackStackEntry?.destination?.route
androidx.activity.compose.BackHandler(
enabled = selectedProfileId.isNullOrBlank() &&
previousRoute != null &&
previousRoute !in ProfilePromptDeferredRoutes,
) {
pickerActivity?.finish()
}
ProfileSelectionScreen(
onNavigateToHome = {
// The switch-profile paths dropped the per-profile card
Expand Down
Loading
Loading