Skip to content

fix(auth): use native branding for server names - #192

Merged
Quick104 merged 1 commit into
mainfrom
codex/native-branding-server-name
Aug 11, 2026
Merged

Quick104 merged 1 commit into
mainfrom
codex/native-branding-server-name

Conversation

@Quick104

@Quick104 Quick104 commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The Android phone and TV clients refresh saved server names from GET /api/v1/health.server_name. That field is currently backed by the Jellyfin compatibility setting, so native clients can show “StreamApp” even when Jellyfin compatibility is disabled.

Fixes #191.
Related to Silo-Server/silo-server#553.

Approach

  • Add a shared client for the public GET /api/v1/theme/branding endpoint.
  • Prefer branding.server_name, with GET /api/v1/health as an older-server fallback.
  • Trim and reject blank names.
  • Keep user rename overrides and URL fallback behavior unchanged.
  • Guard the registry update so a delayed response cannot rename a newly activated server.

Validation

  • Focused shared tests for branding decoding and name resolution passed.
  • :shared:testDebugUnitTest passed.
  • :androidApp:testDebugUnitTest passed.
  • :androidTvApp:testDebugUnitTest passed.
  • :androidApp:assembleDebug passed.
  • :androidTvApp:assembleDebug passed.
  • :shared:lintDebug and :androidTvApp:lintDebug passed.
  • :androidApp:lintDebug remains blocked by 9 pre-existing findings; the first is MissingPermission in PushNotificationPresenter.kt:119. No finding references a changed file.

Risk

Low. The new lookup is best-effort and uses a public endpoint. Servers without that endpoint continue through the existing health request, while failures preserve the current saved or URL-derived display behavior.

AI use

Implemented and validated with Codex on behalf of the repository maintainer.

Summary by CodeRabbit

  • New Features

    • Added support for displaying a server’s native branding name.
    • Server names now prioritize branding information, with health-based and existing fallback behavior preserved.
    • Added safeguards to prevent outdated server responses from overwriting current information.
  • Bug Fixes

    • Blank branding names now correctly fall back to other available names.
    • Improved server-name updates when switching between servers.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 461145d4-bfad-4f81-b0c2-5ac77c140252

📥 Commits

Reviewing files that changed from the base of the PR and between 4ae38ab and fd92f2e.

📒 Files selected for processing (7)
  • shared/src/commonMain/kotlin/org/siloserver/silo/di/NetworkModule.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/server/ServerEntry.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/api/BrandingApi.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/repository/AuthRepository.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/network/api/BrandingApiTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/repository/AuthRepositoryServerNameTest.kt

📝 Walkthrough

Walkthrough

Added BrandingApi to fetch native server branding. AuthRepository now prefers the branding name, falls back to health, normalizes names, and avoids stale updates. Dependency injection and focused tests were added.

Changes

Native branding integration

Layer / File(s) Summary
Branding API and registration
shared/src/commonMain/kotlin/org/siloserver/silo/network/api/BrandingApi.kt, shared/src/commonMain/kotlin/org/siloserver/silo/di/NetworkModule.kt, shared/src/commonTest/kotlin/org/siloserver/silo/network/api/BrandingApiTest.kt
Added BrandingStatus and BrandingApi for /api/v1/theme/branding, registered the API with Koin, and tested JSON decoding with a mocked HTTP engine.
Server-name refresh integration
shared/src/commonMain/kotlin/org/siloserver/silo/repository/AuthRepository.kt, shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt, shared/src/commonMain/kotlin/org/siloserver/silo/model/server/ServerEntry.kt
AuthRepository checks branding before health, uses health when branding is unavailable or blank, normalizes names, and updates only the active server. Koin resolves the new optional dependency. Documentation distinguishes native branding from the legacy health name.
Server-name behavior tests
shared/src/commonTest/kotlin/org/siloserver/silo/repository/AuthRepositoryServerNameTest.kt
Added tests and fakes for branding precedence, health fallback, blank names, suppressed health requests, and stale responses after an active-server change.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant AuthRepository
  participant BrandingApi
  participant HealthApi
  participant ServerRegistry
  AuthRepository->>BrandingApi: Request native branding
  alt Branding is unavailable or blank
    AuthRepository->>HealthApi: Request health name
    HealthApi-->>AuthRepository: Return health name
  end
  AuthRepository->>ServerRegistry: Save the usable fetched name
Loading

Suggested reviewers: rxwatcher

✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/native-branding-server-name

Comment @coderabbitai help to get the list of available commands.

@Quick104
Quick104 marked this pull request as ready for review August 11, 2026 01:28
@Quick104
Quick104 merged commit 9dace7f into main Aug 11, 2026
0 of 2 checks passed
@Quick104
Quick104 deleted the codex/native-branding-server-name branch August 11, 2026 01:28

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fd92f2e58f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

?.data
?.serverName
.usableServerName()
val resolvedName = brandingName ?: (healthApi?.checkHealth() as? ApiResult.Success)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve native names when branding fails transiently

When a modern server's branding request temporarily times out, returns a 5xx, or fails to decode, brandingName becomes null and this unconditional fallback persists health.server_name instead. Since that health field is compatibility-backed and may be “StreamApp,” a transient branding failure can overwrite an already-correct native name with the exact incorrect value this change is intended to avoid. Only use health for an older-server signal such as a 404; other branding failures should preserve the saved name.

Useful? React with 👍 / 👎.

Comment on lines +213 to +216
val brandingName = (brandingApi?.getBranding() as? ApiResult.Success)
?.data
?.serverName
.usableServerName()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Refresh existing phone registry entries

On phone, the only production path that reaches this branding lookup is setServerUrl, which runs while adding or accepting a server; ServerListViewModel has no AuthRepository dependency and never calls refreshActiveServerName when the list opens or a saved server is selected. A repo-wide production call-site search finds only the TV server list caller, so phone users upgrading with a persisted compatibility-backed fetchedName will continue seeing that stale name indefinitely unless they re-add the server. Trigger this refresh from the phone server-list or switch flow as well.

Useful? React with 👍 / 👎.

RXWatcher added a commit that referenced this pull request Aug 11, 2026
…e 401 (#205)

* fix(auth): refresh an expiring token before spending it, not after the 401

Every TokenManager has recorded an access-token deadline at save time since
the beginning — `TokenManagerImpl.tokenExpiry`, `EncryptedTokenManagerImpl`'s
`tokenExpiryEpochMs`, `TemporaryAuthScope.expiresAtEpochMs` — and no caller
has ever read any of them. Expiry was therefore only ever discovered by a 401:
the first request past the deadline was sent with a token the server was
always going to reject, and the interceptor then refreshed and retried it.

The result is correct and invisible, which is why it survived. It is not free.
On a live device `/api/v1/home/sections` was 309 × 200 against 42 × 401, every
401 immediately followed by `token refresh required / started / succeeded` —
12% of home loads paying two round trips for one, on the screen whose latency
the viewer actually sees. `ws-ticket` shows the same shape at 17/4.

`TokenManager` gains `accessTokenExpiresWithin(marginMs)`, defaulting to false
so that a manager which cannot answer keeps today's reactive behaviour exactly
rather than guessing — a wrong "yes" would spend a refresh token on every
request. Both real implementations answer from the deadline they already
store, and both exclude the identity they do not own: the in-memory one
declines for a temporary overlay it tracks no expiry for, and the Android one
answers from the overlay's own deadline rather than falling through to the
saved account's.

The plugin's 401 path is unchanged. Its refresh body is lifted verbatim into
`refreshScopeOnce()` and called from both paths, so the new one cannot drift
from it — every guard in there (mid-flight server switch, a sign-out landing
while the round trip is open, a dead temporary credential generation) exists
because it was needed once, and a second copy would be a second place to
forget one. The proactive path is deliberately narrow: authenticated requests
on the active scope only, never the auth endpoints themselves, never a pinned
outbox op.

Verified: :shared:testDebugUnitTest 1015 tests and
:android-shared:testDebugUnitTest 1101 tests, both 0 failures — including the
existing SiloAuthPluginRefreshFailureTest and SiloAuthPluginPinTest, which are
what prove the 401 path still behaves as it did.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(auth): stop the proactive refresh storming, and never spend a repudiated bearer

Adversarial review of the proactive-refresh change found four hazards, none
of which the original tests could have caught.

1. The 60s margin was fixed, so a server issuing tokens shorter than the
   margin was inside the refresh window from the instant it issued one:
   every request refreshed and every refresh rotated the refresh token.
   `shouldRefreshProactively` now clamps the margin to half the token's own
   lifetime, so a 30s token refreshes at its half-life instead of on every
   call. Lifetime is recorded and persisted alongside the expiry.

2. A rejected proactive refresh tore the session down and then sent the
   original request anyway, still carrying the old bearer. The access token
   often has time left, so the server could honour a write for a session the
   client had already ended. `refreshScopeOnce` now reports a `RefreshOutcome`
   and the proactive path strips the repudiated header instead of spending it.

3. The expiry question was answered by whichever identity was installed at
   check time while the refresh spent the scope captured earlier, so an
   overlay beginning or ending in between charged one identity's rejection
   against the other. The generation is now read first and must match the
   request's scope, and must still match after the check.

4. TemporaryAuthScope.expiresAtEpochMs is the SESSION deadline, but the
   scoped save overwrote it with the access-token expiry and the new expiry
   probe read it as one — a four-hour session read as a four-hour token, and
   every refresh silently extended the guest session. Access-token expiry and
   lifetime are now their own fields, null until a refresh reports them.

Tests: the half-life clamp and both hazards, each mutation-checked (removing
the clamp fails the storm tests; removing the header strip fails the
repudiation test). shared 1015 -> 1024, all green; android-shared 1101 and
androidTvApp 976 unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(auth): fail a repudiated request instead of sending it anonymously

Second review round against the previous commit closed all four original
findings but raised three against the fix itself.

Stripping only the bearer still SENT the request. An optionally-authenticated
endpoint would accept the anonymous remainder, so a repudiated write could
still land — and the profile headers were left attached besides. Drop every
credential header and fail the call with `silo_auth_credentials_repudiated`,
matching what a pinned request with no usable token already does. The test now
uses a write against a deliberately permissive endpoint and asserts the call
never reaches the server, rather than asserting a header was absent from a
request that still went out.

An unknown lifetime now stays reactive rather than falling back to the full
margin. Credentials stored before this field existed load without one, and
because a 5xx refresh never persists a lifetime, the old fallback would retry
a proactive refresh on every request for the length of an outage. They migrate
on the next successful issuance. An already-expired token stays due either
way — there is nothing left to conserve.

Temporary playback keeps its access-token lifetime: DeviceLoginPollResponse
does carry expires_in, so the previous comment claiming otherwise was wrong
and the overlay was needlessly reactive-only until its first 401.

shared 1024, android-shared 1101, androidTvApp 976, all green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(auth): keep a repudiated session from failing downloads and public reads

Third review round closed all three of the previous round's findings and
raised two more against the throw itself.

A repudiated session mid-download was permanently failing the download.
DownloadWorker calls Ktor directly and classifies 401 as retriable, but the
new exception fell into its generic `catch (e: Throwable)`, which deletes the
partial and marks the download Failed — potentially gigabytes discarded
because a refresh token expired. The classification is now a named predicate,
`downloadAuthFailureIsRetriable`, so it is unit-testable without a worker
harness, and it is deliberately narrower than the IllegalStateException that
SiloAuthUnavailableException extends: widening it that far would make a
genuine 404 retry forever.

Failing the request also punished endpoints that never needed the bearer.
/health and the relative setup/signup-status calls do not opt out of auth, so
the header is merely attached globally; with a live access token they would
have answered fine. The rule now matches the harm: credentials always come
off, and only unsafe methods are blocked. An anonymous write could be accepted
as anonymous; an anonymous read either works or 401s exactly as before.

Both sentinels are now a typed SiloAuthUnavailableException rather than a bare
IllegalStateException carrying a magic string, so callers can classify them
without matching on message text.

Also confirmed by review rather than assumed: the throw happens inside Send
before proceed(), so no engine connection is ever acquired and the refresh
mutex has already unwound; pinned outbox calls never enter the proactive path;
and safeApiCall maps both sentinels to ApiResult.NetworkError.

shared 1025, android-shared 1103, androidTvApp 976, all green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(auth): opt public calls out of auth instead of loosening the repudiation rule

Fourth review round closed both previous findings but rejected the method-based
fallback, correctly.

Two things I asserted were wrong. "Safe methods do not change server state" is
false in this codebase: GET /downloads/{id}/file moves the download to
completed server-side, and GET /admin/stats?refresh=true forces a recompute.
And an anonymous GET is not "a 401 exactly as before" — an optionally
authenticated read can return GUEST data with a 200 that callers accept and
cache while sessionExpired is signing the user out. That is a worse outcome
than the 401 it replaced.

So the rule goes back to strict: a repudiated session sends nothing, whatever
the method. The public endpoints that motivated the exception are fixed at the
root instead — /health and the RELATIVE setup/signup-status calls now
skipSiloAuth(), matching their explicit-server twins which already did. Opted
out, they never carry a bearer, never enter the proactive path, and cannot be
failed by a dead session elsewhere. This also restores the download GET to
throwing, so downloadAuthFailureIsRetriable covers a path production actually
takes rather than documenting a dead one.

Separately: a transient proactive failure (5xx, gateway, dropped connection) is
now RefreshOutcome.FailedTransient and suppresses the reactive retry for that
request. One request was producing two refresh attempts against a refresh
service already failing, and concurrent traffic amplified the outage.

shared 1027, android-shared 1103, androidTvApp 976, androidApp 591, all green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(auth): let a concurrently rotated token still rescue a suppressed request

Round 5 closed the previous four findings and left one real defect, in the
suppression added by the last commit.

Returning early on a transient proactive failure skipped more than the network
call: it skipped refreshScopeOnce's double-check. So if request A's proactive
refresh failed transiently while request B's succeeded and installed a new
token, A surfaced a stale 401 even though working credentials were already
sitting there — and recovering needed no network call at all, just the check
that was being bypassed.

The suppression is now a parameter on refreshScopeOnce rather than an early
return at the call site. Everything before the network POST still runs,
including the already-rotated check; only the POST itself is skipped.

Test covers the concurrent-rotation case and is mutation-checked: restoring the
early return fails it. The single-request cost stands as intended — one
genuinely expired token surfaces a 401 after a transient failure and recovers
on a later request, which is the point of not hammering a failing refresh
service.

shared 1028, android-shared 1103, androidTvApp 976, androidApp 591, all green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(auth): correct two comments the refactor left stale

refreshScopeOnce's KDoc still documented a boolean return, and the
CredentialsDead branch said 'a 401 is the honest answer' when it throws
without sending anything. Also documents allowNetworkRefresh.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(auth): opt the branding probe out of auth too

Post-merge review against the new main. #192 added BrandingApi as the PRIMARY
source of a server's display name, replacing checkHealth() in the same
AuthRepository path — but it does not skipSiloAuth(), so it carries a bearer it
never needed.

Before this stack that was harmless. It is not harmless now: a repudiated
session makes the proactive path throw before branding reaches the server,
safeApiCall turns that into a NetworkError, and AuthRepository falls back to
health — restoring the compatibility-backed name that #192 exists to stop
using. Opening the TV server list is enough to trigger it. The regression is
introduced by this stack, so it belongs in this stack rather than a follow-up.

Opted out exactly like its sibling. Test drives both probes through a
repudiated session and asserts neither fails and neither carries a bearer;
mutation-checked by removing the opt-out.

shared 1067, android-shared 1134, androidTvApp 993, androidApp 606, green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(auth): verify the credentials still exist before spending them

Pre-merge gate against the new main found a race that breaks this stack's
central invariant.

A request captures its bearer before it waits on the refresh mutex. A
concurrent sign-out, server switch, or repudiation in that window all make
refreshScopeOnce return NotAttempted — which says only "no refresh happened",
not "the scope is still alive". The proactive path read that as permission to
continue and sent the request with the bearer it had captured, so an
invalidated credential could still be spent after another request had already
torn the session down.

Rather than enumerate every outcome that can mean a dead scope, the caller now
checks the invariant directly at the only point it matters: immediately before
proceed(). If nothing is installed, or the active server has changed, the
request is dropped and fails like any other repudiated one. If the credentials
were merely rotated by another coroutine, the request spends the token that is
actually installed instead of the stale capture. Applied to every non-Refreshed
outcome, including FailedTransient — that case is meant to spend the existing
credentials, but only if they still exist.

Tests cover both halves and are mutation-checked: neutering the guard fails
both. shared 1069, android-shared 1138, androidTvApp 993, androidApp 606.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: rxwatcher <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use native branding for saved server names

1 participant