fix(stalker): only mint a temporary link when the row asks for one (#1364)

* fix(stalker): only mint a temporary link when the row asks for one

`create_link` ran on every Stalker playback. The reference client — the
portal's own `player.js`, mirrored by Kodi's pvr.stalker — mints a link
only when the catalog row sets `use_http_tmp_link` or `use_load_balancing`;
otherwise it plays the static `cmd` that `get_all_channels` /
`get_ordered_list` already returned. Neither flag was read anywhere in the
codebase, so every channel paid a round trip and gained a failure point the
reference client does not have.

One helper now owns the decision (`resolveStalkerStaticPlaybackUrl`), used
by `fetchStalkerPlaybackLink()` for ITV/VOD/radio, by the download path,
and by `StreamResolverService` for Favorites/Recently Viewed. Its guards
are deliberately wider than the flags alone and can only route a row back
onto the `create_link` path: no row to read flags from, a relative or
query-only command (the VOD `has_files` rewrite), a non-HTTP scheme, or a
loopback host. An episode always mints, since `series` selects it
server-side. Radio joins the same decision, so a station the portal proxies
now gets its link instead of playing a URL the portal never meant to serve.

Temporary links live ~5 s, so the audit that came with this: favorites and
recently-viewed persist the `cmd`, playback positions store ids, and the
main-process context map stores headers keyed by origin+path — none replay
a resolved URL. Downloads are the documented exception, and honouring the
flags shrinks even that, since an unflagged movie now yields a permanent
URL that survives retry.

`forced_storage` and `play_token` stay unwired, with the reasoning recorded
in the docs rather than left ambiguous.

The mock's ITV/radio rows now carry both flags, and the new
`static-channel-cmd` scenario (MAC 00:1A:79:00:00:0A) serves unflagged rows
with a playable command so the e2e can assert that NO `create_link` request
reaches the portal — verified to fail when the change is reverted, with a
companion test proving the recorder sees a link when one is due.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(stalker): keep temporary-link flags across VOD normalization

Codex P1 on #1364, and it is real. `buildStalkerSelectedVodItem()` narrows a
raw portal row to an explicit whitelist, and the two flags were not on it.
It feeds both `selectedItem()` — which the VOD playback path reads as
`linkFlags` — and, through `createStalkerVodItem`, the download payload. So a
flagged VOD row with an absolute HTTP `cmd` arrived looking unflagged and took
the static path, playing the portal's non-final URL instead of minting a link.

The direction of the failure is what makes it a P1: a dropped flag reads as
"no temporary link needed", so the whitelist fails OPEN. Both flags now sit on
`StalkerVodSource` / `StalkerSelectedVodItem` and on the whitelist, with the
consequence spelled out at the normalizer so the next edit does not quietly
undo it, and specs pinning all three normalizers plus a store-level test that
a flagged VOD still mints.

Also two things from re-reading my own diff:
- The radio path called `resolveStalkerStaticPlaybackUrl` and then handed the
  same row to `fetchStalkerPlaybackLink`, which runs that exact check again.
  Two copies of one decision is the divergence this PR exists to remove, so
  the outer call and its now-unreachable guard are gone.
- `portal-catalog-facade.ts` spells the flag shape out instead of importing
  `StalkerLinkFlagSource`; it now says why (`type:util`/`domain:portal-shared`
  may not depend on `type:data-access`/`domain:stalker`), so the obvious
  "reuse the type" cleanup does not get made and break the boundary lint.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(stalker): authenticate before serving a static collection stream

Second Codex P1 on #1364, and a regression this PR introduced. `create_link`
was also the request that warmed the portal session. Tokens live in memory
only (`StalkerSessionService.tokenCache` is a plain Map), and the collection
header builder reads the raw `getCachedToken()`. So a cold start from global
Favorites or Recently Viewed — the portal never opened this session — took the
static path, found no token, and handed a same-host gated stream headers with
no `Authorization`: a 403 on exactly the streams the header contract exists
for. The same raw accessor cannot tell a token negotiated for a pre-edit
identity from a current one.

`StreamResolverService` now calls `ensureToken()` before building a static
playback. It is the right primitive: handshake + `get_profile` with no link
minted, identity fingerprint validated, concurrent callers deduped, and an
immediate null for simple portals — and calling it keeps this change out of
`stalker-session.service.ts`, which PR 6 (#1354) is splitting.

Best-effort by design: a static URL may point at a CDN that needs no
credentials, so a failed handshake degrades to the token-less header set
instead of costing the user their playback. Both halves are pinned by tests,
and removing the call makes the cold-start test fail.

The portal routes need no equivalent and do not get one: an item cannot be
selected before its catalog has loaded, and every catalog load authenticates.
That reasoning is now written down rather than assumed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(stalker): warm the session at the choke point; keep downloads authenticated

Two more Codex findings on #1364, and the first one shows my previous commit
message reasoned too broadly.

P1 — I claimed the portal routes are "structurally warm" because an item
cannot be selected before its catalog loads. That is true of the routed portal
views, but not of the global collection detail, which calls
`setCurrentPlaylist()` and `setSelectedItem()` straight from a persisted row
with no catalog load in between and then goes through the STORE playback path.
A VOD opened from Favorites on a cold start therefore still played a same-host
gated stream with no Bearer token.

Rather than extend the per-route argument, the warm-up moved to the one place
every static return passes through: `fetchStalkerPlaybackLink()` now calls the
session before short-circuiting, covering ITV, VOD, radio and downloads at
once. `StreamResolverService` keeps its own call — its static branch does not
go through that function — but both now share a single primitive,
`ensureStalkerSession()` in `stalker-request.utils.ts`, so the two routes
cannot drift on when a session is required. Still best-effort, still outside
`stalker-session.service.ts` (PR 6 territory).

P2 — downloads cannot use that escape hatch at all: the main-process stored
header allowlist is User-Agent/Origin/Referer only, no Cookie or
Authorization, so a static same-host URL 401s where a minted one worked.
`startStalkerVodDownload` now classifies the candidate with the shared
`isStalkerStreamCredentialSafe()` and withholds the row — forcing
`create_link` — for anything portal-owned. A CDN-hosted movie keeps the
permanent URL that survives retry; a portal-hosted one keeps the minted URL
that carries its own token.

Both fixes mutation-checked: each reverted change fails exactly one test.
Docs corrected, including the overreaching "structurally warm" claim.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(stalker): record the cached-token revalidation trade-off

Codex flagged that the static path no longer self-heals a retired token, since
`ensureToken` returns a same-identity cache entry without a network call —
whereas `create_link` used to refresh it through `makeAuthenticatedRequest`'s
auth-failure retry.

The mechanism it posits does not exist on stock Stalker: per the 4.9.35
reference, handshake tokens have no TTL, and not sending the watchdog does not
invalidate auth (it only clears the admin panel's "online" flag). The real
residual vector is another device calling `get_profile` on the same MAC, which
is common enough on shared subscriptions to be worth naming.

Revalidating on every static playback would cost exactly the round trip this
change removes, so it is deliberately not done. Recorded as a known trade-off
with its mitigation (a running watchdog still self-heals within a ping cycle)
and handed to PR 6, where a refresh on an OBSERVED playback authorization
failure belongs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(stalker): tighten the token-revalidation trade-off wording

Greptile review feedback: the watchdog mitigation was the most important part
of that paragraph and sat behind the caveat. It now follows the MAC-sharing
vector directly, and the paragraph ends by naming what is actually left
uncovered — a same-host static stream played while no watchdog is up — so a
future reader can size the residual without re-deriving it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(stalker): prefer the live playlist row over a stale favorite snapshot

Codex P1 on #1364, and mine. `resolveStalker` reads its portal coordinates as
`item.stalkerPortalUrl ?? playlist?.portalUrl` — item first. The create_link
branch quietly corrected for that afterwards by re-reading
`applyOverride(playlist).portalUrl`, so the row won wherever it existed, which
is what the comment right above it already promised: "when the row exists it
wins over the item's snapshot of the portal URL (a repaired endpoint must beat
a stale favorite)". The static branch I added returns before that correction,
so it shipped the stale snapshot.

Consequences after a playlist edit: a same-host static URL matching the OLD
host gets the newly negotiated token and identity headers sent to the previous
portal, and a MAC-only edit pairs the new token with the old MAC cookie —
precisely the pairing `stalkerIdentityFingerprint` exists to prevent.

Both branches now derive the coordinates once, row-first with the repair
override applied, and fall back to the item's snapshot only for a playlist
that no longer exists — which is the role `buildStalkerPlayback` already
documents for it. Mutation-checked: restoring item-first precedence fails the
new test alone.

Also documents a local-only e2e hazard found while re-running the suite:
`mode: 'serial'` orders tests within one project, but chromium/firefox/webkit
run the file concurrently against the same mock server, so one project's
beforeEach reset can drop a session another is mid-test on — which is what a
lone auth-spec failure that passes on rerun actually is. CI never sees it; the
Web E2E job runs --project=chromium alone, and that command is clean (22/22).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(stalker): warm the session against the repaired portal configuration

Found while auditing my own static branch against the create_link path rather
than waiting for the next review round.

`executeStalkerRequest` applies the lazy-repair override on its first line, so
the create_link path always talks to the configuration a completed repair
proved good. The session warm-up I added did not: it handed `ensureToken` the
caller's pre-repair row, so a portal whose endpoint or mode had been repaired
would handshake against the configuration the repair had already rejected —
stranding the session precisely on the portals repair exists to rescue.

The override now happens inside `ensureStalkerSession`, mirroring
`executeStalkerRequest`'s first line, so every caller inherits the rule instead
of each having to remember it. Mutation-checked: dropping the override fails
the new test alone.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(stalker): fall back to create_link when a portal-owned static url has no session

Codex P1 on #1364. `create_link` was also the request that could FAIL, and a
failure is what triggers the lazy portal repair. A playlist still misclassified
as token-free, or pointing at an unrepaired endpoint, used to self-heal on that
failure and then play; the static path issues no request, so nothing fires and
the stream just 401s.

Its suggested remedy — routing a skipped warm-up through `repairPortal()` —
cannot be taken literally: a skipped warm-up is the NORMAL case for the many
legitimately token-free reseller panels, and probing each of them on every
playback would cost far more than the round trip this PR removes.

What is decidable without a request is whether we are about to serve a stream
we already know will fail. `ensureStalkerSession` now reports whether the
session can serve credentialed playback — true for a portal needing no token
and for one holding a usable token, false for a full portal left without one —
and both static call sites act on it:

- foreign-host URL: served regardless, it never needed the session;
- portal-owned URL with a usable session: served, as before;
- portal-owned URL with no usable session: falls back to `create_link`, which
  mints a URL carrying its own token AND re-enters the only path that can
  observe a failure and repair.

That covers the unrepaired-endpoint half exactly. The misclassified-as-simple
half stays open by construction — no request means no evidence, and "simple
portal" is indistinguishable from "misclassified" without one. It belongs with
the other reactive-repair work already handed to PR 6: refresh and repair on an
OBSERVED playback authorization failure.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(stalker): require flag evidence before trusting a row as unflagged

Two Codex findings on #1364.

P1 — legacy persisted snapshots. Favorites and Recently Viewed rows saved
before this change went through `buildStalkerSelectedVodItem`'s whitelist,
which dropped both flags, and `buildStalkerFavoritePayload` spreads that
whitelisted object. So a legacy row is flagless because WE stripped it, not
because the portal said no — and the helper was reading it as "explicitly
unflagged". With an absolute HTTP `cmd` from a load-balanced portal that meant
playing a non-final URL. There is no migration or provenance marker for those
rows.

A stock portal returns both flags on every row, so their PRESENCE is itself
the provenance signal, and it is the only one available without a refetch.
`resolveStalkerStaticPlaybackUrl` now requires at least one flag key to be
present; absence reads as "no evidence" and routes back to `create_link`,
which is the pre-PR behaviour. This costs the optimization on panels that omit
the flags entirely — the honest price for not being able to tell them apart
from our own stripped rows.

Radio is the one documented exception. It has always played a directly usable
command without `create_link`, so a flagless radio row keeps that rather than
newly minting — a portal whose radio `create_link` never worked would
otherwise lose playback it has today. ITV and VOD have no such history and
stay conservative.

P2 — loopback range. IPv4 reserves all of `127.0.0.0/8`, so `127.0.0.2` was
being handed to the player as a real address. Classified by range now, with a
test that `127.0.0.1.cdn.example` is still treated as the ordinary hostname it
is.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(stalker): classify every portal-local IPv6 placeholder

Codex P2 on #1364, same class as the 127.0.0.0/8 one. `http://[::]/ch/1234_`
and the IPv4-mapped loopback forms slipped past the exact-name set and would
have been handed to the player as real addresses.

Checked how `URL` actually normalizes these rather than guessing at the
spelling a portal might use: brackets are kept, `[0:0:0:0:0:0:0:1]` collapses
to `[::1]`, and an IPv4-mapped address is rewritten to hex — `[::ffff:127.0.0.1]`
arrives as `[::ffff:7f00:1]`. The guard now strips the brackets, matches `::1`
and `::`, and decodes the mapped form by its high byte, so the whole of the
mapped 127.0.0.0/8 range is covered along with the mapped unspecified address.
The dotted tail is still accepted for any engine that leaves it alone.

Routable hosts are unaffected, pinned by tests for `[2001:db8::1]` and
`[::ffff:203.0.113.7]`. Mutation-checked: dropping `::` and the mapped-IPv4
decode fails five tests and nothing else.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(stalker): normalize hostname and scheme spelling before the static verdict

Two Codex P2s on #1364, both about trusting how a portal spells things.

`http://localhost./ch/1234_` — a trailing dot is the DNS root and resolves
identically, but `URL` keeps it for names while dropping it for IP literals
(`127.0.0.1.` arrives bare, `localhost.` does not). The exact-name check read
that as a remote host and would have pointed the player at its own loopback.
Stripped before classifying.

`HTTP://cdn.example/a.ts` — RFC 3986 makes the scheme case-insensitive. The
case-sensitive tests failed SAFE, minting a link instead, but that defeats the
contract for a portal that spells it this way, and one whose `create_link`
cannot resolve an already-playable row would break.

There were five such tests, and only one was on the new static path: the other
three live in `resolveStalkerPlaybackUrl`, the create_link RESPONSE resolver,
where `ffrt3 HTTP://…` failed to split its solution prefix and a query-only
reply was appended to the portal base instead of to the command. That is
pre-existing, but it is the same bug in the same shared normalizer, and fixing
only the half this PR introduced would leave exactly the divergence this PR
keeps removing. All five now go through one `hasHttpScheme()`.

The response resolver had only indirect coverage, so it gains a direct spec
alongside the static-path tests. Mutation-checked: reverting the dot strip and
the case-insensitive scheme fails ten tests and nothing else.

Also carries a docblock fix noticed on a read-through: the guard list still
pointed at `PORTAL_LOCAL_HOSTNAMES` after the logic moved into
`isPortalLocalHostname`, which now covers considerably more than that set.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(stalker): normalize DNS root dots in the shared credential classifier

Codex P2 on #1364, extending the `localhost.` fix into
`isStalkerStreamCredentialSafe()`. It compared hostnames literally, so a
portal on `portal.example` serving `https://portal.example./movie.mkv`
classified its own stream as third-party.

Wider than the download guard it was reported against: this predicate is the
single rule BOTH the renderer playback-header builder and the Electron
main-process fallback use to decide whether a stream may carry the mac cookie
and Bearer token. A portal-owned stream spelled with the root dot was getting
the credential-free profile and would 401 — pre-existing, and exactly the
"only VLC works" class this contract exists to prevent. My PR added two new
dependencies on the same predicate (the download static guard and the
portal-owned fallback), which is how it surfaced.

Both sides are normalized, so it stays symmetric, and it can only widen toward
"same host" — never toward handing credentials to a different one. A test pins
that `evil.portal.example.` is still rejected.

Also carries the authority guard found by probing the same class myself rather
than waiting for it to be reported: `http:///ch/1` has no authority and `URL`
quietly reinterprets the first path segment as the host, so a malformed
command reached the player as a nonsense address instead of going to the
portal. `isPlayableHttpUrl()` now requires a non-empty authority. The other
exotic spellings I probed were already covered — `URL` canonicalizes `127.1`,
`2130706433` and `0x7f000001` to `127.0.0.1`, uppercases and expanded IPv6
normalize too.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* perf(stalker): classify the static url before authenticating

Codex P2 on #1364. Both static call sites awaited the session warm-up and only
then asked whether the stream needed portal credentials at all — so a movie or
channel on a foreign CDN paid for a handshake whose result was immediately
discarded.

That is not free: non-`create_link` requests carry a 15 s timeout
(`stalker.events.ts`), so a portal that is slow or offline stalled playback of
a stream the CDN would have served instantly. Cold Favorites/Recently Viewed
starts are exactly where this bites, since that is where the session is not
warm already.

Classification now runs first. Foreign host returns immediately, portal-owned
still warms and still falls back to `create_link` without a usable session.
Behaviour is otherwise unchanged; only the order and the wasted wait are gone.

Two tests moved with it: the foreign-host case now asserts the portal is not
contacted at all rather than merely not asked for a link, and the
repaired-endpoint case had been written against a foreign-host command, which
under the new ordering correctly never reaches the handshake it was meant to
be testing — it uses a portal-owned command now.

Mutation-checked: restoring warm-before-classify fails the foreign-host test
alone.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(stalker): repoint two handshake tests at the path they claim to cover

Self-audit, prompted by the previous round: the reorder exposed one test that
was asserting through a path it no longer reached, so I checked the rest of
that class rather than assume it was the only one. Two more had the same
defect, both mine.

`still returns the static url when the handshake fails` (both specs) mocked
`ensureToken` to reject, but used a FOREIGN-host command. Now that
classification runs before authentication, that command returns before the
handshake is ever attempted — the rejection was never exercised and the test
passed on the early return instead of the mechanism in its name. Worse, the
foreign case is already covered by the test added alongside the reorder, so
these were asserting nothing new.

Both now use a portal-owned command, which is what actually reaches the
handshake, and assert what a throw really produces: `ensureStalkerSession`
swallows it, the verdict is false, and the row falls back to `create_link`
rather than being served as a known 401. Each asserts `ensureToken` was in
fact called, so neither can silently drift back into testing an early return.

Docs corrected with them: the "best-effort degrades to the token-less header
set" wording described behaviour the reorder removed. A foreign-host URL is
now returned before any handshake, and a failed one routes to `create_link`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(stalker): make the simple-portal skip test prove portal mode

Fourth test found passing through the wrong exit, from auditing all ten in the
block rather than waiting to trip over another one.

`skips the handshake for a simple portal` used a foreign-host command, so the
classification step returned before the warm-up was reached. `ensureToken` was
indeed not called — but because the host was foreign, not because the portal
was simple, and the assertion could not tell those apart. The command is now
portal-owned, so the skip can only come from the mode, and the test also pins
the returned URL and that no request was made.

Mutation-checked properly this time: removing the simple-portal early return
from `ensureStalkerSession` now fails this test. Under the old command it
would not have.

Also records the pattern where the next person will meet it. The decision
chain has several exits — no flag evidence, unresolvable command, `series`
set, foreign host, unusable session — and more than one can satisfy the same
assertion, so a foreign-host command silently stands in for "simple portal" or
"handshake failed". Mutation testing does not catch that class: it proves a
test is coupled to its target, not that it reached the mechanism it names.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(stalker): key the radio fallback on flag evidence, not snapshot presence

Codex P2 on #1364, and a divergence I introduced myself.

`withStalkerPlayer`'s radio branch checks `hasStalkerLinkFlagEvidence(item)`
before synthesizing the zero flags. `StreamResolverService` used `??`, which
only falls back when the snapshot is absent entirely. A radio Favorite or
Recent row persisted before the flags were carried HAS a snapshot — the old
whitelist just stripped the flags out of it — so the `??` selected that
flagless object, the helper found no evidence, and the collection route began
minting for exactly the rows that used to play directly. That breaks portals
whose radio `create_link` is unsupported, which is the case the radio
exception exists for.

The two paths now apply the identical rule. The divergence came from fixing
them in different rounds and is precisely the class this PR keeps closing, so
the comment on each side now points at the other.

The existing radio test carries no `stalkerItem` at all, so it exercises the
missing-snapshot arm and stayed green throughout — the same "passes through a
different exit" pattern documented in the section above. The new test supplies
a present-but-flagless snapshot. Mutation-checked: restoring the presence
check fails it alone.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(stalker): treat every reserved localhost name as portal-local

Codex P2 on #1364, the fourth in this class. RFC 6761 §6.3 reserves
`localhost` AND every name ending in `.localhost` for the loopback interface,
and resolvers honour it — so `http://stream.localhost/ch/1234_` reached the
player's own machine instead of being sent to the portal to resolve.

Closed the class rather than adding one more name: the suffix is matched, and
`localhost.localdomain` goes in with it as the conventional `/etc/hosts` alias
for 127.0.0.1 on most Linux systems. Together with the earlier rounds the
predicate now covers `localhost` and `*.localhost`, `localhost.localdomain`,
`127.0.0.0/8`, `0.0.0.0`, `::1`, `::`, the IPv4-mapped forms `URL` rewrites to
hex, and a terminal DNS root dot on any of them.

Only the suffix is reserved, so the guard must not over-match: tests pin that
`localhost.cdn.example` and `notlocalhost` remain ordinary routable names and
keep playing statically. Mutation-checked: dropping the suffix rule and the
localdomain alias fails four tests and nothing else.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
4grayandClaude Opus 5 authored and GitHub committed 2026-08-03 18:36:56 +02:00
1 parent d44948f2fa
commit e197409b10
31 files changed
+2459 -175

No files matched your search

+13
View File
@@ -297,6 +297,9 @@ interface ScenarioConfig {
supportsGetAllChannels?: boolean; // default true; false mimics legacy portals
// without the ITV get_all_channels action
marketingFixture?: true; // replace generated VOD with shared posters
requiresLogin?: true; // get_profile answers status 2 until do_auth
gatedStream?: true; // create_link returns a credential-gated URL
staticChannelCmd?: true; // ITV rows need no temporary link
}
```
@@ -317,6 +320,16 @@ forwarded host/protocol) as
`<portal-origin>/assets/marketing/poster/<slug>.png`. `main.ts` serves the
committed PNG directory directly, so the Xtream server does not need to run.
Every generated ITV channel and radio station carries `use_http_tmp_link` and
`use_load_balancing`, the flags a real portal uses to tell a client whether the
row needs `create_link`. They are `'1'`/`'0'` for the default generators —
honest, because those rows carry `ffrt4://…` pseudo-URLs. The
`static-channel-cmd` scenario (`00:1A:79:00:00:0A`) sets `staticChannelCmd`,
which gives ITV rows both flags at `'0'` and a real
`ffrt3 https://…m3u8` command, so `apps/web-e2e/src/stalker.e2e.ts` can assert
that no `create_link` request reaches the portal. See
`docs/architecture/stalker-portal.md`, "Playback Link Resolution".
### Adding a New Scenario
1. Add an entry to the `SCENARIOS` map in `src/app/scenarios.ts`.
+224 -1
View File
@@ -305,6 +305,226 @@ the cross-portal collection resolver (`StreamResolverService`) use
resolve relative (`/media/...`) or query-only (`?token=...`) `create_link`
replies against the portal base URL.
## Playback Link Resolution
### When `create_link` is called
A Stalker catalog row decides for itself whether it needs a temporary link.
The portal's own `player.js` — mirrored by Kodi's `pvr.stalker` — calls
`create_link` only when the row sets `use_http_tmp_link` (the portal proxies
the stream through a per-session URL) or `use_load_balancing` (the portal
picks a storage server per request). Every other row plays the static `cmd`
that `get_all_channels` / `get_ordered_list` already returned. Until PR 8 the
app called `create_link` unconditionally, so every playback paid a round trip
and gained a failure point that the reference client does not have.
One helper owns the decision:
`resolveStalkerStaticPlaybackUrl(row, cmd)` in
`libs/portal/stalker/data-access/src/lib/stores/utils/stalker-link-semantics.utils.ts`.
It returns the playable URL when the static path applies and `null` when the
portal has to resolve the command. `null` is deliberately wider than the flag
check alone; the extra guards can only push a row back onto the `create_link`
path, so they cannot regress a portal that works today:
| Input | Verdict | Why |
| --- | --- | --- |
| Either flag truthy (`1`, `'1'`, `true`) | `create_link` | The portal asked for a temporary link. |
| No row supplied at all | `create_link` | A caller that cannot show the flags gets no verdict. |
| A row carrying neither flag KEY | `create_link` | Absence means "no evidence", not "no". A stock portal returns both flags on every row, so their PRESENCE is the provenance signal — and the only one available, because rows persisted into Favorites/Recently Viewed before this change were stripped of them by `buildStalkerSelectedVodItem`'s whitelist, making a legacy snapshot indistinguishable from a genuinely unflagged row. There is no migration for those. **Radio is the documented exception**: a directly playable radio command has always played as-is, so a flagless radio row keeps that rather than newly minting. |
| Relative `/media/file_12.mpg` or query-only `?token=…` | `create_link` | Only the portal turns those into an address; the VOD `has_files` rewrite produces exactly the first shape. |
| Non-HTTP scheme (`ffrt4://ch/live/…`) | `create_link` | Portal-internal pseudo-URL. |
| Portal-local host — `localhost` and any `*.localhost` name (RFC 6761 §6.3 reserves the whole suffix for loopback), `localhost.localdomain`, all of `127.0.0.0/8`, `0.0.0.0`, `::1`, `::`, and the IPv4-mapped forms `URL` normalizes to hex (`::ffff:7f00:1`); a terminal DNS root dot is stripped first | `create_link` | `ffrt3 http://localhost/ch/1234_` is an instruction to the portal, not an address a set-top box could open. |
| Otherwise | static `cmd` | Solution prefix stripped by `normalizeStalkerPlaybackCommand()`. |
`fetchStalkerPlaybackLink()` applies the verdict for ITV, VOD and radio, and
short-circuits before the request. It never applies it when `series` is set:
an episode is selected server-side by that parameter, so the parent row's
static `cmd` addresses the series, not the episode.
**The flags must survive normalization.** `buildStalkerSelectedVodItem()`
(`stalker-vod.utils.ts`) narrows a raw portal row to a whitelist, so a field it
does not name is silently dropped — and it feeds both VOD playback
(`selectedItem()`) and the download payload (`createStalkerVodItem` passes its
`data` straight through). Losing a flag there fails **open**: the row reads as
"no temporary link needed" and the static path plays the portal's non-final
URL. Both flags are therefore on the whitelist, on `StalkerVodSource` /
`StalkerSelectedVodItem`, and pinned by tests in `stalker-vod.utils.spec.ts`.
Any new normalizer between a portal response and a playback call has the same
obligation.
Callers pass the row they resolved the `cmd` from:
- ITV and radio — the channel/station row (`withStalkerPlayer`); radio
previously bypassed `create_link` for any directly playable command, which
meant a proxied station played a URL the portal never intended to serve.
- VOD and series — `selectedItem()`.
- Downloads — the movie payload, through the optional `linkFlags` argument on
`fetchLinkToPlay()`, but only for a credential-free URL (see below).
- Favorites and Recently Viewed — `StreamResolverService.resolveStalker()`
reads the flags off the persisted raw row (`UnifiedCollectionItem.stalkerItem`).
Radio keeps its long-standing "directly usable command plays as-is"
behaviour, keyed off flag EVIDENCE rather than snapshot presence — a radio
row persisted before the flags were carried has a snapshot that simply lacks
them, and testing presence would skip the fallback for exactly those rows.
`withStalkerPlayer`'s radio branch applies the identical rule; the two must
not drift.
### The static path still needs the session
`create_link` was also the request that warmed the portal session, and tokens
live in memory only (`StalkerSessionService.tokenCache`). Skipping it therefore
has to account for streams that are still gated on the Bearer token — and
"which routes are already warm" is not a question worth answering per route:
the global collection detail sets the playlist and the selected item straight
from a persisted row, with no catalog load in between, so a VOD opened from
Favorites reaches the store's playback path stone cold.
Every static return therefore warms first, through one primitive —
`ensureStalkerSession()` in `stalker-request.utils.ts`, wrapping
`StalkerSessionService.ensureToken()`:
- `fetchStalkerPlaybackLink()` calls it before returning a static URL, which
covers ITV, VOD, radio and downloads at a single choke point.
- `StreamResolverService` calls it on its own static branch, which does not go
through that function.
`ensureToken` performs handshake + `get_profile` with no link minted, and
validates the identity the cached token was negotiated for — which the raw
`getCachedToken()` the header builders use cannot. It is cheap where it is not
needed: a simple portal returns immediately and a warm cache with a matching
fingerprint resolves without a request.
The classification happens BEFORE the handshake, not after: a **foreign-host**
static URL never needs the session at all, and warming it anyway would stall
playback behind a request worth up to 15 s against a portal that may be slow
or offline while the CDN is perfectly reachable — for a result that is then
discarded.
A **foreign-host** static URL is returned before the handshake is even
attempted — it never needed the session. A **portal-owned** one with no usable
session (handshake failed, or threw) would be served knowing it will 401, so
both call sites fall back to `create_link` instead — which mints a URL
carrying its own token and, crucially, is the only path that can observe a
failure and trigger the lazy portal repair. That keeps a playlist still
misclassified as token-free, or pointing at an unrepaired endpoint, on the
self-healing path it was on before this change.
`ensureStalkerSession` returns that verdict: `true` for a portal that needs no
token and for one holding a usable token, `false` for a full portal left
without one. It swallows a throwing handshake rather than propagating it — an
unreachable portal must not surface as an exception mid-playback — which
simply makes the verdict `false` and routes the row to `create_link`.
**Known trade-off: a cached token is not revalidated.** `ensureToken` returns a
same-identity cache entry without touching the network, so the static path no
longer self-heals a token the server has retired — something `create_link`
used to do for free, since `makeAuthenticatedRequest` retires and re-auths on
an authorization failure. This is narrower than it sounds: per the 4.9.35
reference, handshake tokens have **no TTL**, and failing to send the watchdog
does **not** invalidate auth (it only clears the admin panel's "online"
status). The one real vector left is another device performing `get_profile`
on the same MAC — common enough on shared subscriptions, but wherever a
watchdog is running it still self-heals within a ping cycle, because the ping
goes through `makeAuthenticatedRequest` too. What is left uncovered is a
same-host static stream played while no watchdog is up.
Revalidating on every static playback would cost exactly the round trip this
section exists to remove, so it is deliberately not done here. The right home
for a fix is the auth lifecycle (PR 6): refresh on an observed playback
authorization failure, rather than pre-emptively on every play.
**Downloads are the exception, and cannot use this.** A download request cannot
carry portal credentials at all — the main-process stored-header allowlist is
`User-Agent` / `Origin` / `Referer` only
(`download-request-headers.ts`), with no `Cookie` or `Authorization`. So
`startStalkerVodDownload` offers the static shortcut only for a URL that needs
none: it classifies the candidate with `isStalkerStreamCredentialSafe()` and
withholds the row (forcing `create_link`) for anything portal-owned. A
same-host movie keeps using the minted URL, which carries its own access token;
a CDN-hosted one keeps the permanent URL that survives retry.
### Resolved links are never stored
A temporary link lives about 5 seconds (`tv_tmp_link_ttl` /
`vclub_tmp_link_ttl`, both default 5). It is time-limited but not single-use,
so the rule is to resolve immediately before playback and never persist,
cache or replay the result. What each persisting path actually stores:
| Path | Stores | Verdict |
| --- | --- | --- |
| Recently Viewed | the raw row including `cmd` (`buildStalkerRecentlyViewedPayload` spreads the item) | Re-resolves on replay. |
| Favorites | the raw row including `cmd` (`addStalkerFavorite`, `toggleFavorite`) | Re-resolves on replay. |
| Playback positions | `playlist_id` + `content_xtream_id` + content type only — no URL column | Not applicable. |
| Main-process playback context (`stalker-playback-context.service.ts`) | header sets keyed by the stream URL's origin + path, 15 min TTL | Stores no URL. The key drops the query, so a re-minted link with a fresh token still finds its headers instead of playing bare. |
| ITV full-list cache (`StalkerItvCacheService`) | catalog rows | Rows, not links. |
| Downloads | the resolved `url` on the `downloads` row | **The one exception** — see below. |
The download row is the only place a resolved URL outlives the playback that
produced it, because the main-process downloader needs a URL it can retry and
resume with. Honouring the flags shrinks the exposure: an unflagged movie on a
host that needs no portal credentials now yields a permanent URL that survives
retry. A movie that needs a temporary link — or one on the portal host, which a
download cannot authenticate against — still stores a link that is dead by the
time retry runs. Fixing that needs the `cmd` on the download row plus a
re-resolution step before retry/resume, which is a schema change and is
deliberately out of scope here.
### `forced_storage` and `play_token`
Both are deliberately unused, and neither appears in the 4.9.35 reference
fact set as a parameter the stock server enforces:
- **`forced_storage`** is a `create_link` request parameter that pins VOD
playback to one storage server. It exists for clients that let the user pick
a storage; IPTVnator has no such concept, and omitting the parameter is what
produces the empty value the portal treats as "no preference". Wiring it
would first need storage discovery and a picker in the VOD detail view.
- **`play_token`** is a `create_link` response field for clients that assemble
the stream URL themselves. IPTVnator plays the `cmd` the portal returns
verbatim (after the solution-prefix strip and base resolution above), so the
token the stream needs is already in the URL. Note the coupling with the
section above: on the static path no `create_link` runs at all, so no
`play_token` is ever produced — which is consistent, because a row that
wants neither flag is announcing that its `cmd` needs no portal-minted
credential.
Revisit both only with a portal that demonstrably fails without them.
### Regression coverage
**Writing tests against this section:** the decision chain has several exits —
no flag evidence, unresolvable command shape, `series` set, foreign host,
session unusable — and more than one of them can satisfy the same assertion.
Four tests in the PR that introduced this were found passing through an exit
other than the one they named (a foreign-host command reaches neither the
handshake nor `create_link`, so it silently stands in for "simple portal" or
"handshake failed"). Mutation testing does not catch it: it proves a test is
coupled to its target, not that it reached the mechanism in its name. Check the
mock setup against the execution path, and assert the step you mean was
actually taken — `expect(ensureToken).toHaveBeenCalled()` rather than only the
returned URL.
- `stalker-link-semantics.utils.spec.ts` — the decision table above.
- `stalker-vod.utils.spec.ts` — both flags survive
`buildStalkerSelectedVodItem` / `normalizeStalkerVodDetailsItem` /
`normalizeStalkerFavoriteItem`, and an unflagged row gains no flags.
- `stalker-player-request.utils.spec.ts` — static short-circuit, both flags,
the `series` exception, relative VOD commands, the session warm-up (simple
portal skipped, repaired endpoint used, failure degraded) and the
portal-owned-without-session fallback to `create_link`.
- `with-stalker-player.feature.spec.ts` — ITV/radio store paths and proof that
Recently Viewed stores the `cmd`, never the stream URL.
- `stream-resolver.service.spec.ts` — the collection route, plus the cold
full-portal session warm-up and its best-effort degradation.
- `stalker-vod-download.spec.ts` — a CDN movie takes the static shortcut, a
same-host one keeps minting.
- `stalker-playback-context.service.spec.ts` — headers only, query-insensitive
key.
- `apps/web-e2e/src/stalker.e2e.ts` — mock scenario `00:1A:79:00:00:0A` serves
unflagged ITV rows with a playable `cmd`; the spec asserts NO `create_link`
request reaches the portal, and a companion test on the default (flagged)
scenario proves the recorder does see one when a link is due.
## Playback Header Contract
Every playback kind — ITV, VOD, series episodes, and radio — resolves its
@@ -326,7 +546,10 @@ live layout for the radio audio player, which renders outside
Two stream profiles exist, selected by one shared predicate:
- **Portal-owned** (`isStalkerStreamCredentialSafe()` in
`@iptvnator/shared/interfaces`): the stream host equals the portal host —
`@iptvnator/shared/interfaces`): the stream host equals the portal host
(compared with a terminal DNS root dot normalized away, since
`portal.example.` and `portal.example` are the same host but `URL` keeps
the dot) —
including a different port or an http→https upgrade, the routine IPTV panel
shape (#1158 class). These streams get the full MAG profile: `Cookie`
(`mac=…` plus protocol cookies), `Authorization: Bearer <token>` when a