Skip to content

Plex adapter: tester with a live server, local token only, as offered in CONTRIBUTING #180

Closed

Description

@Svnow132

What did you ask, and what came back?

I asked what is playing right now and what I have left to continue. get_playback answered 0 playing, 0 to continue, with an empty degraded list. That is true from where arr-mcp sits, since it knows no media server is configured, but it reads like an empty library rather than a blind spot. Nothing in the answer said, “no media server configured.”

The bigger gap is get_library. The README calls it the join across Radarr, Sonarr, and the media server the one tool that can say a file one side believes in is missing from the other. For me, the media server half is Plex, so that half of the join never happens.

What should the answer have been?

Now Playing and On Deck from Plex for my account, and get_library can tell whether a Radarr film or Sonarr episode is actually visible in Plex. When no media server is configured, a note saying so in the playback answer would already help.

Which services would this have to read?

  • Radarr
  • Sonarr
  • Prowlarr
  • Bazarr
  • Jellyfin
  • Seerr
  • SABnzbd
  • Transmission
  • qBittorrent

A service arr-mcp does not support at all?

Plex Media Server 1.43.3.10896 (linuxserver image), amd64, Docker, same LAN as arr-mcp. I read the constraint in CONTRIBUTING: an operator supplied X-Plex-Token talking only to the configured local server, never plex.tv. That is exactly how I would want it to run anyway, and I already have such a token. I am offering to be the tester. I can pull a main or branch image within a day or two of a ping, run it against a real library of a few thousand films and series, report what works and what does not against the version above, and re-test after changes. Happy to start with a read only adapter.

Would this change anything in your stack?

Not sure

arr-mcp version

1.18.0 (ghcr.io image)

How are you working around it today?

A separate Plex MCP server plus Tautulli. It answers the Plex side fine, but it is a different endpoint, so the join with Radarr and Sonarr never happens in one conversation. https://github.com/niavasha/plex-mcp-server

Before submitting

  • I checked the tool list in the README, including each tool's parameters, and none of them answers this.

Activity

  1. bardesss commented on Aug 31, 2026

    @bardesss
    Owner

    Thanks for offering to test, that is genuinely the thing that was blocking this.

    Two updates.

    The smaller half of your report is already fixed and went out in 1.18.1. get_playback no longer answers "0 playing, 0 to continue" when there is no media server configured, it now says that is what happened. get_library does the same. You were right that it read like an empty library rather than a blind spot.

    There is now a read-only Plex adapter. It is not merged and I do not want to merge it until you have run it, because I have never called a Plex API in my life. All of it is written off Plex's documentation, so assume some of it is wrong.

    If you want to try it:

    docker pull ghcr.io/bardesss/arr-mcp:preview-plex
    

    Config looks like this. Note the field is called api_key but it takes your X-Plex-Token, that name is inherited from the shared config schema and I know it is confusing:

    services:
      plex:
        url: http://your-plex:32400
        api_key: your-token
        default_user: YourPlexUsername

    jellyfin and plex cannot both be configured, the server refuses to start if you try. That is deliberate, get_library joins against exactly one media server.

    What I would like to know, roughly in the order of how badly it breaks if I guessed wrong:

    1. Does get_library actually join? This is the whole point of the thing. If every film comes back as arr_only then the external ids are not coming through and nothing else matters much.
    2. Does get_playback show both what is playing and what you can continue? Those come from two different endpoints and I am not certain about the second one.
    3. Whose name shows up as the user? I read /accounts and take the account with id 1. If that is wrong or comes back blank it falls back to whatever you put in default_user.
    4. Does diagnose say anything useful about library scans, or does it tell you plex cannot report that? If it is the latter I will just drop that part rather than fake it.
    5. Anything that hangs instead of failing. There is a guess in there about how paging works and I tried to make it throw a clear error if the guess is wrong, but I would rather hear about it.

    If you are willing to clone the repo as well, npm run capture against your server writes fixtures I can turn into real tests, which is what this actually needs to merge. Account names and your public IP are anonymised before anything gets written. I checked that specifically because I was not going to ask you to paste your own IP into a public issue.

    What it does not do: no writes at all, so nothing marks things watched. And it only ever sees the account your token belongs to, since a local token cannot read other users without going through plex.tv, which is the one thing I am not willing to do.

    PR is #188 if you want to look at the code. No rush at all, and thanks again.

  2. Svnow132 commented on Aug 31, 2026

    @Svnow132
    Author

    Ran it against my server. Plex 1.43.3.10896. Sections are Movies 553, TV Shows 363 shows and 23,492 episodes, and a third movie-type section holding 432 generated loop videos. Radarr manages 575 films, Sonarr 382 series. Image was ghcr.io/bardesss/arr-mcp:preview-plex at digest f9b6bd97. Your five questions first, then four things you did not ask about.

    1. The join works

    Everything I checked came back presence: "both" with Plex watch state attached, nothing fell into arr_only. I verified the per season data on One Piece against the Plex API directly rather than trusting the output: season 1 was 8 of 8 watched, season 22 was 44 of 66, season 23 was 0 of 21, and lastPlayed matched the highest lastViewedAt Plex reports for each season. Season 23 correctly carried no lastPlayed rather than a zero.

    Reading the Guid children with includeGuids=1 on the section listing is the right call and it is why this works. I checked what that parameter actually buys you: on my TV section the same request returns 0 Guid children without it and 9 across the first three rows with it. The other Plex MCP server I run keeps only the opaque plex:// guid and never resolves imdb/tmdb/tvdb, which is exactly why it cannot answer anything spanning Plex and the arrs.

    2. Both halves show up, but the currently playing item comes back twice

    Once as now_playing and once as resume, same itemId, same positionSeconds, and total counts it twice. Verified against the server: /status/sessions returned exactly one row, ratingKey 217697, and /library/onDeck contains 217697 as well. The two reads genuinely overlap and the concatenation does not dedupe.

    Collect the rating keys from the session rows and drop matching on-deck rows before mapping, keeping the now_playing row since it is the one carrying the device. One caveat if you do it by rating key: #commonPlayback can emit itemId: "" for a row with no rating key, so blank ids need excluding from the comparison rather than matching each other.

    3. /accounts id 1 is correct here

    It is the owner and the name is populated. I could not tell your two paths apart while default_user was correct, so I set it to a junk string:

    plex not found: no user named "SENTINEL_NOT_A_REAL_USER" — Known users: Svnow132. Fix default_user in config.yaml.
    

    So it does not fall back silently, it errors and names the real user back. That is better than the fallback you described and I would keep it.

    Two things you may not expect. /accounts on my server returns 103 accounts and 102 of them have an empty name, so anything that ever iterates that list should expect mostly blanks. And listUsers always returns account 1 as the owner, while the config schema has allow_other_users which PlexAdapter never reads, so a token belonging to a managed user would be labelled and filtered as the owner. I could not test that, I only have the owner token.

    4. The scan state is wrong, and I would fix this first

    getScanState matches /library|refresh/i against the activity type. My server permanently carries two provider.subscription.refresh activities, which match the refresh half, so running is effectively always true. Every diagnose call returns:

    {"stage":"scan","service":"plex","status":"blocked","detail":"A library scan is running now — check again once it finishes."}

    while nothing is scanning. I polled /activities repeatedly over several minutes and the four entries never changed: media.generate.chapter.thumbs, butler at progress 100, and two provider.subscription.refresh.

    Rather than guess at the fix I triggered a real scan on my smallest section and fast-polled both endpoints:

    <Activity uuid="4f7d0645-…" type="library.update.section" cancellable="0" userID="1" title="Scanning Bumpers" subtitle="" progress="0"

    So anchoring on the library. prefix does fix it and provider.subscription.refresh stops matching. I never observed library.refresh.items, so I would not add that one on my say-so.

    The better option is to drop /activities here entirely. /library/sections carries a refreshing attribute per section. It read "0" on all three sections at rest and flipped to "1" on the section being scanned the instant I kicked it off. python-plexapi exposes the same thing as LibrarySection.refreshing, so it is an established property rather than something my server does. You already fetch /library/sections in #sections(), so it costs no extra call, and RawSection only needs refreshing added to it. Worth checking for true, 1 and "1" rather than one JS type, since this comes off XML.

    The section list also carries scannedAt, a per section last-scan epoch, which would let you give Plex a lastCompleted in stack_health the way Radarr and Sonarr already get one. Right now the plex scans row has only running.

    I originally thought a scan short enough to finish between polls was a weakness of this approach, since my first attempt at 1.5s polling missed one entirely. On reflection that is wrong and I am not raising it as an objection: getScanState answers "is a scan blocking right now", so a scan that already finished is correctly not blocking, and /activities has exactly the same sampling limit.

    5. Nothing hung

    The paging path is exercised here, my Movies section is 553 against your PAGE_SIZE of 500, and it returned all 553 rather than stopping at 500. Your comment calls the query-parameter form a guess, and it is the same form the other Plex MCP server uses, so I think you can stop hedging it. Heaviest calls all returned well under a second off the cached index.


    Four things you did not ask about.

    /search does not send includeGuids=1, so search results carry no external ids

    The paged section read sends it, /search does not, and externalIds is still called on the result. On my server /search?query=one%20piece returns 0 Guid children, and the identical query with includeGuids=1 returns 55. Anything resolving an item through the Plex search path therefore cannot join it.

    Worth saying that /library/metadata/{ratingKey} does not need the same change: it returns the Guid children by default, I checked, so only the search path is affected.

    Watch history is capped before it is filtered

    getWatchHistory requests 500 rows with no paging loop and then filters by accountID. The read is server-wide, so on a server with many accounts the newest 500 rows can be mostly other people's and the user silently ends up with far fewer than 500 of their own. My history came back at 439 so I did not hit it, but the cap is applied to the wrong side of the filter.

    counts."plex:episodes" is mislabelled

    It reports 362 while my server holds 23,492 episodes. In library.ts the source id is built as `${seasons.id}:episodes` but its fetch is listUserSeasons, which returns one entry per series, so the number is series. I can account for the missing one exactly: of my 363 shows, exactly one has no external id, "The Ocean Cut" on tv.plex.agents.none, and it is dropped, leaving 362.

    The per season numbers themselves are correct so nothing is broken, but the name is wrong in a way a user reads, since get_library surfaces counts unchanged. Something like plex:series-seasons would be honest.

    get_library still talks about Jellyfin

    get_playback and diagnose both read "your media server" now, but get_library's description mentions Jellyfin three times, describes watched as "Jellyfin watch state", and its presence enum still uses the literal jellyfin_only. It works, my Plex-only items come back correctly, they are just labelled presence: "jellyfin_only" on a stack with no Jellyfin.

    Since these descriptions are the contract the model reads, this can have it tell a Plex user that Jellyfin supplied the answer. A neutral media_server_only, with jellyfin_only kept as a deprecated alias if you need compatibility, would settle it.

    One code-level thing I could not reproduce and am flagging as unproven rather than a bug: in externalIds, a non-empty Guid array returns early, so the legacy com.plexapp.agents fallback is unreachable for any row whose Guid children are all unrecognised. On my library that case does not occur, every row either has proper imdb/tmdb/tvdb children or an empty array, so I have no evidence it ever fires. Mentioning it only because you asked people to assume parts are wrong.

    On the fixtures

    I want to run capture for you and I stopped before doing it, so you know why. Your comment said account names and my public IP are anonymised and that is true, anonymisePlexAccounts and redactPlexSessions both do what you said, and the refuse-to-write gate on surviving secrets and hosts is a good design.

    But the script header says redaction is secrets-only by design, and the plex endpoint list captures /status/sessions/history/all and /library/onDeck with no anonymise function at all. For Jellyfin you wrote neutraliseWatchState and commented that watch history is the one genuinely personal thing in the fixture set. I agree with that comment, and the Plex side has no equivalent, so as it stands capture would commit my full watch history and current resume list to a public repo.

    Separately, redactPlexSessions only rewrites Player.remotePublicAddress, while the session shape your own types carry includes User.title, which is a username and is not anonymised anywhere.

    Add a Plex analogue of neutraliseWatchState over those two endpoints and scrub User.title on sessions, and I will run capture the same day and send you the fixtures.

    Happy to re-test whenever you push.

  3. bardesss commented on Sep 1, 2026

    @bardesss
    Owner

    This is a great report, thank you. Everything below is pushed and the preview-plex tag is rebuilt, so a fresh pull gets all of it.

    The duplicate was my fault and you were right. I had actually decided not to dedupe, on the reasoning that the Jellyfin adapter concatenates its two reads the same way and nobody had complained. That was me matching a bug rather than a behaviour. Now deduped by rating key, keeping the now_playing row for the device, and blank ids are excluded from the comparison rather than matching each other like you warned.

    Scan state now reads /library/sections. I dropped /activities entirely, your option was better and it costs no extra call since #sections() already fetches it. refreshing is checked for true, 1 and "1". I also took scannedAt for lastCompleted, so plex now reports one in stack_health like Radarr and Sonarr do. Thank you for triggering a real scan to check that, it is the sort of thing I could not have got right by reading docs.

    /search sends includeGuids=1 now. Good catch, and thanks for checking that /library/metadata does not need it, that saved me a round trip.

    History paging was fixed on the right side of the filter, and it also now sends sort=viewedAt:desc, which I had not thought about. If the default sort turns out to be ascending the old code would have truncated from the oldest end while the tool promises newest first. I would like to know if that parameter spelling is right.

    Related, a reviewer pointed out that history rows probably carry viewedAt rather than lastViewedAt, which is what I was reading. It now takes either. Worth confirming which one your server actually sends.

    counts is renamed to plex:seasons. You were right that the number is series, not episodes, and the same key was wrong on the Jellyfin side too, so that is fixed for both.

    allow_other_users: true is now refused for plex at config parse, since the token only ever sees one account. Your point about a managed user's token being labelled as the owner is real and I cannot fix it without plex.tv, so it is documented as a known limit.

    On get_library still saying Jellyfin: the description is fixed. I left the literal jellyfin_only value alone for now. It is a published output field and renaming it is a breaking change I would rather do deliberately with a release note than slip into this PR. You are right that it is wrong on a Plex-only stack.

    On capture, you were right to stop, and more right than you knew. I added a Plex watch-state neutraliser, and then a reviewer pointed out it did not actually solve the problem: a history row exists because you watched that thing, so scrubbing the timestamps and leaving the titles still publishes your viewing record. The Jellyfin one gets away with it because it neutralises library listings, where a title is not evidence of anything.

    So titles, series names and thumb/art/key URLs on history and onDeck are now replaced with synthetic placeholders, deviceID is scrubbed, and the history capture is capped at 5 rows. ratingKey and accountID stay real because the adapter's filtering has to keep being exercised. Library listings keep their real titles, those are genuinely not sensitive and they make the fixtures much more useful.

    Whenever you have time. And if capture still shows you something you would not want committed, tell me and I will fix that before you send anything.

  4. Svnow132 commented on Sep 1, 2026

    @Svnow132
    Author

    Pulled the rebuilt preview-plex (digest 9e7abc53, image created 2026-09-01T06:04:35Z) and re-ran the battery. Five of the seven are fixed on my server. Your two questions are answered below with the raw reads. Capture is still not safe to run, I have one naming point on the counts fix, and I found a bug in the fixture pipeline that is not a privacy issue at all.

    Everything below is measured against Plex 1.43.3.10896, one server, one library. Where I say something is confirmed, that is the scope.

    Your two questions

    sort=viewedAt:desc is the right spelling. On this server the default order is ascending, so the parameter is doing real work rather than just formalising the existing order. Same three rows, X-Plex-Container-Size=3:

    query first row viewedAt
    no sort 1774497322 (oldest)
    sort=viewedAt:asc 1774497322
    sort=viewedAt 1774497322
    sort=viewedAt:desc 1788246399 (newest)

    So on the tested server the pre-fix code was paging from the oldest end while the tool promised newest first.

    Plex also rejects a malformed sort rather than ignoring it. sort=bogusField:desc returns HTTP 400, and so does a bad direction on a good field (sort=viewedAt:sideways). I only tried those two forms, so I would not claim every possible typo fails loudly, but the parameter is clearly validated rather than silently dropped.

    For a second source that is not my server: python-plexapi's PlexServer.history() sends {'sort': 'viewedAt:desc'} against this same endpoint (plexapi/server.py, the history method). Same field, same direction suffix. So the spelling is right independently of what I measured.

    History rows carry viewedAt. There is no lastViewedAt on them. Full key set, identical on every row of /status/sessions/history/all:

    accountID, deviceID, grandparentArt, grandparentKey, grandparentThumb,
    grandparentTitle, historyKey, index, key, librarySectionID,
    originallyAvailableAt, parentIndex, parentKey, parentThumb, ratingKey,
    thumb, title, type, viewedAt
    

    Keep reading both spellings though. lastViewedAt is what /library/onDeck sends, and /library/metadata/{ratingKey} returned lastViewedAt for me directly. So neutralisePlexWatchState checking for both is right for all three of those shapes.

    Confirmed fixed

    Scan state. stack_health returns {"service":"plex","running":false,"lastCompleted":"2026-09-01T08:19:41.000Z"}. The permanent blocked is gone. That timestamp is the max scannedAt across my three sections and matches the Movies section exactly (scannedAt=1788250781), so the epoch conversion is right.

    Playback dedupe. I put a real session on a rating key that was already sitting in onDeck, so the collision was live rather than hypothetical. Before, that returned 12 items with rating key 1357 present twice. Now it returns 11, 1357 appears once as now_playing, and it carries device. That is the behaviour you described.

    includeGuids=1. A library search hit now comes back with "ids":{"imdb":"tt5897304","tmdb":67075,"tvdb":307375}. It had no ids before.

    History paging on the filtered side. This one has a clean numeric check here. Raw /status/sessions/history/all reports totalSize 443 server-wide, and the account breakdown is 442 rows for accountID 1 plus 1 row for a second account. get_playback scope=history now reports total: 442, so it is filtering first and paging the filtered list. Newest first confirmed, and offset: 439 returns the last three, ending on item 48130, which is the same row the raw ascending read shows as oldest. The walk is consistent across the full range.

    get_library wording. Fixed. Leaving the literal jellyfin_only for a deliberate breaking change later seems right to me.

    On the counts rename

    I would push once more on the name, but more weakly than my last report, because there is a defensible reading I did not account for.

    The number is a series count. Your own comment in library.ts says listUserSeasons returns one row per series, and on my library:

    source count
    counts["plex:seasons"] reported 362
    shows in the section (type=2) 363
    seasons (type=3) 1288
    episodes (type=4) 23506

    362 is the show count less one, and the one is a show with no external id that the filter at the end of listUserSeasons correctly drops.

    The defensible reading is that :seasons names the source operation, the companion dataset that listUserSeasons produces, rather than asserting each row is a season. If that is the intent then it is not a bug and I would not want you to change it on my say-so. But sitting in a counts map next to radarr: 576 and sonarr: 382, which are both row counts of the thing they name, a reader is likely to take 362 as a season count, and the real season count is 1288. plex:series would remove the ambiguity. Your call which reading you meant.

    Same question applies to jellyfin:seasons, which by your comment got the same rename, though I have no Jellyfin server to measure against.

    One small related thing: counts.plex is 1348 on my server, which is 553 movies plus 363 shows plus 432 items in a Bumpers section. It is a truthful count of what Plex indexed, but it is not comparable to the Radarr and Sonarr numbers sitting beside it, and any bumpers or similar section will make it look inflated to someone reading the three together.

    Capture, still not safe to run

    I did not run npm run capture. I pulled one real /library/onDeck row from my server and ran your actual anonymisePlexHistory and redact over it in the order capture-fixtures.ts applies them, so what follows is what the fixture file would have contained for that row.

    Titles become placeholders. The row is still identifiable:

    title:             "Fixture Title 1"
    grandparentTitle:  "Fixture Series 1"
    parentTitle:       "Fixture Season 1"
    titleSort:         "Fleeting Moment of Happiness - Kumachi and Ginny"   <- real episode title
    grandparentSlug:   "one-piece"                                          <- real series
    summary:           "Kuma and Ginny live peacefully in the Sorbet Kingdom eight years after..."
    studio:            "Toei Animation"
    Role[].tag:        ["Mayumi Tanaka","Kazuya Nakai","Mari Yaguchi"]
    grandparentArt:    "/library/metadata/1212/art/1775125667"
    grandparentTheme:  "/library/metadata/1212/theme/1775125667"
    Media[0].Part[0].file:
      "/data/media/tv/<Series>/Season 22/<Series> (1999) - S22E46 - <Episode Title> [WEBDL-1080p Proper][EAC3 2.0][h265]-<GROUP>.mkv"
    

    art, thumb, key, parentThumb, grandparentThumb, grandparentKey and parentKey are all blanked correctly.

    The root cause is structural rather than a missing field or two: anonymisePlexHistory maps only top-level keys, and onDeck rows are nested. Anything inside Media, Part, Role, Director, Writer, Producer, Guid or Image passes through untouched today, and any nested field Plex adds later will too. Media[].Part[].file is the one that matters most on this row, since it carries the series, season, episode title and release group in a single string, and the library's directory layout with it.

    The fix I would suggest, in two halves

    Half one: stop receiving most of it. Plex has server-side parameters for this, and they turn the worst item on that list into something that cannot be leaked rather than something that must be scrubbed. excludeElements and excludeFields are ordinary comma-separated query params. python-plexapi uses them as its default _EXCLUDES (plexapi/base.py), which is where I got the syntax.

    The full element list I tested, which is python-plexapi's own:

    excludeElements=Media,Genre,Country,Guid,Rating,Collection,Director,Writer,Role,Producer,Similar,Style,Mood,Format
    excludeFields=summary,tagline
    checkFiles=0
    

    Measured on /library/metadata/1357, same item each time:

    request Media Part.file summary Role keys
    baseline yes yes yes yes 45
    + excludeElements (full list above) no no yes no 43
    + excludeFields and checkFiles=0 no no no no 42
    excludeElements=Media alone, includeGuids=1 kept no no yes yes 46

    That last row is the useful one for you: excludeElements=Media on its own removes the entire Media[].Part[] subtree, so the file path never arrives, and includeGuids=1 still returns the Guid array you need for external ids. checkFiles=0 also stops Plex doing a file-existence pass it does not need to do for a fixture.

    Two things this does not solve, so I would not treat it as the whole answer:

    • titleSort and grandparentSlug survive both parameters. I checked. They still need the anonymiser.
    • I could not test whether excludeElements does anything on /status/sessions, because my session list was empty by the time I tried. It returns HTTP 200 with the parameter present, but that proves nothing on its own.

    Half two: make the anonymiser reach nested values. If you want the smallest possible change, JSON.stringify takes a replacer that is invoked for every key at every depth, so the key set you already have becomes recursive without restructuring anonymisePlexHistory at all. The alternative, and what I would pick for a fixture pipeline, is to invert it: project each row into an explicit allow-list of fields you want recorded instead of denying the ones you do not. A deny-list has to be updated every time Plex adds a field; an allow-list fails closed on fields nobody has thought about yet, which for a public fixture is the direction you want to fail in.

    Then the remaining specifics:

    1. titleSort, grandparentSlug, studio and the tag arrays (Role, Director, Writer, Producer) need the same treatment as title.
    2. grandparentArt and grandparentTheme were missed while their thumb and key siblings were caught. Same /library/metadata/{id}/... shape.
    3. Part[].key is a /library/parts/... path, if you keep Media for any reason.
    4. /library/onDeck is captured with no X-Plex-Container-Size, so it takes whatever the server returns. Mine returned 17 rows. History is capped at 5 and onDeck could use the same cap.

    /status/sessions needs more than redactPlexSessions

    A session row is the same class of record as a history row, and right now it only gets host and user redaction, so it keeps the real title, grandparentTitle, summary, grandparentSlug and Media[].Part[].file, plus two fields nothing currently touches:

    • Player.title, the client's display name. On my setup those are named after the people who use them, which I think is a common way to name a TV.
    • Player.machineIdentifier.

    User.title and User.thumb are handled correctly, and blanking thumb matters more than it looks, because the value on my server is https://plex.tv/users/<hex>/avatar?c=<ts> with a real account id in it.

    One thing I could not settle: Player carries both address and remotePublicAddress. Your PRIVATE_IPV4 regex covers address when the client is on the LAN, which is what I measured, but a remote client's address would be a public address and outside what that regex matches. remotePublicAddress is handled explicitly, so this may just be a question of whether address deserves the same explicit handling.

    My sessions list was empty for most of this test, so a capture run at that moment writes an empty fixture and leaks nothing. That is timing rather than a property of the code.

    The host redaction bug, not a privacy issue

    redact() replaces configured hosts by plain substring over every string value. My Plex is configured as http://plex:32400, so hostsOf yields the bare string plex, and every occurrence of those four characters anywhere in the body gets rewritten.

    This is the Docker service-name form (http://plex:32400, http://sonarr:8989) that your configuration docs use, so I would guess other adapters are exposed to the same class of problem, though Plex is the only one I can measure.

    The guid fields are the clearest case. In the single onDeck row I tested:

    guid:             "service.example.test://episode/682b5868101ed419724007e7"
    parentGuid:       "service.example.test://season/65593ad0b67b7b55555317a1"
    grandparentGuid:  "service.example.test://show/5d9c084fec357c001f9ab4d8"
    

    No plex:// survives. For scale, a single shows page from my library contains 362 plex:// values. The fixture would record a guid scheme no Plex server emits, which at minimum means the recorded input no longer matches what the adapter sees in production.

    It is not limited to guids, which is the part I had not appreciated. It hits ordinary prose. Scanning 553 movie rows on my server for the substring:

    "The Boy and the Heron"                    summary  "...a persistent gray heron, who perplexes and bedevils Mahito..."
    "Inside Out 2"                             summary  "...brand new, more complex emotions as a result..."
    "Rascal Does Not Dream of a Knapsack Kid"  studio   "Aniplex"
    "Tekkonkinkreet"                           studio   "Aniplex"
    

    Those become perservice.example.testes, comservice.example.test and Aniservice.example.test. Four hits in 553 rows, so it is not common, but it is silent and it lands in the committed fixture.

    The write gate does not catch any of this, because it only asks whether the literal host string survived, and by construction it did not.

    I also want to flag that I was wrong about the fix in my own head before I checked. A delimiter boundary does not work here, because plex:// has a delimiter immediately after the match. The fix has to be authority-aware:

    function redactHosts(value: string, hosts: readonly string[]): string {
      const configured = new Set(hosts.map(h => h.toLowerCase().replace(/^\[|\]$/g, '')));
      if (configured.has(value.toLowerCase())) return ANONYMOUS_HOST;
    
      return value.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]+/gi, candidate => {
        try {
          const url = new URL(candidate);
          if (!configured.has(url.host.toLowerCase()) && !configured.has(url.hostname.toLowerCase())) return candidate;
          url.hostname = ANONYMOUS_HOST;
          return url.toString();
        } catch {
          return candidate;
        }
      });
    }

    The property that makes this work is that plex://show/... parses plex as the URI scheme, not the authority, so it is left alone unless the authority itself matches a configured host. Exact whole-string matches are still handled, for the fields that hold a bare host with no scheme. Comparing against url.host rather than url.hostname keeps the port in the comparison.

    One caution if you go a different route: your current split/join is a literal match, so it has no regex-escaping problem. Building a pattern out of the configured host would introduce one, since an IP host like 192.168.7.37 used unescaped matches 192a168x7y37 as well. Worth escaping metacharacters if the fix ends up regex-shaped.

    A fixture containing a plex:// guid and a titleSort would pin this as a regression test, which seems better than a comment.

    Last thing, and I have not verified it, so treat it as a question rather than a finding: secretsOf values go through the same substring replacement. If a short or common credential value is ever configured, it would corrupt unrelated text the same way. A minimum-length guard before substring-replacing a secret might be worth considering.

    Happy to re-run the whole battery on the next build, and to run capture for real once the fixture side is closed.

  5. Svnow132 commented on Sep 1, 2026

    @Svnow132
    Author

    Four more from a second pass over the capture path, plus one thing worth being precise about. The first is a direct consequence of a fix from this round, so it is the one I would look at first.

    The history fix left the capture script behind. The adapter now sends sort=viewedAt:desc (plex.ts:370). The capture script still sends no sort (capture-fixtures.ts:495), and since the default is ascending, the fixture gets recorded from the opposite end of the list to the one production reads. The two 5-row windows on my server:

    capture (no sort):        ratingKeys 48130, 8060, 48131, 48153, 47553
                              viewedAt 1774497322 .. 1775210373, ascending
    adapter (viewedAt:desc):  ratingKeys 145030, 130618, 217697, 217861, 62551
                              viewedAt 1788246399 .. 1787897495, descending
    

    No overlap at all. The comment just above that capture line still says the query "matches the query form PlexAdapter#getWatchHistory sends", which was true before the sort went in.

    The sizes differ too: PAGE_SIZE is 500 and the capture hardcodes 5. Five rows is reasonable for a shape fixture, but it does mean nothing in the fixture set exercises the 500-row page boundary, the second-page path, or the repeated-page guard.

    Real Plex account ids stay in the fixtures. anonymisePlexAccounts replaces name, and the session and history anonymisers deliberately keep User.id and accountID because the adapter's filtering matches on them. That reasoning is sound, but the values do not have to be the real ones. On my server /accounts returns about 103 rows, and three of them carry real plex.tv account ids next to the names that do get replaced. One consistent synthetic id, mapped the same way everywhere it appears, would keep every join the tests rely on while putting nothing real in the repo.

    /accounts is also captured with no X-Plex-Container-Size, same as onDeck.

    The metadata-detail fixture may not cover the code it exists for. The capture picks the first ratingKey from the section listing, and nothing requires that item to have a file. On my server the TV section's first item is ratingKey 211802, type: show, with no Media, no Part and no file. getMediaDetails reads Media[0].Part[0].file and size, so a fixture built from a row like that never contracts the mapping it is meant to prove. Both of my movie sections do return file-bearing first items, so whether this bites depends on the section and the server. Selecting the first row that actually has a Part would make it deterministic.

    Two more from reading rather than hitting them, so treat them accordingly. PRIVATE_IPV4 is IPv4 only, so a ULA, link-local or loopback IPv6 literal would pass through unredacted. I looked across /accounts, /identity and /status/sessions on my server and found no IPv6 at all, so I cannot show you a real case. Separately, in #paged the ignored-paging guard only fires when firstKey !== undefined && firstKey === previousFirstKey, so if a server ignored the paging parameters and the leading row happened to have no ratingKey, the guard would not trip and the loop would run to its page cap instead.

    Scope, so my last comment does not read as worse than it is

    Everything in that comment was about scripts/capture-fixtures.ts, and I do not want it taken as "the adapter leaks". It does not. get_playback, get_library at detail: "full", search_media and get_media_details asked by title all return small projections with no file path, no titleSort and no grandparentSlug.

    The one exception is deliberate and worth naming so nobody trips over it later. get_media_details with service: "plex" and an id returns path and overview, mapped straight from Media[0].Part[0].file and summary at plex.ts:631 and plex.ts:629:

    path:     "<<untrusted:plex.file>>/data/media/tv/<Series>/Season 22/<Series> ... .mkv<</untrusted>>"
    overview: "<<untrusted:plex.summary>>Kuma and Ginny live peacefully in the Sorbet Kingdom ...<</untrusted>>"
    

    That looks right to me. Handing an operator their own file path is the point of a raw per-service view, and it is how you diagnose a join that looks wrong. The reason I am spelling it out is that the fence around those values is prompt-injection containment rather than privacy redaction, and those two are easy to conflate. The accurate scope of my last comment is that the capture script is the only path where any of this becomes public.

    One last thing, this time about something I got wrong rather than something you did. I had a fifth finding drafted claiming the index-keyed synthetic placeholders in anonymisePlexHistory produce spurious diffs whenever onDeck reorders. That is wrong and I did not send it. When rows reorder, index 0 still yields Fixture Title 1, so the placeholder text at each position is unchanged. Any churn in those fixtures comes from the real ratingKey values moving, not from the placeholders. Your comment about determinism holds as written.

  6. bardesss commented on Sep 2, 2026

    @bardesss
    Owner

    All five are fixed and pushed, preview-plex is rebuilt.

    The sort drift was my own fix breaking the capture, which is a bit embarrassing. I added sort=viewedAt:desc to the adapter and never looked at the capture script, and the comment above it kept claiming the two matched. Fixed, and both now build the path from one place so they cannot drift again.

    I also audited every other plex capture endpoint against what the adapter actually sends. History was the only one that had drifted, the other eight matched. There are now parity tests for search and section-all that fail if a future change moves one side and not the other, since that is clearly a mistake I can make twice.

    On the 5 versus 500 rows: I left the capture at 5, that is the right size for a shape fixture. The page boundary, second page and repeated-page guard are all covered by hand-built tests rather than captures, so nothing is going untested there.

    Account ids are synthetic now, mapped consistently so the same real id becomes the same fake one everywhere it appears and every join the tests rely on still holds. You were right that keeping them real was not actually necessary for the filtering to be exercised. /accounts is capped too. One thing I cannot confirm from here: whether Plex honours the container size parameter on /accounts specifically. If your accounts.json comes back with 103 rows instead of 5, that is the answer and I will do it differently.

    metadata-detail now picks the first row that actually has a Part, falling back to the first row if none does. Good catch, a fixture that never exercises the file mapping it exists for is worse than no fixture.

    IPv6 is redacted now, and the paging guard no longer depends on the leading row having a ratingKey.

    Thank you for the scope note. You are right and I would not want it read that way either. The distinction you drew is the one that matters and I had not seen it stated that cleanly: the fence around path and overview is prompt-injection containment, not privacy redaction. Two different jobs that happen to look similar in the output. get_media_details handing an operator their own file path is the point of the raw per-service view, and I am keeping it.

    Also noted that you caught your own fifth finding before sending it. Genuinely useful to know which things you checked and discarded, not just the ones that survived.

    Whenever you get to capture.

  7. Svnow132 commented on Sep 2, 2026

    @Svnow132
    Author

    /accounts honours the container size. Uncapped it returns 103 rows, with X-Plex-Container-Start=0&X-Plex-Container-Size=5 it returns 5. So the cap works and that endpoint will record five rows.

    I checked the account cap, the account id types, the section row shapes and the IPv6 false-positive behaviour against my server. The paging guard and the history sort are code and test reads only, since nothing here ignores paging parameters and my history is 443 rows against a PAGE_SIZE of 500, so it never reaches a second page.

    Account ids. All 103 id values on my /accounts are JSON numbers, so anonymisePlexAccounts's typeof a.id === 'number' fires on every row here. Two things I could not settle from my server. That check is stricter than the mappedId helper you use for User.id and accountID, which also accepts a numeric string, so accounts would be the one place a string-valued id survives while the other two are mapped. And mappedId converts with Number() without a safe-integer check, so two distinct digit strings above Number.MAX_SAFE_INTEGER would collapse onto one synthetic id. I have no evidence Plex emits either shape, so both are worth a decision rather than a fix.

    The mapper preserves some real ids, and it is positional rather than just one value. next starts at 1001 and increments once per newly seen non-owner, so the nth distinct non-owner id survives unchanged whenever its real value happens to be 1000 + n:

    input:  1 -> 1     4000 -> 1001   1002 -> 1002   777 -> 1003   1004 -> 1004
                                      ^^^^^^^^^^^^                 ^^^^^^^^^^^^
    

    The existing test uses 78901234, which cannot expose this. Starting the counter above the largest real id seen in the run, or using negative values since Plex ids are positive, would close it by construction. No two real ids ever collide onto one synthetic, so the join the fixtures rely on is safe either way.

    Parity tests. I found three, covering history, section-all and search, and they construct a real PlexAdapter against a stub and assert on the URL it actually sends. That means the dimensions they assert will fail if the two sides drift. Worth noting that history and section-all compare selected parameters rather than the whole query, only search compares all of it, and the adapter does not import plexCapture.ts, so an unasserted parameter could still move on one side only. That still seems like the right trade to me. I also spot-checked your audit of the other endpoints against what the adapter sends and agree they match, with /accounts being the one deliberate difference you documented.

    Five rows. Agreed. I found the hand-built tests for the second page, the full-page boundary and both ignored-paging cases, so a five-row shape fixture is the right size.

    IPv6, one range gap. Zero matches across the payloads I sampled from this server, so I saw no false positives in that dataset. I have no IPv6 anywhere here, so I could not exercise a true positive. Reading the pattern rather than running it, fe80::/10 fixes the top ten bits, so the range runs fe80 through febf, but the alternation matches only the literal fe80:

    fe80::1  matched      fe81::1  missed      fe90::1  missed
    fea0::1  missed       febf::1  missed      fc00::1  matched
    

    fc00::/7 and ::1 are both covered correctly. Separately the tail allows zero-length hextets, so fc00: and fd00::: also match. That is harmless for redaction, since over-matching a malformed literal costs nothing, but it means the pattern is a token matcher rather than a validator if you ever reuse it.

    metadata-detail. The fix works here, though only because my first section is Movies and all five captured rows carry a Part. The limiting step is section selection rather than row selection: section-all is built only from firstSectionKey, and the helper falls back to the first row when none in that five-row page has a Part. On my TV section I pulled every row, not a sample:

    rows: 364 | types: {"show": 364} | rows with Media[0].Part[0]: 0 | rows with any Media key: 0
    

    The season level below has none either: 97 season rows across 25 shows, none with a Media key, while every episode sampled carries a Part. So on a server whose first section is a TV library, the capture would land on a Part-less row and the fixture would not contract Media[0].Part[0].file. Walking sections until one yields a Part-bearing row would close it.

    Paging guard. Read only, so treat this as reasoning rather than a measurement. Comparing consecutive page leaders can throw when paging did advance, since ratingKey identifies media rather than a viewing event, and two adjacent pages could legitimately share a leader. That needs a run of identical consecutive ratingKey values spanning a page boundary, so at least 501 at PAGE_SIZE 500. The longest such run in my full 443-row history is 115, so I cannot produce the case, and it looks unlikely rather than impossible.

    The three items from my 09-01 comment

    I think these fell between the two reports rather than being declined, so I am restating them plainly rather than assuming. Your five-fix reply answers #180 (comment), and these three are from the comment before it.

    One, the anonymiser still reaches only top-level keys. At a632fae, anonymisePlexHistory maps title, grandparentTitle, parentTitle, originalTitle, the thumb and key fields, and accountID. Not handled: titleSort, grandparentSlug, summary, studio, grandparentArt, grandparentTheme, and anything nested inside Media, Part, Role, Director, Writer, Producer, Guid or Image. Media[].Part[].file is the one that matters most, since it carries series, season, episode title and release group in one string.

    Two, the server-side exclusion parameters are not adopted. capture-fixtures.ts uses none of excludeElements, excludeFields or checkFiles. I measured what they buy per endpoint this time rather than on one metadata row:

    endpoint removed by exclusion still present
    /library/onDeck Media[].Part[].file, Role, summary titleSort, grandparentSlug, studio, grandparentArt, grandparentTheme, originalTitle
    /status/sessions/history/all nothing left to remove grandparentArt
    /library/sections/1/all Media[].Part[].file, Role, summary studio

    So the parameters remove the file path outright, which is the item I would least like to see committed, but they are not the whole answer and the anonymiser still has to cover the rest. History is much cleaner than onDeck at baseline, which surprised me.

    Three, the host redaction. redact() is unchanged, so the host pass is still hosts.reduce((acc, host) => acc.split(host).join(ANONYMOUS_HOST), ...). Re-measured on the current head over 500 movie rows:

    changed fields: {"guid": 500, "summary": 2, "studio": 2}
    before: plex://movie/5d776b8e96b655001fe14e31
    after:  service.example.test://movie/5d776b8e96b655001fe14e31
    

    Every guid in the page is rewritten, so those fixtures would record service.example.test://... where this server sends plex://.... Aniplex becomes Aniservice.example.test the same way.

    On the fix, with prior art

    I went looking at how other record-and-replay tools handle this before suggesting anything, and the useful finding is that you are not doing something unusual. VCR's filter_sensitive_data has exactly this bug. vcr/vcr#204, opened in 2012, reports that filtering the username admin out of a request URL also rewrote the word administrator in the response body, leaving <username>strator. Same shape as Aniplex.

    What matters is why VCR is stuck and you are not. The maintainer's reason there is that the substitution has to be reversible on playback, so it must be a literal round trip, and a regex cannot do a two-way substitution. A record-only fixture scrubber never un-substitutes, so that constraint does not apply here. His own workaround in that thread is also the answer: drop to the hook and run the replacement on interaction.request.uri only, so the body is never searched.

    Every tool I looked at that avoids the bug avoids it the same way, by addressing a structural slot instead of searching text. Azure's test-proxy has an explicit SanitizerScope of Uri, Header or Body, and its UriRegexSanitizer structurally cannot touch a body. Polly.JS exposes url.hostname and url.port as separate knobs. nock records the origin as its own scope key, and HAR keeps request.url as its own field the same way.

    Two shapes would work here, and both pass every case I tried, including the ones that defeat the obvious fixes:

    The smaller one anchors on authority position rather than a word boundary, which is the specific thing \b cannot express, since plex:// has a delimiter immediately after the match:

    new RegExp(`(?<=\\/\\/|@)(?:${alternation})\\.?(?=[:/?#"'\\s]|$)`, 'gi')

    A scheme is followed by // and never preceded by it, so plex://movie/... is rejected and http://plex:32400/... is not. Escape the alternation, because an unescaped 192.168.7.37 also matches 192a168x7y37.

    The other hands each URL-shaped substring to new URL() and rewrites only the authority slice. That one is correct by construction rather than by getting an anchor right, and the reason is a one-liner:

    new URL('plex://movie/abc').protocol  // 'plex:'   the scheme
    new URL('plex://movie/abc').hostname  // 'movie'   the authority, which is not "plex"

    Either way, one gap remains that I would rather name now than have you find later. Neither approach touches a bare authority with no scheme, so a Host: plex:32400 header or a percent-encoded nested URL would still pass through. Azure ships a separate header-scoped sanitiser next to the URI one for exactly that reason. A fixture holding a real plex:// guid alongside a real configured URL would pin the whole thing as a regression test.

    Where capture stands

    Authority-aware host redaction is the blocker I can demonstrate on my own payloads. Before I would call capture ready I would also want the nested-field coverage settled, since that is what actually decides whether my file paths and episode titles land in the repo, and a decision either way on the exclusion parameters.

    The smaller items are not blockers and I would not hold capture for them: the positional id survival, the fe80 range, and the mappedId integer conversion. One I could check and it is fine, so it needs no action: onDeck calls anonymisePlexHistory without the shared mapper, unlike history, but no /library/onDeck row on my server carries accountID at all, so nothing is exposed there today. It is an inconsistency rather than a leak.

    Say the word once redaction and the nested fields are settled and I will run capture and send the whole set.

  8. bardesss commented on Sep 2, 2026

    @bardesss
    Owner

    Thanks for confirming the container size, and for the three restated items. You were right that they fell between reports rather than being declined.

    All three blockers are done, plus the smaller ones. But before you run capture, one thing you should know, because it would have wasted your evening.

    The host fix I made would have aborted your run on the second endpoint. I fixed redact() to only rewrite authority positions, and completely forgot the safety gate next to it, which still did a blind includes() check. Your sections fixture contains agent: "tv.plex.agents.movie" and scanner: "Plex Movie", so the gate would have found "plex" surviving, refused to write, and exited. Same shape as the sort drift: I fixed one side and left the other. The gate and the scrubber now share one predicate so they cannot disagree again.

    Host redaction is authority-aware now. I went with the anchored regex rather than the new URL() approach, since the URL version still needs a regex to find URL-shaped substrings first. Your plex:// guids survive, Aniplex survives, http://plex:32400/... redacts. The bare-authority gap you named is real and documented in a comment rather than papered over. Thanks for the VCR dig, the reason they are stuck and we are not was the useful part, and it is what made me confident the anchored version is safe here rather than just convenient.

    Nested fields are covered, by a recursive walk rather than a key list, since a key list drifts the moment Plex adds a field. Media[].Part[].file included.

    On the exclusion parameters, I took them selectively. history and onDeck now request them, since #commonPlayback never reads Media, Part, Role or summary there, so not fetching the file path beats scrubbing it. section-all and metadata-detail deliberately do not, because getMediaDetails genuinely reads Media[0].Part[0].file and the fixture has to keep contracting that. Excluding there would have recreated the drift problem in a new place.

    Three more that a review caught after your list, all of which would have put real data in the repo:

    • /accounts rows carry key: "/accounts/<real id>" and a thumb pointing at plex.tv/users/<uuid>/avatar. I had remapped id and left both of those, so the real id came straight back and the uuid identified every shared user in your rows.
    • Top-level guid, parentGuid and grandparentGuid survived on history and onDeck. Those name the exact episode, which is the entire thing the anonymiser exists to sever.
    • Your section walk could have landed on a photo library. Every photo has a Part, so the Part-bearing search would have happily picked five of your photos with file paths and titles. Section keys are now filtered to movie and show types.

    Also fixed: sessions rows are scrubbed as a viewing record now rather than just for the IP, including Player.title and machineIdentifier, since a device called something like "Firstname's iPhone" is not much better than a name. Image[].alt was claimed as covered in a commit message and was not. Percent-encoded IPs slipped past PRIVATE_IPV4 because the word boundary never fires in %2F127.0.0.1%3A32400. And fe80::/10 now covers the whole range rather than the literal.

    The positional id survival, the safe-integer conversion and the accounts id type are all done too. The paging guard now fingerprints the whole page, which closes your leader-collision case as well.

    preview-plex is rebuilt. I think capture is ready, and if it is not I would rather find out from a refused write than from something landing in the repo. Whenever suits you.

  9. Svnow132 commented on Sep 2, 2026

    @Svnow132
    Author

    Capture ran. Twice, actually, and both runs wrote all nine fixtures with the gate never firing, including sections, which carries agent: "tv.plex.agents.movie" and would have stopped the old gate on the second endpoint exactly as you predicted.

    I ran it from a checkout of 2ad260e in a node:24-alpine container on the same Docker network as Plex, with a Plex-only config whose url is http://plex:32400, so hostsOf() produced the short host that caused all the trouble. Then I ran your own test suite with the captured files in place, and scanned every written fixture for every string value from the raw payloads.

    What holds up, measured rather than read. No configured host survives in the authority form the scrubber recognises, and service.example.test does not appear in these captures because no body carried one. The 76 plex:// guids in the library listings are untouched and the 48 on the watch-state rows are synthetic. Studio names survive intact. On the onDeck, history and sessions rows every title, slug, summary, tagline, studio, art, theme, Image[].alt, Image[].url, Guid[].id and person name is synthetic or blank, Media[].Part[].file is empty, and the onDeck rows carry no Media, Role or summary at all, so the exclusion parameters took effect. /accounts rows are id 1 then -1 to -4 with key and thumb empty on every row. The sessions row has Player.title synthetic, Player.machineIdentifier empty, both addresses replaced with documentation-range placeholders, and the user reduced to viewer. I also executed the regexes: the percent-encoded 127.0.0.1 inside a transcode URL is redacted, a version string is not, and fe81 through febf are now caught while fec0 is correctly left alone. The whole-page fingerprint closes the leader-collision case I raised, read only on my side since nothing here pages. The movie/show section filter had nothing to exclude on this server, all three of my sections are one or the other, so that one is unexercised too.

    The sessions fixture has a real row this time. I could not get anything to play on a device, so I registered a client by sending /:/timeline with identifier=com.plexapp.plugins.library, a client identifier, a session identifier and X-Plex-Device-Name, every three seconds. Without that identifier parameter the same pings register nothing. So Player.product reads FixtureCapture in that row rather than a real app name. I cleared the resulting watch state afterwards.

    Your test suite, with my fixtures dropped in. 2224 of 2225 pass. The sole failure is the repository's own fixture-safety guard rejecting the captured identity file, and it is the finding:

    FAIL test/fixtures.test.ts > committed fixtures > contain no secret-shaped content
      file:   test/fixtures/plex/identity.json
      path:   $.MediaContainer.machineIdentifier
      reason: long opaque value that is not an id-named field
    

    identity has no anonymiser, so the server's real 40-hex machineIdentifier goes straight into the file. Your own unverified-identity.json uses abc123def456 there, and fixtures.test.ts rejects the real one, so capture currently writes a file CI refuses. The adapter never reads it.

    What else survives, and is not read by the adapter

    I grepped plex.ts for each key, so "not read" means the name does not appear in the adapter.

    • sourceTitle on 45 of the search rows is the server's friendlyName. Mine is a user-chosen name, so I do not want it committed. Not read.
    • Library section uuid. Three in sections, and librarySectionUUID on 17 of 18 onDeck rows and 45 search rows. Stable per-library identifiers. Not read.
    • Person tagKey and filter survive with the name scrubbed. On 4 of 18 onDeck rows and on the sessions row, Writer, Director, Producer and Role entries read tag: "Fixture Person 71" next to tagKey: "5d776b8e96b655001fe14e82", which is the plex.tv person id and resolves back to the person. Since the adapter reads none of those four arrays on either endpoint, adding them to excludeElements for history and onDeck removes the problem without a scrubber; sessions would still need both tagKey and filter scrubbed, or the same arrays excluded there.
    • CommonSenseMedia[].oneLiner on the sessions row is a unique sentence about the item, sitting on a row whose title, summary and tagline are synthetic. Not read.
    • File paths in the library listings. 34 distinct real paths across search, section-all and metadata-detail, plus the library roots in sections.json under Directory[].Location[].path. They carry my directory scheme and 21 distinct release-group suffixes. I understand why metadata-detail keeps Media[0].Part[0].file, and I agree the fixture has to contract it. But present is not the same as real. A synthetic path that keeps the shape, something like /library/movies/Fixture title 5 (2016)/Fixture title 5 (2016).mkv, contracts the mapping just as well: getMediaDetails fences the string and never interprets it, and Part[].size is the other thing it reads, so keeping size real and the path synthetic exercises both path and sizeBytes. These are mine to publish and I would rather not.

    Two notes on scope rather than findings. First, the walk in anonymiseNested is recursive, but what it does at each node is still an allowlist: IDENTIFYING_TEXT_KEYS, IDENTIFYING_SLUG_KEYS, GUID_STRING_KEYS and the person and tag arrays. That is why tagKey, filter and oneLiner survive, and it means a field Plex adds next year passes through until someone lists it. Recursion fixed the depth problem; it did not change the key-list nature of the thing, which is fine as long as it is not read as a general guarantee. Second, and the same way round, the gate and the scrubber now share one predicate, which means the gate can no longer catch anything the scrubber misses. The bare-authority and percent-encoded cases you documented are exactly the ones both now agree to let through. Also fine, just worth saying out loud since the gate used to be an independent check.

    And one on what "anonymised" means here. A scrubbed watch-state row still carries year, originallyAvailableAt, duration, contentRating and the rating values, and together those pin down any well-known title without a name. The adapter needs duration and viewOffset, so I am not asking for anything, just naming where it stops.

    Small one: plexAdapter.test.ts and contract.test.ts still read unverified-identity.json and unverified-accounts.json by name, so the captured identity.json and accounts.json sit beside them unused. Expected at this stage, noting it so nobody reads the passing suite as proof the captured files were exercised.

    Where this leaves the handover

    I have the nine files and I have reviewed every one. I am holding them rather than attaching them, because an attachment on a public issue still publishes the values, and right now they contain my server id, my server name and my file paths. Once identity, sourceTitle and the paths are handled I will recapture from the next build and attach the set. Everything else above I would take or leave at your discretion.

  10. bardesss commented on Sep 2, 2026

    @bardesss
    Owner

    All three blockers are done, and I took the discretionary three as well. preview-plex is rebuilt from 11ba5c3.

    identity is anonymised. That one was embarrassing, the endpoint had no anonymiser at all and our own guard was right to reject the file. Capture was writing something CI would refuse.

    sourceTitle is scrubbed, and so are the section uuid and librarySectionUUID.

    On the file paths, you changed my mind. I had ruled that section-all and metadata-detail must keep the real Media[0].Part[0].file because getMediaDetails reads it and the fixture has to contract that mapping. "Present is not the same as real" is the bit I had not thought through. The path is fenced and never parsed, so a synthetic one with the same shape contracts it identically. Paths are synthesised from the row's already-synthetic title now, Part[].size stays real so sizeBytes is still exercised, and Directory[].Location[].path in sections is synthesised too.

    tagKey and filter were the worst of the batch. Scrubbing a person's name and leaving the id that resolves back to them is worse than doing nothing, because it looks handled. Writer, Director and Producer are excluded server-side on history and onDeck now, per your suggestion. For sessions I scrubbed rather than excluded, because I cannot verify that the exclude parameters behave the same way on /status/sessions and I did not want to guess at it twice in one round. The scrub is provably right without a live server, and it gives history and onDeck a second layer for free. oneLiner is gone too.

    Both your scope notes are correct and are now comments in the code, because they are the kind of thing that gets forgotten and then rediscovered as a surprise. The recursion fixed depth and did not change the allowlist nature of the thing. And the gate genuinely can no longer catch what the scrubber misses, which was a deliberate trade for making them impossible to contradict, but it does mean the two documented gaps are now agreed on by both rather than caught by one.

    Your point about year, originallyAvailableAt, duration and contentRating pinning a well-known title is fair and I am not going to pretend otherwise. The adapter needs duration and viewOffset, so the honest description is that these fixtures are scrubbed of identity, not of content.

    On the unverified- filenames: that is the merge gate working as intended. When your set lands I swap the tests onto the real files and drop the prefix, and that prefix disappearing from git status is the thing that says this adapter has actually been exercised. So you are right that a passing suite today proves nothing about your captures, and it is not meant to yet.

    Recapture whenever suits you.

  11. Svnow132 commented on Sep 2, 2026

    @Svnow132
    Author

    Recaptured from 11ba5c3 and your suite is green on my files: 2247 passing across 90 files, against 2224 of 2225 last time where the sole failure was the fixture guard rejecting the real machineIdentifier. That one is closed.

    All six verified by scanning the new fixtures against freshly fetched raw payloads, not just read. identity.machineIdentifier is empty and the real 40-hex appears nowhere. sourceTitle is empty on all 45 search rows and my server's friendlyName is absent from all nine files. Every one of the 36 nonempty file paths is synthetic, and the three library roots in sections.json are too; the 34 real paths and 21 release-group suffixes I counted last round are the before-figures from that capture, not something I re-measured today, but nothing matching them survives. Part[].size is left alone by synthesisePlexFilePaths, so sizeBytes is still contracted. Of the 103 rows /accounts returns, 26 carry plex.tv-scale ids: none of those 26 appear anywhere in the set, by id or by name, and the mapped ids come out 1 then -1 to -4. On sessions, all 14 tagKey values are empty, the 14 person filter values are empty, and oneLiner is a placeholder. The other 14 filter values on that row are taxonomy rather than people (genre=, country=, label=) and are untouched, which reads correct to me: I checked and the label ids resolve to agent-supplied keywords like Airplane and Guitar, not anything I created. The only IP literals left in the set are the two documentation-range placeholders.

    One thing still leaks, and the obvious fix does not catch it

    metadata-detail.json and section-all.json still carry my real librarySectionUUID, on the MediaContainer itself rather than on the rows.

    The row-level scrub works everywhere it runs: 45 search rows, 18 onDeck rows and the 3 uuid values in sections.json all come out empty. But redactPlexSearchRow spreads the container through unchanged and only maps container.Metadata:

    return {
        ...(body as Row),
        MediaContainer: {
            ...container,                       // container-level librarySectionUUID rides through here
            Metadata: container.Metadata.map(...)
        }
    };

    So a container-level copy survives even on an endpoint where the function does run. search is clean only because Plex does not send librarySectionUUID at container level for /search, not because anything scrubbed it. /library/sections/{id}/all and /library/metadata/{id} both do send it.

    That matters for what the fix is, because it is two-part and either half alone leaves the value in.

    synthesisePlexFilePaths(neutralisePlexWatchState(body)) at lines 566 and 578 skips redactPlexSearchRow, which line 535 has, and the docstring above synthesisePlexFilePaths already describes all three endpoints as one group. So adding the missing call at both sites is the reading the code invites, and on its own it would still ship the value, because the field is not on the rows in those two responses. But scrubbing the container inside redactPlexSearchRow on its own does nothing either, for the same reason in reverse: those two endpoints never call it. It needs both, the container handled and the function actually applied at 566 and 578.

    While you are in there, the name is part of what hid this. redactPlexSearchRow sanitises a whole library-listing response, not a row, and it is used by three endpoints of which only one is search. A name saying that would have made the container the obvious place to look.

    Worth a test either way, and there is a reason the current ones cannot catch it. Every case that exercises a row builds its body through the same helper:

    const search = (rows: Record<string, unknown>[]) => ({ MediaContainer: { Metadata: rows } });

    That container only ever holds Metadata, so none of those can put the field where it actually survives. The fourth case builds its own body, { MediaContainer: { version: '1.32.0' } }, and asserts the whole thing comes back unchanged, which is exactly what a container-level value would also do. A body carrying the field in both places at once would close it:

    { MediaContainer: { librarySectionUUID: '...', Metadata: [{ librarySectionUUID: '...' }] } }

    The sessions exclude question, answered on a live server

    You said you scrubbed rather than excluded on sessions because you could not verify that the exclude parameters behave the same way on /status/sessions. They do not, and you were right to be careful. I registered a session and asked the same server three ways:

    /library/onDeck        excludeElements + excludeFields   Media=- Role=- Writer=- Director=- Producer=- summary=-
    /status/sessions       excludeElements only              Media=1 Role=8 Writer=3 Director=1 Producer=2 summary=201
    /status/sessions       excludeFields only                Media=1 Role=8 Writer=3 Director=1 Producer=2 summary=-
    

    excludeElements is silently ignored on /status/sessions. Not rejected, not an error, just no effect: same row, same counts. The onDeck line is the control, same parameters, same request shape, everything dropped. So excluding instead of scrubbing on sessions would have looked correct in the code and changed nothing in the response, which is the worst of the available outcomes and exactly what your caution avoided.

    excludeFields is honoured there. So excludeFields=summary works on sessions today if you want the second layer for free, and the elements have to stay scrubbed.

    One note I am not asking you to act on

    metadata-detail.json still has real tagKey on 14 entries, real filter on 28, real person ids on Writer, Director and Producer, and a real CommonSenseMedia[].oneLiner.

    I raised tagKey and oneLiner last round about onDeck and sessions, and the argument there was that scrubbing a name while keeping the id that resolves to it looks handled without being handled. That argument does not transfer here. These three endpoints publish real title, summary and studio by design and we both agreed on that, so the film is openly named on the row and the person credits are public credits for it. Nothing about me is in those fields.

    I am only mentioning it because "oneLiner is gone too" is true of sessions and not of this file, and I would rather you know which it is than find out later. If you want them consistent that is your call, not a request from me.

    Where this leaves the handover

    Everything I listed as blocking is done, so this is the last item and it is a small one. I am holding the set one more build rather than attaching now, because the section uuid is a stable identifier for my server and it is exactly the kind of value I asked to keep out.

    Done criterion, unchanged from last round: your suite green on my capture, my own raw-to-fixture value scan clean, and nothing in the library listings I object to. The first is already true and the third has been true since you synthesised the paths. Fix the container-level case, rebuild, and I will recapture and attach the nine files the same day.

  12. bardesss commented on Sep 3, 2026

    @bardesss
    Owner

    Fixed, both halves. preview-plex is rebuilt.

    You were right that either half alone still ships the value, and I would probably have done just the first one if you had not spelled that out. redactPlexLibraryListing (renamed, since it sanitises a whole library-listing response and only one of its three endpoints is search) now scrubs the container as well as the rows, and it is actually applied at both sites that were skipping it.

    Your point about the test helper is the part I want to keep. Every row case builds its body through a helper whose container only ever holds Metadata, so none of them could put the field where it survives, and the fourth case asserts an untouched container comes back unchanged, which is exactly what the leak also does. That test was providing false comfort rather than no comfort, which is worse. There is now a case carrying the field in both places at once.

    I checked the other anonymisers for the same container-spread shape. neutralisePlexWatchState, anonymisePlexHistory and redactPlexSessions all build results the same way, but their endpoints aggregate across every library so Plex has no single librarySectionUUID to put at container level. That is reasoning, not a live measurement, so it is worth a glance on your scan rather than my word.

    Thanks for testing the sessions exclude question properly. Silently ignored is the worst of the three possible answers and the one I could not have guessed at. excludeFields=summary is added to sessions for the free layer, the element scrubbing stays exactly as it is since that is doing the real work, and there is a comment recording that excludeElements does nothing there, because "make these two endpoints consistent" is precisely the tidy-up someone attempts later.

    On metadata-detail's person ids and oneLiner: agreed, and leaving them. Your reasoning is right that the earlier argument does not transfer, since those endpoints publish real title, summary and studio by design and public credits for a publicly named film are not about you. I should also correct myself, "oneLiner is gone too" was true of sessions and I let it stand as though it were true everywhere. There is a comment next to it now so nobody scrubs it later on the strength of the old argument.

    One thing before you recapture: I merged main into the branch, so the head has moved to f55e455 and it now includes 1.20.0 plus some unrelated tool work. Nothing there touches the capture path, but you will want to pull rather than build from 11ba5c3.

  13. Svnow132 commented on Sep 3, 2026

    @Svnow132
    Author

    Recaptured from f55e455. Your suite is green on my files: 2395 passing across 97 files, no failures.

    The container-level UUID is gone from both files

    metadata-detail.json and section-all.json now come out with librarySectionUUID: "" on the MediaContainer itself. That is the field read directly, not a substring hunt. I also fetched /library/sections fresh and checked all three of my real section uuids against every one of the nine files: none appears anywhere, at container level or on a row. search.json still has no container-level field at all, which remains Plex's doing rather than yours.

    One boundary worth knowing rather than a request: redactPlexLibraryListing returns the body untouched when MediaContainer.Metadata is not an array, and your fourth test case pins that behaviour deliberately. For these three endpoints Metadata is always an array so it never bites, but the container scrub is reachable only through that guard.

    Your reasoning on the other three anonymisers, measured

    You asked for a glance rather than taking your word for it, so I read the container keys off the raw responses:

    raw /library/onDeck   librarySectionUUID at container: False
      keys: allowSync, identifier, mediaTagPrefix, mediaTagVersion, mixedParents, size
    raw history           librarySectionUUID at container: False   keys: size
    raw /status/sessions  librarySectionUUID at container: False   keys: size
    

    Your explanation holds on my server. I would not call it a Plex-wide invariant on one server's evidence, and neutralisePlexWatchState, anonymisePlexHistory and redactPlexSessions all preserve unknown container keys, so if any of those responses ever starts carrying the field it rides through the same way this one did. Nothing to change today.

    The six earlier fixes, re-verified rather than assumed

    The branch now also carries 1.20.0 and #190, so I re-ran the full suite and repeated the whole fixture scan instead of leaning on the earlier pass:

    • identity.machineIdentifier empty, and my real value absent from all nine files
    • server friendlyName absent from all nine
    • 26 plex.tv-scale account ids absent; those accounts hold three distinct non-empty names between them and none survives in a name, title, thumb or User slot; mapped ids come out 1, -1, -2, -3, -4
    • my three real library roots absent; all 36 file paths in the set are synthetic, 0 of them under a real root
    • Part[].size still real, 37 values, so getMediaDetails stays contracted
    • the only IP literals in the set are the two documentation-range placeholders

    sessions.json

    summary is absent, so excludeFields=summary is doing what the live test said it would. All 14 Role entries have empty tagKey and empty filter.

    This row carries no CommonSenseMedia, so the file does not exercise the oneLiner path at all. Your redactor would keep the key and replace the value rather than drop it, and I only kept the post-redaction fixture, so I cannot tell you from this capture why Plex omitted it. Flagging it as uncovered rather than as verified.

    metadata-detail.json, unchanged and expected

    8 Role, 3 Writer, 1 Director, 2 Producer, all with real tagKey and filter, and a real CommonSenseMedia[].oneLiner. That is the state we agreed to leave, on a row that publishes 10 Cloverfield Lane with its real title, summary and studio by design. Recording it so the next person reading the file knows it is deliberate.

    One thing for the merge

    test/contract.test.ts still reads unverified-accounts.json and unverified-identity.json. I found that out by deleting the fixture directory before my first capture run and watching exactly those two tests fail on the missing files, which is the gate working. Now that captured accounts.json and identity.json exist, those two dependencies can point at the captured filenames.

    Attaching the nine files. That satisfies my done criterion on all three parts: your suite green on my capture, every real value I checked absent from the fixtures, and nothing in the library listings I object to. Thanks for taking the container case seriously rather than patching the call sites and calling it done, and for marking your own reasoning as reasoning. That is the only reason I went and measured it.

    accounts.json history.json identity.json metadata-detail.json ondeck.json search.json section-all.json sections.json sessions.json

  14. bardesss commented on Sep 4, 2026

    @bardesss
    Owner

    Fixtures are in. test/fixtures/plex/ now holds your nine files, the unverified- prefix is gone from the repo, and the contract is declared for all nine endpoints rather than the two that had fixtures before. 2409 tests green across 97 files, and CI is green on the PR.

    I scanned the files myself before committing them rather than taking your word for it, since I am the one publishing them. Same result you got: no machine id, no token, no private IP outside the documentation range, no library uuids, no real paths, no server name. All 36 file paths synthetic, 3 library roots synthetic, and 300 guid-shaped values still present so the join stays contracted. The 14 tagKey and 14 metadata-static.plex.tv thumbs in metadata-detail.json are the set we agreed to leave.

    Two things your capture settled that I had listed as open. History rows carry only viewedAt and never lastViewedAt, so the adapter reading both was the right call and the preference order is correct. And none of the five captured movies has ever been watched, so viewCount and the view timestamp are not contracted on those rows, which is worth knowing rather than assuming.

    One thing your capture cannot settle, and the reason is our own doing. The onDeck resume versus next-up split and the history sort order are exactly the values the anonymiser synthesises before writing the fixture, so no capture can confirm them. I left those two sentences in the docs alone rather than claiming more than we know. If you ever feel like eyeballing an unredacted onDeck response on your own machine, that would close it, but I am not asking.

    Also worth saying: Plex publishes no OpenAPI document, so it cannot join the nightly drift job the way Radarr and Sonarr do. Its contract is the fields declared in the contract test, checked against your fixtures. That catches us breaking our own adapter and cannot catch Plex changing underneath it. Five of the ten services are in that position now, and I have written it down in CONTRIBUTING rather than leaving it implicit, because "the contract test covers it" is easy to read as more than it is.

    Thank you for this. You found four things that two rounds of code review missed, and every one of them was invisible without a real server. The capture script would have published your watch history, your file paths, your server id and your section uuids if you had just run it when I first asked, and the reason you did not is that you read it first. I have kept your measurements in the PR description so the next person can see what was actually checked rather than taking a green suite as proof.

  15. bardesss commented on Sep 4, 2026

    @bardesss
    Owner

    Merged in #188.

    Both halves of what you reported are now in. get_playback stopped answering "0 playing, 0 to continue" at people with no media server back in 1.18.1, and Plex support went in just now with your fixtures as the test data.

    For anyone finding this later, what shipped:

    • A read-only Plex adapter. Operator-supplied X-Plex-Token, your own server only, never plex.tv.
    • get_playback and get_library answer from Plex, and get_library joins it against Radarr and Sonarr on shared external ids, which was the thing you actually asked for.
    • diagnose and search_media work against it too.
    • Jellyfin and plex cannot both be configured, since the join needs exactly one counterparty.
    • Known limits, all documented: read-only so no marking things watched, and one Plex account per token because a local token cannot see other users without going through plex.tv.

    @Svnow132 did the work that made this mergeable. Four defects that two rounds of code review missed, every one of them invisible without a real server: scan state permanently reporting a scan in progress, the playing item counted twice, search results carrying no external ids at all, and watch history capped on the wrong side of its filter. One of those, the includeGuids=1 parameter, was the difference between the join working and every single item reporting as unmanaged.

    He also read the fixture capture script before running it and refused, which was right. As written it would have committed his watch history, his file paths, his server id and his library uuids to this repository. That took four passes to fix, and he checked each one against his own server rather than taking my word for it.

    qBittorrent is still unverified and #147 is open if anyone runs it.

    Closing this one. Thanks again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions