Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
160 commits
Select commit Hold shift + click to select a range
a0ce1be
fix(api): allow HEAD on /api/v1/direct-download
May 24, 2026
8537d26
Merge pull request #5 from Silo-Server/fix/direct-download-head
Quick104 May 24, 2026
0e927b3
Merge pull request #7 from Silo-Server/t3code/discover-studios-networ…
Quick104 May 25, 2026
0891e61
docs: design jellyfin autoscan scan compatibility
May 24, 2026
85bf94d
refactor(scan): extract scan trigger resolver
May 24, 2026
6d2c35f
refactor(api): share scan target resolution
May 24, 2026
3d82e59
feat(jellycompat): accept admin api keys for autoscan
May 24, 2026
8c856c4
feat(jellycompat): add autoscan media update route
May 24, 2026
7d612f6
docs: document jellyfin autoscan setup
May 24, 2026
09a02a7
fix(jellycompat): harden autoscan auth and batch scan enqueue
May 25, 2026
eed9439
chore: add planning docs and requests updates
May 25, 2026
eccf68f
refactor(scantrigger): drop redundant Target.LibraryID field
May 25, 2026
dcd443f
fix(catalog): gate search overview-only matches behind title FTS
May 25, 2026
bfb977a
ci(docker): build image on push to main via self-hosted runner
May 25, 2026
e9a2a16
docs(specs): add design for TMDB-backed request section in search
May 25, 2026
2c0751a
docs(specs): address Codex adversarial review for search request section
May 25, 2026
14471cf
docs(plans): add implementation plan for search request section
May 25, 2026
0e57325
docs(plans): address Codex adversarial review for search request section
May 25, 2026
5184696
test(api): pin AbortSignal forwarding contract on api()
May 25, 2026
ca18407
feat(hooks): add useCanRequest gating hook for discovery eligibility
May 25, 2026
53c9bc3
refactor(keys): add viewerKey to requestKeys.search
May 25, 2026
2e2bf46
feat(requests): key useRequestSearch by viewer, forward signal, raise…
May 25, 2026
8a7e58e
test(requests): document viewer-keyed cache isolation and invalidatio…
May 25, 2026
ac62769
feat(request-card): make onRequest optional on discover variant
May 25, 2026
dd2334e
feat(search): add RequestToAddSection dialog variant
May 25, 2026
038f9be
feat(search): add RequestToAddSection grid variant for Catalog page
May 25, 2026
d23a27f
feat(search): render RequestToAddSection in the Cmd+K dialog with emp…
May 25, 2026
d11eff6
feat(catalog): render RequestToAddSection grid with empty-state suppr…
May 25, 2026
cb8ad9f
chore(web): format request search section
May 25, 2026
52d300b
test(web): avoid unsupported Array.at in search request tests
May 25, 2026
8763e56
commit message
May 26, 2026
2bf9651
fix(jellycompat): tolerate autoscan sidecar updates
zZebrahz May 26, 2026
87451d0
Merge pull request #8 from Silo-Server/t3code/jellyfin-autoscan-scan-…
Quick104 May 26, 2026
4d5a6d5
fix(webhooksync): skip events for unmapped external users
May 26, 2026
7b8f9e1
Merge branch 'main' of https://github.com/Silo-Server/silo-server
May 26, 2026
31806c8
refactor(admin): show per-section loading and error states
Quick104 May 26, 2026
2412486
fix(search): address request search review feedback
Quick104 May 26, 2026
8df7cf5
Merge pull request #9 from Silo-Server/t3code/search-tmdb-fallback-re…
Quick104 May 26, 2026
5fec3ca
feat(subtitles): restore upload management
Quick104 May 26, 2026
a5fbaaf
Merge pull request #10 from Silo-Server/codex/restore-subtitle-uploads
Quick104 May 26, 2026
6928122
feat(auth): add assignable user permissions
Quick104 May 26, 2026
06d24f6
feat(auth): expose user permissions
Quick104 May 26, 2026
6bec1fc
feat(api): authorize item metadata curation
Quick104 May 26, 2026
5b959cc
feat(api): route metadata curation by permission
Quick104 May 26, 2026
d16401c
feat(web): add permission helpers
Quick104 May 26, 2026
7538749
feat(web): assign metadata curation permission
Quick104 May 26, 2026
fe99981
fix(web): keep device profile hooks unconditional
Quick104 May 26, 2026
c89346f
feat(web): show metadata tools to curators
Quick104 May 26, 2026
539a5c5
fix(auth): address metadata curation review issues
Quick104 May 26, 2026
46b10db
fix(auth): tighten curator job response review fixes
Quick104 May 26, 2026
87516c7
docs: add metadata curation permission plan
Quick104 May 26, 2026
41d2eeb
test(auth): expand session revocation coverage
Quick104 May 26, 2026
83b1d10
docs: add PageBack component design spec
Quick104 May 26, 2026
7793597
fix(auth): gate media file paths on metadata curation permission
Quick104 May 27, 2026
c85ea1c
Merge pull request #11 from Silo-Server/t3code/eb3dedf1
Quick104 May 27, 2026
705ea1f
Merge branch 'main' of https://github.com/Silo-Server/silo-server
Quick104 May 27, 2026
811ce54
fix(metadata): break duplicate provider candidate ties
Quick104 May 27, 2026
7be1f73
feat(ui): add shared PageBack component for consistent back navigation
Quick104 May 27, 2026
8492043
feat(ui): add floating variant to PageBack for sticky nav
Quick104 May 27, 2026
13fe740
fix(ui): make PageBack destinations deterministic
Quick104 May 27, 2026
5b32b01
feat(episode-carousel): highlight currently viewed episode
Quick104 May 27, 2026
d9e287a
Merge pull request #12 from Silo-Server/t3code/5155230b
Quick104 May 27, 2026
1070c62
Merge pull request #13 from Silo-Server/t3code/2f7d918d
Quick104 May 27, 2026
22bae2f
feat(jellycompat): sign image tags and accept them without session
Quick104 May 27, 2026
e3b8a4b
fix(jellycompat): harden signed image tags
Quick104 May 27, 2026
44f90dd
fix(jellycompat): stabilize signed image tags across restarts
Quick104 May 27, 2026
c4ea942
Merge pull request #14 from Silo-Server/t3code/116da365
Quick104 May 27, 2026
e46f608
fix(metadata): accept exact cross-provider match ties
Quick104 May 27, 2026
058f3e0
Optimize episode added_at sorting
Quick104 May 27, 2026
ea5be46
fix(libraryingest): treat drainer shutdown cancel as clean stop
CoffeeKnyte May 27, 2026
6facf2e
perf(catalog): add episode browse index fast path
Quick104 May 27, 2026
1b326f4
fix(catalog): address episode catalog review feedback
Quick104 May 27, 2026
583c16c
Merge pull request #16 from Silo-Server/codex/episode-catalog-perform…
Quick104 May 27, 2026
f2cb7e1
Fix settle-window drainer cancellation in library ingest
Quick104 May 27, 2026
bf34462
Merge pull request #15 from Silo-Server/fix/tv-scan-settle-window-cancel
Quick104 May 27, 2026
d04e469
fix(catalog): support relative date filters
Quick104 May 27, 2026
d3cc6f7
fix(collections): cap smart collection results
Quick104 May 27, 2026
d73d5da
fix(library): preserve episode browse url
Quick104 May 27, 2026
c066d75
fix(catalog): use season posters for episode cards
Quick104 May 27, 2026
b880c7d
feat(sections): show episode context in cards
Quick104 May 27, 2026
985b296
Merge pull request #18 from Silo-Server/codex/episode-section-labels
Quick104 May 27, 2026
fb10bde
feat(calendar): show local episode airtimes
Quick104 May 28, 2026
bbaea15
Enable DRI passthrough in docker compose
Quick104 May 28, 2026
647f8b9
feat(ui): paginate the Ambiguous Roots table
fluxis May 27, 2026
dc45373
feat(admin): enlarge match-candidate posters + hover-to-enlarge
fluxis May 28, 2026
836fc73
fix(admin): search unmatched items across the whole table, not just t…
fluxis May 28, 2026
bf68957
style(admin): prettier-format match dialog; reset unmatched page in o…
fluxis May 28, 2026
e2a14f6
test(admin): wire QueryClientProvider + missing hook mocks so the sui…
fluxis May 28, 2026
b1c5ff3
fix(admin): search all unmatched item library memberships
Quick104 May 28, 2026
2d9a0f7
Merge pull request #20 from fluxis/mr/b-admin-ux
Quick104 May 28, 2026
257a36b
Merge branch 'main' of https://github.com/Silo-Server/silo-server
Quick104 May 28, 2026
a0ea7de
fix(naming): strip unsubstituted Sonarr tokens ({TvdbId}/{imdb-}) fro…
fluxis May 27, 2026
756709b
fix(naming): numeric-only titles are not bare provider IDs
fluxis May 27, 2026
7f42158
test(naming): document bare-id trade-off; cover CJK title + movies nu…
fluxis May 27, 2026
559e10e
feat(matcher): auto-accept a year-corroborated single distinct show
fluxis May 27, 2026
4ba6c48
test(matcher): exercise the single-distinct-show guard properly + con…
fluxis May 27, 2026
5cfcd63
fix(matcher): tolerate concurrent-merge ErrItemNotFound in series epi…
fluxis May 27, 2026
0e39c43
diag(matcher): debug-log per-candidate match scores
fluxis May 27, 2026
4fce788
feat(matcher): resolve cross-source ties by library provider priority
fluxis May 27, 2026
c72cec8
feat(matcher): accept cross-source-corroborated ties without a hint year
fluxis May 27, 2026
b6e7fd0
diag(matcher): debug-log provider search query + per-provider result …
fluxis May 28, 2026
fdad754
fix(naming): parse bare bracketed IMDb IDs ([tt10011226]/{tt...})
fluxis May 28, 2026
71bf580
feat(metadata): match sole exact-title candidate despite year off by <=2
fluxis May 28, 2026
df11126
chore(lint): gofmt single-space alignment in root_inference.go var block
fluxis May 28, 2026
38389a7
fix(metadata): tighten matcher and bare IMDb parsing
Quick104 May 28, 2026
5ceb0cf
Merge pull request #19 from fluxis/mr/a-matcher-reliability
Quick104 May 28, 2026
aaf73f2
Merge branch 'main' of https://github.com/Silo-Server/silo-server
Quick104 May 28, 2026
d9a7421
docs: add resilient library deletion design spec
Quick104 May 28, 2026
1e38992
docs: add implementation plan for resilient library deletion
Quick104 May 28, 2026
ec8a356
feat(catalog): add deadlock-retry helper for batched deletes
Quick104 May 28, 2026
2411405
test(catalog): clarify cancel-path expectation in retry test
Quick104 May 28, 2026
0ca604b
feat(catalog): add deleteInBatches loop helper
Quick104 May 28, 2026
0a00823
refactor(catalog): make image-dir helpers querier-agnostic
Quick104 May 28, 2026
6f05713
fix(catalog): delete libraries in deadlock-retrying batches
Quick104 May 28, 2026
9abf4ed
refactor(catalog): wrap orphan-batch iteration error
Quick104 May 28, 2026
e6f1df6
fix(catalog): clamp still/poster/logo backdrops to largest cached var…
Quick104 May 28, 2026
48e8e21
perf(startup): defer non-critical init off the HTTP listener path
Quick104 May 28, 2026
9bfc400
fix(migrations): make air_timezone column add idempotent
Quick104 May 28, 2026
ff51a9e
build: stamp git revision via Makefile ldflags
Quick104 May 28, 2026
93e4df2
fix(web): accessibility & UX fixes from visual QA pass
Quick104 May 28, 2026
7f77da4
fix(catalog): re-check orphan status when deleting library items
Quick104 May 29, 2026
9014720
fix(metadata): persist a cleared air_timezone instead of skipping it
Quick104 May 29, 2026
64578d5
fix(startup): sweep open scrobbles before accepting playback
Quick104 May 29, 2026
a93fee3
fix(catalog): scan air_timezone in paginated item queries
Quick104 May 29, 2026
b6c37f5
revert(startup): keep open-scrobble sweep deferred for fast startup
Quick104 May 29, 2026
6df5d94
fix(startup): recover from panics in deferred background init
Quick104 May 29, 2026
8353880
Merge pull request #21 from Silo-Server/fix/web-a11y-visual-qa
Quick104 May 29, 2026
ea2c637
feat(auth): make usernames and emails case-insensitive
Quick104 May 29, 2026
b8ae273
Merge pull request #22 from Silo-Server/feat/case-insensitive-usernames
Quick104 May 29, 2026
2e6f9f6
feat(sections): add trending_discover home section
Quick104 May 29, 2026
abce996
docs: add trending_discover persistent snapshot design
Quick104 May 29, 2026
62d5325
docs: add trending_discover persistent snapshot implementation plan
Quick104 May 29, 2026
a78a1e8
refactor(sections): tidy trending_discover fetch and cache helpers
Quick104 May 29, 2026
44614cf
feat(sections): add trending_discover_snapshots table
Quick104 May 29, 2026
c3ac462
feat(sections): add trending snapshot model and repository
Quick104 May 29, 2026
f37a925
feat(sections): list enabled trending_discover section configs
Quick104 May 29, 2026
5c736bf
feat(sections): add trending refresher with persisted snapshots
Quick104 May 29, 2026
cbcc326
feat(tasks): add refresh_trending_discover task
Quick104 May 29, 2026
34d1922
refactor(sections): read trending_discover from persisted snapshot
Quick104 May 29, 2026
e12bb3c
feat: wire trending refresh task and snapshot reader
Quick104 May 29, 2026
2b47105
chore(sections): satisfy lint (wrap trakt errors, lift source/window …
Quick104 May 29, 2026
644e5f2
fix(migrations): renumber trending_discover_snapshots 166 -> 167
Quick104 May 29, 2026
c944c6c
fix(sections): harden trending refresher per PR review
Quick104 May 29, 2026
97eb83d
Merge pull request #23 from Silo-Server/feat/trending-section
Quick104 May 29, 2026
88ac1a1
fix(catalog): project air_timezone in episode catalog subquery
Quick104 May 29, 2026
202509b
Merge pull request #24 from Silo-Server/claude/amazing-thompson-b2843d
Quick104 May 29, 2026
998803c
fix(calendar): order events by viewer-local wall-clock time
Quick104 May 29, 2026
0e376c3
docs(calendar): add presets design spec and implementation plan
Quick104 May 29, 2026
a175b52
feat(calendar): generalize personal filter to an id-set restriction
Quick104 May 29, 2026
736c1c7
feat(calendar): add per-profile followed/favorites/watchlist/watched …
Quick104 May 29, 2026
3aa7e79
feat(calendar): resolve presets to id-sets and overlay watched status
Quick104 May 29, 2026
07aea30
feat(calendar): wire popular and trending sources into calendar handler
Quick104 May 29, 2026
17d5353
feat(calendar): add watched field to CalendarEvent type
Quick104 May 29, 2026
ffb8fcd
feat(calendar): preset selector with responsive pills, persistence, e…
Quick104 May 29, 2026
c7d1ca5
feat(calendar): dim and check-mark already-watched event cards
Quick104 May 29, 2026
234599f
feat(calendar): hide server-wide Popular preset in web UI for now
Quick104 May 29, 2026
5d23b65
refactor(calendar): simplify preset handler and reuse storage util
Quick104 May 29, 2026
e15c07d
Merge pull request #25 from Silo-Server/feat/calendar-presets
Quick104 May 29, 2026
42db002
Merge branch 'main' of https://github.com/Silo-Server/silo-server
Quick104 Jun 8, 2026
e10cc79
feat(jellycompat): add /Users endpoint and unified sa_ admin-key auth
Quick104 Jun 8, 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
50 changes: 38 additions & 12 deletions internal/jellycompat/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,7 @@ func (a *Authenticator) RequireSession(next http.Handler) http.Handler {
}
}

ctx := context.WithValue(r.Context(), compatSessionKey, session)
next.ServeHTTP(w, r.WithContext(ctx))
serveWithSession(next, w, r, session)
})
}

Expand All @@ -141,28 +140,55 @@ func safeTokenPrefix(token string) string {
return token[:8] + "..."
}

// serveWithSession injects the resolved compat session into the request context
// and continues the handler chain.
func serveWithSession(next http.Handler, w http.ResponseWriter, r *http.Request, session *Session) {
ctx := context.WithValue(r.Context(), compatSessionKey, session)
next.ServeHTTP(w, r.WithContext(ctx))
}

// resolveCompatToken resolves a token to a compat session: a session-store token
// (normal login) or, matching Jellyfin, an sa_ admin API key (synthesized
// session bound to the key user's primary profile). Returns false when the token
// matches neither. keyAuth may be nil (resolveSession handles a nil receiver).
func resolveCompatToken(ctx context.Context, sessions *SessionStore, keyAuth *AdminAPIKeyAuthenticator, token string) (*Session, bool) {
if token == "" {
return nil, false
}
if session, ok := sessions.Get(token); ok {
return session, true
}
if strings.HasPrefix(token, "sa_") {
if session, _, _ := keyAuth.resolveSession(ctx, token); session != nil {
return session, true
}
}
return nil, false
}

// PlaybackSessionAuth creates middleware that falls back to playback session
// authentication for media stream endpoints where external players (e.g. libmpv)
// don't forward auth headers or query parameters.
func PlaybackSessionAuth(sessions *SessionStore, playbackStore *PlaybackSessionStore) func(next http.Handler) http.Handler {
func PlaybackSessionAuth(sessions *SessionStore, playbackStore *PlaybackSessionStore, keyAuth *AdminAPIKeyAuthenticator) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Try standard token auth first.
// Try standard token auth first — a compat session token or an sa_
// admin key (synthesized session).
if token, ok := ExtractToken(r); ok {
if session, sessionOK := sessions.Get(token); sessionOK {
ctx := context.WithValue(r.Context(), compatSessionKey, session)
next.ServeHTTP(w, r.WithContext(ctx))
if session, ok := resolveCompatToken(r.Context(), sessions, keyAuth, token); ok {
serveWithSession(next, w, r, session)
return
}
}

// Prefer the exact negotiated playback session when the client
// includes PlaySessionId on follow-up stream requests.
// Follow-up HLS requests (master/segment) carry only PlaySessionId,
// no auth header or api_key. Resolve the negotiated session's
// CompatToken — which for an API-key stream is itself the sa_ key,
// so it must go through the same session-or-API-key resolution.
if playSessionID := firstNonEmpty(r.URL.Query().Get("PlaySessionId"), r.URL.Query().Get("PlaySessionID")); playSessionID != "" {
if playSession, found := playbackStore.Get(playSessionID); found {
if session, ok := sessions.Get(playSession.CompatToken); ok {
ctx := context.WithValue(r.Context(), compatSessionKey, session)
next.ServeHTTP(w, r.WithContext(ctx))
if session, ok := resolveCompatToken(r.Context(), sessions, keyAuth, playSession.CompatToken); ok {
serveWithSession(next, w, r, session)
return
}
writeError(w, http.StatusUnauthorized, "Unauthorized", "Session expired")
Expand Down
255 changes: 235 additions & 20 deletions internal/jellycompat/auth_api_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ package jellycompat

import (
"context"
"fmt"
"log/slog"
"net/http"
"strings"
"sync"
"time"

"github.com/Silo-Server/silo-server/internal/models"
"github.com/Silo-Server/silo-server/internal/userstore"
)

type adminAPIKeyContextKey string
Expand All @@ -24,8 +27,17 @@ type apiKeyUserLoader interface {
}

type AdminAPIKeyAuthenticator struct {
keys apiKeyValidator
users apiKeyUserLoader
keys apiKeyValidator
users apiKeyUserLoader
provider userstore.UserStoreProvider
now func() time.Time

// profiles caches only the primary-profile lookup per user — never an
// authorization decision, which is re-checked on every request.
profiles *apiKeyProfileCache

lastUsedMu sync.Mutex
lastUsedAt map[int64]time.Time
}

type adminAPIKeyAuthResult struct {
Expand All @@ -36,11 +48,26 @@ type adminAPIKeyAuthResult struct {
ok bool
}

func NewAdminAPIKeyAuthenticator(keys apiKeyValidator, users apiKeyUserLoader) *AdminAPIKeyAuthenticator {
// NewAdminAPIKeyAuthenticator builds the authenticator. keys and users are
// required (a nil return disables API-key auth entirely). provider is optional:
// when present, an admin key can synthesize a compat session (see
// resolveSession); when nil, only the admin-bool path (RequireAdminAPIKey /
// RequireSessionOrAdminAPIKey) is available.
func NewAdminAPIKeyAuthenticator(keys apiKeyValidator, users apiKeyUserLoader, provider userstore.UserStoreProvider, now func() time.Time) *AdminAPIKeyAuthenticator {
if keys == nil || users == nil {
return nil
}
return &AdminAPIKeyAuthenticator{keys: keys, users: users}
if now == nil {
now = time.Now
}
return &AdminAPIKeyAuthenticator{
keys: keys,
users: users,
provider: provider,
now: now,
profiles: newAPIKeyProfileCache(),
lastUsedAt: make(map[int64]time.Time),
}
}

func AdminAPIKeyFromContext(ctx context.Context) bool {
Expand Down Expand Up @@ -77,46 +104,234 @@ func RequireSessionOrAdminAPIKey(sessionAuth *Authenticator, keyAuth *AdminAPIKe
}
}

// RequireSessionOrAPIKeySession authenticates either a compat session token or
// an sa_ admin API key. For an API key it injects a session synthesized for the
// key user's primary profile, so ordinary handlers (which read
// SessionFromContext) work unchanged for both auth modes — matching Jellyfin,
// where an API key authorizes the same endpoints a user token does. When
// API-key auth is unavailable (nil authenticator or no UserStoreProvider) an
// sa_ token falls through to session-token auth and is rejected there.
func RequireSessionOrAPIKeySession(sessionAuth *Authenticator, keyAuth *AdminAPIKeyAuthenticator) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if token, ok := ExtractToken(r); ok && strings.HasPrefix(token, "sa_") {
if session, result, handled := keyAuth.resolveSession(r.Context(), token); handled {
if !result.ok {
writeError(w, result.status, result.code, result.message)
return
}
serveWithSession(next, w, r, session)
return
}
}
sessionAuth.RequireSession(next).ServeHTTP(w, r)
})
}
}

// authenticate validates an admin API key and, on success, returns a result
// carrying the admin-API-key marker in context. Used by the server-to-server
// admin routes that act on the admin identity rather than a compat session.
func (a *AdminAPIKeyAuthenticator) authenticate(r *http.Request) adminAPIKeyAuthResult {
token, _ := ExtractToken(r)
apiKey, _, res := a.validate(r.Context(), token)
if !res.ok {
return res
}
a.touchLastUsed(apiKey.ID)
return adminAPIKeyAuthResult{
ctx: context.WithValue(r.Context(), adminAPIKeyKey, true),
status: http.StatusOK,
ok: true,
}
}

// validate authenticates an admin API key by token and returns the key plus its
// owning admin user. The full authorization check — key lookup, user load,
// enabled, admin role — runs on EVERY call, so revocation (key deletion, user
// disable, role change) takes effect on the very next request. On failure the
// result carries the HTTP status/code/message: 401 for a missing/unknown/
// disabled key, 403 for a non-admin key.
func (a *AdminAPIKeyAuthenticator) validate(ctx context.Context, token string) (*models.APIKey, *models.User, adminAPIKeyAuthResult) {
unauthorized := adminAPIKeyAuthResult{
ctx: r.Context(),
status: http.StatusUnauthorized,
code: "Unauthorized",
message: "Invalid API key",
}
if a == nil || a.keys == nil || a.users == nil {
return unauthorized
return nil, nil, unauthorized
}
token, ok := ExtractToken(r)
if !ok || !strings.HasPrefix(token, "sa_") {
return unauthorized
if !strings.HasPrefix(token, "sa_") {
return nil, nil, unauthorized
}
apiKey, err := a.keys.GetByKey(r.Context(), token)
apiKey, err := a.keys.GetByKey(ctx, token)
if err != nil || apiKey == nil {
return unauthorized
return nil, nil, unauthorized
}
user, err := a.users.GetByID(r.Context(), apiKey.UserID)
user, err := a.users.GetByID(ctx, apiKey.UserID)
if err != nil || user == nil || !user.Enabled {
return unauthorized
return nil, nil, unauthorized
}
if user.Role != "admin" {
return adminAPIKeyAuthResult{
ctx: r.Context(),
return nil, nil, adminAPIKeyAuthResult{
status: http.StatusForbidden,
code: "Forbidden",
message: "Admin access required",
}
}
return apiKey, user, adminAPIKeyAuthResult{ok: true}
}

// touchLastUsed records key usage without blocking the request, throttled to at
// most once per apiKeyLastUsedInterval per key so per-request validation on the
// hot path (e.g. HLS segments) does not issue a DB write each time.
func (a *AdminAPIKeyAuthenticator) touchLastUsed(id int64) {
now := a.now()
a.lastUsedMu.Lock()
if last, ok := a.lastUsedAt[id]; ok && now.Sub(last) < apiKeyLastUsedInterval {
a.lastUsedMu.Unlock()
return
}
a.lastUsedAt[id] = now
a.lastUsedMu.Unlock()

go func(id int64) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := a.keys.UpdateLastUsed(ctx, id); err != nil {
slog.Debug("jellycompat api key last-used update failed", "id", id, "error", err)
}
}(apiKey.ID)
return adminAPIKeyAuthResult{
ctx: context.WithValue(r.Context(), adminAPIKeyKey, true),
status: http.StatusOK,
ok: true,
}(id)
}

// resolveSession authenticates an sa_ API key and returns a compat session
// synthesized for the key user's primary profile, so ordinary browse/stream
// handlers (which read SessionFromContext) work unchanged for an API key.
//
// handled reports whether this authenticator can serve API-key session auth at
// all: false when the authenticator is nil or has no UserStoreProvider wired, in
// which case the caller must fall through to session-token auth. When handled is
// true, result.ok reports success; on failure result carries what to return.
//
// The key and owning user are re-validated on EVERY call (no cached
// authorization), so revocation is immediate. Only the primary-profile lookup is
// cached (see primaryProfile), sparing the hot path the ListProfiles round-trip.
func (a *AdminAPIKeyAuthenticator) resolveSession(ctx context.Context, token string) (*Session, adminAPIKeyAuthResult, bool) {
if a == nil || a.provider == nil {
return nil, adminAPIKeyAuthResult{}, false
}
apiKey, user, res := a.validate(ctx, token)
if !res.ok {
return nil, res, true
}
a.touchLastUsed(apiKey.ID)

profile, err := a.primaryProfile(ctx, user.ID)
if err != nil {
slog.Warn("jellycompat api key session synthesis failed", "user_id", user.ID, "error", err)
return nil, adminAPIKeyAuthResult{
status: http.StatusUnauthorized,
code: "Unauthorized",
message: "Unable to resolve a profile for this API key",
}, true
}

// Upstream Silo token fields are left empty and the expiry zero: an API key
// has no refreshable Silo token, and a zero expiry makes RequireSession's
// refresh path a no-op. Downstream services scope by StreamAppUserID/ProfileID.
return &Session{
Token: token,
Username: user.Username,
AccountUsername: user.Username,
ProfileID: profile.ID,
ProfileName: profile.Name,
PseudoUserID: PseudoUserID(user.ID, profile.ID),
StreamAppUserID: user.ID,
CreatedAt: a.now(),
}, adminAPIKeyAuthResult{ok: true}, true
}

// primaryProfile returns the account's primary profile, caching the result per
// user for apiKeyProfileCacheTTL. This caches profile DATA only — never an
// authorization decision — so it is safe against revocation (validated
// separately on every request).
func (a *AdminAPIKeyAuthenticator) primaryProfile(ctx context.Context, userID int) (userstore.Profile, error) {
if profile, ok := a.profiles.get(userID, a.now()); ok {
return profile, nil
}
store, err := a.provider.ForUser(ctx, userID)
if err != nil {
return userstore.Profile{}, fmt.Errorf("open user store for user %d: %w", userID, err)
}
profiles, err := store.ListProfiles(ctx)
if err != nil {
return userstore.Profile{}, fmt.Errorf("list profiles for user %d: %w", userID, err)
}
profile, err := selectPrimaryProfile(userID, profiles)
if err != nil {
return userstore.Profile{}, err
}
a.profiles.put(userID, profile, a.now().Add(apiKeyProfileCacheTTL))
return profile, nil
}

// selectPrimaryProfile returns the account's primary profile, falling back to
// the first profile (with a warning) when none is flagged primary, and erroring
// when the account has no profiles.
func selectPrimaryProfile(userID int, profiles []userstore.Profile) (userstore.Profile, error) {
if len(profiles) == 0 {
return userstore.Profile{}, fmt.Errorf("user %d has no profiles", userID)
}
for _, p := range profiles {
if p.IsPrimary {
return p, nil
}
}
slog.Warn("jellycompat api key: no primary profile found, using first",
"user_id", userID, "profile_id", profiles[0].ID)
return profiles[0], nil
}

const (
// apiKeyProfileCacheTTL bounds how long a primary-profile lookup is reused.
// Profiles are stable, so this is generous; it only affects how quickly a
// reassigned/renamed primary profile is picked up, never authorization
// (the key and user are re-validated on every request).
apiKeyProfileCacheTTL = 5 * time.Minute
// apiKeyLastUsedInterval throttles api_keys.last_used_at writes so that
// per-request validation on the hot path does not write each time.
apiKeyLastUsedInterval = time.Minute
)

type apiKeyProfileCacheEntry struct {
profile userstore.Profile
expiresAt time.Time
}

// apiKeyProfileCache caches the primary-profile lookup per user so the hot path
// (e.g. HLS segment requests) skips the ListProfiles round-trip. It caches only
// profile data, never an authorization decision.
type apiKeyProfileCache struct {
mu sync.RWMutex
entries map[int]apiKeyProfileCacheEntry
}

func newAPIKeyProfileCache() *apiKeyProfileCache {
return &apiKeyProfileCache{entries: make(map[int]apiKeyProfileCacheEntry)}
}

func (c *apiKeyProfileCache) get(userID int, now time.Time) (userstore.Profile, bool) {
c.mu.RLock()
entry, ok := c.entries[userID]
c.mu.RUnlock()
if !ok || !entry.expiresAt.After(now) {
return userstore.Profile{}, false
}
return entry.profile, true
}

func (c *apiKeyProfileCache) put(userID int, profile userstore.Profile, expiresAt time.Time) {
c.mu.Lock()
c.entries[userID] = apiKeyProfileCacheEntry{profile: profile, expiresAt: expiresAt}
c.mu.Unlock()
}
Loading