From 21d652f700efed85928513370ae1f9afac8fb592 Mon Sep 17 00:00:00 2001 From: maliavko Date: Thu, 19 Nov 2026 19:09:42 +0100 Subject: [PATCH 1/3] fix(plex): keep the token out of track paths Each Plex track path was the stream URL with X-Plex-Token in its query, so the token was written to favorites, history, playlists and resume.json, and shown in IPC output. Tracks now carry plex:track:. A source resolver turns it into the stream URL when playback starts and adds the token in memory. After a restart the provider reads the track's part once from /library/metadata/. A ratingKey with other characters than letters, digits, - and _ is refused before any request. Saved paths that hold a stream URL keep playing as before. Verified with make check (gofmt, go vet, go test ./...) and staticcheck, and read-only against a live server: 40 albums gave token-free paths, and a fresh provider resolved each to a part that answered 206. Co-Authored-By: Claude Opus 5.5 --- docs/plex.md | 6 ++-- external/plex/client.go | 16 +++++++++ external/plex/provider.go | 62 ++++++++++++++++++++++++++++++++-- external/plex/provider_test.go | 57 +++++++++++++++++++++++++------ providers.go | 10 ++++++ providers_test.go | 11 ++++++ 6 files changed, 146 insertions(+), 16 deletions(-) diff --git a/docs/plex.md b/docs/plex.md index 66177b642..388997657 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -70,13 +70,13 @@ provider = "plex" ## How it works -cliamp calls the Plex HTTP API to list audio playlists (`/playlists`) and music library albums. When you select an entry, cliamp gets its track list from the playlist-items or album-children endpoint. It then creates authenticated streaming URLs in this form: +cliamp calls the Plex HTTP API to list audio playlists (`/playlists`) and music library albums. When you select an entry, cliamp gets its track list from the playlist-items or album-children endpoint. Queues, playlists, favorites, history, resume state and IPC keep only a token-free path: ``` -http://:32400/library/parts///file.?X-Plex-Token= +plex:track: ``` -These URLs serve files directly. Plex serves the original file without transcoding. cliamp handles playback through its HTTP streaming pipeline. cliamp can play MP3, FLAC, AAC, OGG, OPUS, WAV, and other supported source formats. +When playback starts, cliamp resolves that path to the Plex part URL in memory and adds your token to the request. The token is not written into track paths. The part URLs serve files directly. Plex serves the original file without transcoding. cliamp handles playback through its HTTP streaming pipeline. cliamp can play MP3, FLAC, AAC, OGG, OPUS, WAV, and other supported source formats. ## Troubleshooting diff --git a/external/plex/client.go b/external/plex/client.go index 1a8eacc16..e4876e740 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -374,6 +374,22 @@ func (c *Client) Search(query string) ([]Track, error) { return tracks, nil } +// Track returns one track by its ratingKey. +func (c *Client) Track(ratingKey string) (Track, error) { + var result struct { + MediaContainer struct { + Metadata []trackJSON `json:"Metadata"` + } `json:"MediaContainer"` + } + if err := c.get("/library/metadata/"+ratingKey, nil, &result); err != nil { + return Track{}, err + } + if len(result.MediaContainer.Metadata) == 0 { + return Track{}, fmt.Errorf("plex: track %s not found", ratingKey) + } + return trackFromJSON(result.MediaContainer.Metadata[0]), nil +} + // StreamURL returns the authenticated HTTP URL for streaming a track part. // partKey is the relative path from the Part element, e.g. "/library/parts/…/file.flac". // The token is appended as a query parameter; Plex accepts it in either header or query form. diff --git a/external/plex/provider.go b/external/plex/provider.go index ad5c60220..88b397c3f 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -16,6 +16,9 @@ import ( // the browse view. Playlist IDs are prefixed so they can be told apart from // album ratingKeys (both live in the same server-side metadata key space). const ( + // TrackURIPrefix starts the token-free path that queues, history, + // favorites, playlists, resume state and IPC keep for a Plex track. + TrackURIPrefix = "plex:track:" prefixPlaylist = "pl:" sectionAlbums = "Albums" sectionPlaylists = "Playlists" @@ -37,6 +40,7 @@ type Provider struct { mu sync.Mutex playlistCache []playlist.PlaylistInfo trackCache map[string][]playlist.Track + partKeys map[string]string // ratingKey to stream part } // newProvider returns a Provider backed by the given Client. @@ -184,15 +188,23 @@ func (p *Provider) SearchTracks(_ context.Context, query string, limit int) ([]p } // convertTracks converts Plex tracks to playlist tracks, skipping entries -// without a streamable part. If limit > 0, at most limit tracks are returned. +// without a valid ratingKey or a streamable part. If limit > 0, at most limit +// tracks are returned. Each Path is a token-free plex:track: URI; +// ResolveSource adds the token when playback starts. func (p *Provider) convertTracks(plexTracks []Track, limit int) []playlist.Track { tracks := make([]playlist.Track, 0, len(plexTracks)) + p.mu.Lock() + defer p.mu.Unlock() for _, t := range plexTracks { - if t.PartKey == "" { + if !validRatingKey(t.RatingKey) || t.PartKey == "" { continue } + if p.partKeys == nil { + p.partKeys = make(map[string]string) + } + p.partKeys[t.RatingKey] = t.PartKey tracks = append(tracks, playlist.Track{ - Path: p.client.StreamURL(t.PartKey), + Path: TrackURIPrefix + t.RatingKey, Title: t.Title, Artist: t.ArtistName, Album: t.AlbumName, @@ -208,6 +220,50 @@ func (p *Provider) convertTracks(plexTracks []Track, limit int) []playlist.Track return tracks } +// ResolveSource turns a plex:track: URI into an authenticated stream URL when +// playback starts. After a restart the part is not known yet, so it reads +// the track's metadata once. +func (p *Provider) ResolveSource(uri string) (string, error) { + id, ok := strings.CutPrefix(uri, TrackURIPrefix) + if !ok || !validRatingKey(id) { + return "", fmt.Errorf("plex: invalid track uri %q", uri) + } + p.mu.Lock() + partKey := p.partKeys[id] + p.mu.Unlock() + if partKey == "" { + track, err := p.client.Track(id) + if err != nil { + return "", fmt.Errorf("plex: resolve track %s: %w", id, err) + } + if track.PartKey == "" { + return "", fmt.Errorf("plex: track %s has no streamable part", id) + } + partKey = track.PartKey + p.mu.Lock() + if p.partKeys == nil { + p.partKeys = make(map[string]string) + } + p.partKeys[id] = partKey + p.mu.Unlock() + } + return p.client.StreamURL(partKey), nil +} + +// validRatingKey reports whether id is safe to put in a metadata path. +func validRatingKey(id string) bool { + if id == "" { + return false + } + for _, r := range id { + if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && + (r < '0' || r > '9') && r != '-' && r != '_' { + return false + } + } + return true +} + // AlbumTracks returns the tracks for the given album (ratingKey). // Implements provider.AlbumTrackLoader. func (p *Provider) AlbumTracks(albumID string) ([]playlist.Track, error) { diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 466e97a17..2610420c4 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -220,14 +220,15 @@ func TestProvider_Tracks(t *testing.T) { if !tr.Stream { t.Error("Stream = false, want true") } - if !strings.HasPrefix(tr.Path, srv.URL) { - t.Errorf("Path %q does not start with server URL", tr.Path) + if tr.Path != TrackURIPrefix+"200" { + t.Errorf("Path = %q, want %q", tr.Path, TrackURIPrefix+"200") } - if !strings.Contains(tr.Path, "X-Plex-Token=tok") { - t.Errorf("Path %q missing X-Plex-Token", tr.Path) + got, err := p.ResolveSource(tr.Path) + if err != nil { + t.Fatalf("ResolveSource: %v", err) } - if !strings.Contains(tr.Path, "/library/parts/1/111/SoWhat.flac") { - t.Errorf("Path %q missing part key", tr.Path) + if !strings.HasPrefix(got, srv.URL+"/library/parts/1/111/SoWhat.flac?") || !strings.Contains(got, "X-Plex-Token=tok") { + t.Errorf("ResolveSource = %q, want the authenticated part URL", got) } } @@ -264,11 +265,47 @@ func TestProvider_Tracks_Playlist(t *testing.T) { if !tr.Stream { t.Error("Stream = false, want true") } - if !strings.Contains(tr.Path, "X-Plex-Token=tok") { - t.Errorf("Path %q missing X-Plex-Token", tr.Path) + if tr.Path != TrackURIPrefix+"300" { + t.Errorf("Path = %q, want %q", tr.Path, TrackURIPrefix+"300") } - if !strings.Contains(tr.Path, "/library/parts/3/333/HighwayToHell.flac") { - t.Errorf("Path %q missing part key", tr.Path) +} + +// After a restart the queue holds only plex:track: paths. ResolveSource +// reads the track's part from the server and adds the token. +func TestProviderResolveSourceRestoresAfterRestart(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/library/metadata/200" { + t.Errorf("path = %q, want the metadata lookup", r.URL.Path) + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"MediaContainer":{"Metadata":[{"ratingKey":"200","Media":[{"Part":[{"key":"/library/parts/1/111/file.flac"}]}]}]}}`)) + })) + defer srv.Close() + + p := newProvider(NewClient(srv.URL, "tok")) + got, err := p.ResolveSource(TrackURIPrefix + "200") + if err != nil { + t.Fatalf("ResolveSource: %v", err) + } + if !strings.HasPrefix(got, srv.URL+"/library/parts/1/111/file.flac?") || !strings.Contains(got, "X-Plex-Token=tok") { + t.Fatalf("ResolveSource = %q, want the authenticated part URL", got) + } +} + +// A path that is not a plain ratingKey never reaches the server. +func TestProviderResolveSourceRejectsBadPaths(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("unexpected request %s", r.URL.Path) + })) + defer srv.Close() + + p := newProvider(NewClient(srv.URL, "tok")) + for _, path := range []string{TrackURIPrefix, TrackURIPrefix + "../200", TrackURIPrefix + "200?x=1", "yandex:track:200"} { + if _, err := p.ResolveSource(path); err == nil { + t.Errorf("ResolveSource(%q): got no error", path) + } } } diff --git a/providers.go b/providers.go index 60f3140e6..c927b2214 100644 --- a/providers.go +++ b/providers.go @@ -369,6 +369,16 @@ func (s *providerSet) registerPlayerHooks(p *player.Player) { } } switch prov := e.Provider.(type) { + case *plex.Provider: + // Plex tracks carry token-free plex:track: URIs; the provider + // adds the token in memory when playback starts. + p.RegisterSourceResolver(plex.TrackURIPrefix, func(uri string) (player.ResolvedSource, error) { + u, err := prov.ResolveSource(uri) + if err != nil { + return player.ResolvedSource{}, fmt.Errorf("resolve Plex source: %w", err) + } + return player.ResolvedSource{URL: u, Buffered: true}, nil + }) case *yandex.Provider: // Yandex tracks carry yandex:track: URIs; the provider resolves them // to a fresh signed stream URL when playback starts. diff --git a/providers_test.go b/providers_test.go index d2f4c4d48..96fa62752 100644 --- a/providers_test.go +++ b/providers_test.go @@ -18,6 +18,7 @@ import ( "github.com/bjarneo/cliamp/external/emby" "github.com/bjarneo/cliamp/external/jellyfin" "github.com/bjarneo/cliamp/external/navidrome" + "github.com/bjarneo/cliamp/external/plex" "github.com/bjarneo/cliamp/favorites" "github.com/bjarneo/cliamp/history" "github.com/bjarneo/cliamp/internal/resume" @@ -209,6 +210,16 @@ func TestProviderSetUsesCapabilities(t *testing.T) { } } +func TestProviderSetRegistersPlexSourceResolver(t *testing.T) { + prov := plex.NewFromConfig(config.PlexConfig{URL: "http://127.0.0.1:1", Token: "token"}) + set := &providerSet{entries: []provider.Entry{{Key: "plex", Name: "Plex", Provider: prov}}} + engine := &player.Player{} + set.registerPlayerHooks(engine) + if !engine.HasSourceResolver(plex.TrackURIPrefix + "42") { + t.Fatal("Plex source resolver was not registered") + } +} + // A page URL that playlist.IsYTDL accepts opens through yt-dlp, also when a // Jellyfin server registers a source resolver for every https URL. func TestPlayerHooksSendYTDLPagesToYTDLP(t *testing.T) { From fe8753cd48d440f6075b21aa087ac251aa2a07a1 Mon Sep 17 00:00:00 2001 From: maliavko Date: Thu, 19 Nov 2026 23:10:37 +0100 Subject: [PATCH 2/3] docs(plex): describe token-free track paths The Tracks doc comment still said each track's Path is a complete authenticated HTTP URL. Since the previous commit the Path is a plex:track: URI that ResolveSource turns into a stream URL at play time. The comment now says so. Comment-only change; verified with make check (fmt, vet, tests). Co-Authored-By: Claude Opus 5.5 --- external/plex/provider.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/external/plex/provider.go b/external/plex/provider.go index 88b397c3f..81f6bf2da 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -134,7 +134,8 @@ func (p *Provider) Refresh() { // Tracks returns the tracks for the playlist or album identified by // playlistID. Playlist IDs (prefixed "pl:") load via the server playlists // endpoint; album IDs load via the album children endpoint. Each track's Path -// is a complete authenticated HTTP URL ready for the player. Tracks with no +// is a token-free plex:track: URI that ResolveSource turns into a +// stream URL at play time. Tracks with no // streamable part (missing Media/Part data) are silently skipped. Album tracks // are cached per album ID; playlist tracks are intentionally not cached so // smart playlists always reflect their current server contents. From c259260b87cf020c52f36fbd3dd6315632020311 Mon Sep 17 00:00:00 2001 From: maliavko Date: Thu, 19 Nov 2026 23:40:50 +0100 Subject: [PATCH 3/3] fix(plex): forget cached parts on refresh Refresh cleared the playlist and track caches but kept partKeys. When a file is replaced in Plex, the track keeps its ratingKey and gets a new part, so a queued track kept asking for the old part after Ctrl+R. Refresh now clears partKeys under the same lock. docs/plex.md promised that no saved entry holds the token. Entries saved by an earlier version keep their full stream URL; the docs now say so. The Tracks doc comment is reflowed. Verified with make check (fmt, vet, tests), race tests and staticcheck for external/plex. The new TestProviderRefreshForgetsParts fails without the fix. Co-Authored-By: Claude Opus 5.5 --- docs/plex.md | 2 +- external/plex/provider.go | 9 +++++---- external/plex/provider_test.go | 25 +++++++++++++++++++++++++ 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/docs/plex.md b/docs/plex.md index 388997657..4b8d6943b 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -76,7 +76,7 @@ cliamp calls the Plex HTTP API to list audio playlists (`/playlists`) and music plex:track: ``` -When playback starts, cliamp resolves that path to the Plex part URL in memory and adds your token to the request. The token is not written into track paths. The part URLs serve files directly. Plex serves the original file without transcoding. cliamp handles playback through its HTTP streaming pipeline. cliamp can play MP3, FLAC, AAC, OGG, OPUS, WAV, and other supported source formats. +When playback starts, cliamp resolves that path to the Plex part URL in memory and adds your token to the request. The token is not written into new track paths. Entries saved by an earlier cliamp version keep the full stream URL, token included, until you remove them. The part URLs serve files directly. Plex serves the original file without transcoding. cliamp handles playback through its HTTP streaming pipeline. cliamp can play MP3, FLAC, AAC, OGG, OPUS, WAV, and other supported source formats. ## Troubleshooting diff --git a/external/plex/provider.go b/external/plex/provider.go index 81f6bf2da..a395df1e8 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -128,6 +128,7 @@ func (p *Provider) Refresh() { p.mu.Lock() p.playlistCache = nil p.trackCache = nil + p.partKeys = nil p.mu.Unlock() } @@ -135,10 +136,10 @@ func (p *Provider) Refresh() { // playlistID. Playlist IDs (prefixed "pl:") load via the server playlists // endpoint; album IDs load via the album children endpoint. Each track's Path // is a token-free plex:track: URI that ResolveSource turns into a -// stream URL at play time. Tracks with no -// streamable part (missing Media/Part data) are silently skipped. Album tracks -// are cached per album ID; playlist tracks are intentionally not cached so -// smart playlists always reflect their current server contents. +// stream URL at play time. Tracks with no streamable part (missing Media/Part +// data) are silently skipped. Album tracks are cached per album ID; playlist +// tracks are intentionally not cached so smart playlists always reflect their +// current server contents. func (p *Provider) Tracks(playlistID string) ([]playlist.Track, error) { isPlaylist := strings.HasPrefix(playlistID, prefixPlaylist) diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 2610420c4..cffe628c4 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -294,6 +294,31 @@ func TestProviderResolveSourceRestoresAfterRestart(t *testing.T) { } } +// Refresh forgets the cached parts: a file replaced in Plex keeps its +// ratingKey but gets a new part, and the next play must use the new one. +func TestProviderRefreshForgetsParts(t *testing.T) { + part := "/library/parts/1/111/old.flac" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"MediaContainer":{"Metadata":[{"ratingKey":"200","Media":[{"Part":[{"key":"` + part + `"}]}]}]}}`)) + })) + defer srv.Close() + + p := newProvider(NewClient(srv.URL, "tok")) + if _, err := p.ResolveSource(TrackURIPrefix + "200"); err != nil { + t.Fatalf("ResolveSource: %v", err) + } + part = "/library/parts/2/222/new.flac" + p.Refresh() + got, err := p.ResolveSource(TrackURIPrefix + "200") + if err != nil { + t.Fatalf("ResolveSource after Refresh: %v", err) + } + if !strings.HasPrefix(got, srv.URL+part+"?") { + t.Fatalf("ResolveSource after Refresh = %q, want the new part", got) + } +} + // A path that is not a plain ratingKey never reaches the server. func TestProviderResolveSourceRejectsBadPaths(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {