From 41559b8890b9a149ec0501e1e06fb8132182d42f Mon Sep 17 00:00:00 2001 From: 4gray Date: Sun, 9 Aug 2026 16:13:37 +0200 Subject: [PATCH] fix(stalker): retire restored repair overrides --- CLAUDE.md | 2 +- docs/architecture/stalker-portal.md | 7 +++-- .../lib/stalker-portal-repair.service.spec.ts | 30 +++++++++++++++++++ .../src/lib/stalker-portal-repair.service.ts | 19 ++++++++---- 4 files changed, 50 insertions(+), 8 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 802daba39..1d54cfac9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1264,7 +1264,7 @@ engine` (restart required) or - Portal mode (full vs. simple) follows OBSERVED behavior, never a URL substring. The single predicate is `isFullStalkerPortalPlaylist()` / `isFullStalkerPortalUrl()` in `@iptvnator/shared/interfaces` (`stalker-portal-mode.util.ts`): the persisted `Playlist.isFullStalkerPortal` flag is authoritative and the URL shape is a fallback for legacy rows only. Three diverging copies of this rule used to exist and shipped broken configurations (#850/#686/#755) — never re-implement it. A token-enforcing `portal.php` panel is a full portal; a `server/load.php` endpoint that answers without a token is a simple one. - Import requires an explicit HTTP(S) scheme but accepts a bare host, `/c`, or a concrete `.php` address. It probes candidates in order (a pasted `.php` endpoint first, then `/portal.php` → `/server/load.php` → `/stalker_portal/server/load.php`) and classifies each by behavior — a token-less `itv/get_genres` returning data proves a token-free panel; the plain-text auth failure proves a full portal, confirmed by a real handshake + `get_profile`. `StalkerPortalDiscoveryService` (`libs/portal/stalker/data-access`) persists and displays the proven endpoint and mode. An unreachable panel-style import remains allowed with a warning; a bare host falls back to `/portal.php`, while canonical-shaped unreachable addresses still abort. If bounded discovery returns while abandoned authentication remains on the wire, the refusal is shown immediately but Add and every form field stay disabled until its settlement promise resolves. - The playlist-info Edit dialog loads the complete persisted Stalker row before enabling the form, because Electron's startup metadata projection omits payload-only serial/device/signature/mode fields; a summarized row must never render and then persist an empty portal identity. It preserves an unchanged connection byte-for-byte and skips discovery. Changing URL, MAC, credentials, serial, device IDs or signatures blocks duplicate saves, disables dialog closure for the validation window, and runs the existing discovery service through the app-provided `STALKER_PLAYLIST_CONNECTION_EDITOR` token, keeping Stalker data-access out of `playlist-shared-ui`. Before discovery it reserves the playlist ID; a second Edit cannot replace that owner. The reservation blocks every new authentication (including fingerprint-equivalent URL edits) and repair, drains existing work, and rechecks ownership after every asynchronous drain/rebase; ordinary failure releases it without changing the saved or runtime connection. If discovery returns after its bounded drain while an abandoned authentication is still on the wire, that result carries its settlement promise and both reservations remain installed until it resolves, so catalog, watchdog, repair, or retry authentication cannot race a late `get_profile`. If navigation or another owner closes/destroys the dialog while discovery is in flight, the UI discards a later successful result through `discardResolvedConnection()` and releases both reservations without persisting it. Success uses one awaited write to atomically replace endpoint, mode, normalized identity and session metadata, then feeds its complete merged row into the state-only NgRx update and active `StalkerStore`/session/watchdog replacement before another same-route request can use the old connection. This preserves playback headers and other metadata absent from the form. Runtime configuration authority covers the observed full/simple mode as well as the session fingerprint, and both authenticated and direct simple requests cross its guard before dispatch and after transport, so a same-endpoint mode change rejects stale snapshots and completed responses in either direction. A changed authority may rebase only when the persisted row proves that it owns the same playlist ID, keeping delete/restore and backup merge usable. The transient `PlaylistMetaUpdate.stalkerSessionPatch` preserves on absence, clears on `null`, and fully replaces from an object before storage; it is projected onto existing flat playlist fields and never changes the DB or backup shape. -- `executeStalkerRequest()` (`stores/utils/stalker-request.utils.ts`) is the choke point for catalog, content and playback requests: mode routing, the in-session repair override, and retry-once all live there. Four callers are deliberately outside it because they run below or before the thing it routes on — `StalkerAuthApi` (handshake/`get_profile`/`do_auth`, which the full-portal branch is built from; routing them back would recurse), `StalkerPortalDiscoveryService` (probes precede the mode they determine), `StalkerAccountInfoService.fetchViaProfile()`, and `StreamResolverService` for a collection item with no playlist row. They are exempt from the routing, not from the repair it hooks, but only `fetchViaProfile()` wires `StalkerPortalRepairService` itself: discovery is what repair _drives_, the row-less resolver branch has no playlist to repair, and the auth layer needs nothing — a terminal handshake failure propagates out of the full-portal branch into whichever `executeStalkerRequest()` call triggered the authentication, which is why terminal handshake failures are a repair trigger. Anything new that is not auth or discovery belongs on `executeStalkerRequest()`. Existing playlists are repaired LAZILY (`StalkerPortalRepairService`) — only after a request fails with a shape a wrong endpoint/mode produces, at most once per source configuration per playlist per session, persisted through the atomic `PlaylistsService.transformPlaylistMeta`. Before an unrecorded repair calls discovery, it verifies that the persisted row still owns the failing source, so a late pre-Edit request cannot authenticate against the old portal after Edit commits and invalidate the newly saved token. Each repair installs a session-level authentication fence synchronously, drains the existing token slot before probing, and keeps request routing ahead of effective-connection selection until repair finishes; an abandoned transport keeps both the repair and session fences until it actually settles. There is deliberately **no eager one-shot migration**: a portal that works is never re-probed. +- `executeStalkerRequest()` (`stores/utils/stalker-request.utils.ts`) is the choke point for catalog, content and playback requests: mode routing, the in-session repair override, and retry-once all live there. Four callers are deliberately outside it because they run below or before the thing it routes on — `StalkerAuthApi` (handshake/`get_profile`/`do_auth`, which the full-portal branch is built from; routing them back would recurse), `StalkerPortalDiscoveryService` (probes precede the mode they determine), `StalkerAccountInfoService.fetchViaProfile()`, and `StreamResolverService` for a collection item with no playlist row. They are exempt from the routing, not from the repair it hooks, but only `fetchViaProfile()` wires `StalkerPortalRepairService` itself: discovery is what repair _drives_, the row-less resolver branch has no playlist to repair, and the auth layer needs nothing — a terminal handshake failure propagates out of the full-portal branch into whichever `executeStalkerRequest()` call triggered the authentication, which is why terminal handshake failures are a repair trigger. Anything new that is not auth or discovery belongs on `executeStalkerRequest()`. Existing playlists are repaired LAZILY (`StalkerPortalRepairService`) — only after a request fails with a shape a wrong endpoint/mode produces, at most once per source configuration per playlist per session, persisted through the atomic `PlaylistsService.transformPlaylistMeta`. Before an unrecorded repair calls discovery, it verifies that the persisted row still owns the failing source, so a late pre-Edit request cannot authenticate against the old portal after Edit commits and invalidate the newly saved token. Its in-session override is bound to source endpoint, mode, device identity, and credentials; an Edit or backup restore with the same playlist ID but different connection metadata retires the override and token. Each repair installs a session-level authentication fence synchronously, drains the existing token slot before probing, and keeps request routing ahead of effective-connection selection until repair finishes; an abandoned transport keeps both the repair and session fences until it actually settles. There is deliberately **no eager one-shot migration**: a portal that works is never re-probed. - Explicit Edit advances the repair generation before installing its resolved session. A lazy repair that started earlier is discarded even if it had already verified its row, so it cannot restore an older endpoint, mode or token after Edit. - Both transports build the wire format from the same shared builders in `@iptvnator/shared/interfaces` — `buildStalkerRequestUrl()`, `buildStalkerIdentityRequestContext()`, `encodeStalkerCmdValue()` — so the Electron and PWA legs cannot drift. The mock's `/stalker` mirror shares the identity builder only — it dispatches in-process, so there is no portal URL to build and it mirrors the `JsHttpRequest` default by hand. Never fork any of them. - Simple portals skip the auth lifecycle (no handshake, token or watchdog) but their requests are not stripped to a bare cookie: they still carry everything the shared builder derives from a MAC alone (`mac`/`stb_lang`/`timezone` cookie, MAG `User-Agent`/`X-User-Agent`, `Accept` set). They do NOT carry the serial — `dispatchStalkerRequest()`'s direct branch forwards only `url`/`macAddress`/`params`, so no `SN` header and no serial-derived `__cfduid`, whatever the playlist stores. That gate is on API requests only: `buildStalkerExternalPlaybackHeaders()` reads the serial off the playlist row with no mode check, so the same simple-mode playlist does send `SN`/`__cfduid` with a portal-owned stream. diff --git a/docs/architecture/stalker-portal.md b/docs/architecture/stalker-portal.md index 96ec802ac..798439835 100644 --- a/docs/architecture/stalker-portal.md +++ b/docs/architecture/stalker-portal.md @@ -256,7 +256,7 @@ plain-text auth bodies AND their JSON envelopes (`js.error`/`js.msg`), HTTP 404 (endpoint absent), HTTP 401/403 (endpoint behind an HTTP auth gate), and terminal handshake/profile errors — never timeouts or other network failures), at most once per SOURCE CONFIGURATION (endpoint + mode + MAC + -identity fingerprint) per playlist per session — an edited configuration +identity fingerprint + credentials) per playlist per session — an edited configuration may probe when it fails, while every already-probed one stays latched for the session. Before an unrecorded probe makes any portal request, it verifies that the persisted row still carries the failing source; a request that failed @@ -270,7 +270,10 @@ transport settles. Repair persists only a configuration discovery has proven to answer, and only when it differs from the failing one. A repaired configuration is applied immediately via an in-session override inside `executeStalkerRequest()` (stale store snapshots -keep working) and persisted through `PlaylistsService.transformPlaylistMeta` +keep working). The override is bound to that source's endpoint, mode, device +identity, and credentials; an Edit or backup restore under the same playlist +ID retires it when any connection field differs. The repair is persisted +through `PlaylistsService.transformPlaylistMeta` — the verification and the patch run in ONE slot of the per-playlist write queue, so a user edit that is queued but not yet committed wins over the repair instead of being overwritten; the transform patches the freshly read diff --git a/libs/portal/stalker/data-access/src/lib/stalker-portal-repair.service.spec.ts b/libs/portal/stalker/data-access/src/lib/stalker-portal-repair.service.spec.ts index 450d50454..d43d4dc27 100644 --- a/libs/portal/stalker/data-access/src/lib/stalker-portal-repair.service.spec.ts +++ b/libs/portal/stalker/data-access/src/lib/stalker-portal-repair.service.spec.ts @@ -791,6 +791,36 @@ describe('StalkerPortalRepairService', () => { expect(discover).toHaveBeenCalledTimes(1); }); + it('drops a repaired override when a restored row has new credentials', async () => { + const original = { + ...MISCLASSIFIED, + username: 'user-1', + password: 'password-1', + } as PlaylistMeta; + persistedRow = original as Playlist; + discover.mockResolvedValue({ + status: 'resolved', + portalUrl: original.portalUrl, + isFullStalkerPortal: true, + }); + await service.repairPortal(original); + clearCachedToken.mockClear(); + + const restored = { + ...original, + username: 'user-2', + password: 'password-2', + } as PlaylistMeta; + persistedRow = restored as Playlist; + + expect(service.applyOverride(restored)).toBe(restored); + expect(clearCachedToken).toHaveBeenCalledWith(original._id); + + discover.mockResolvedValue({ status: 'unreachable' }); + await service.repairPortal(restored); + expect(discover).toHaveBeenCalledTimes(2); + }); + it('re-probes a DISCARDED configuration once the row is restored to it', async () => { // A's probe was discarded by the persisted-row preflight because // the row had moved to B; after the user restores the row to A, diff --git a/libs/portal/stalker/data-access/src/lib/stalker-portal-repair.service.ts b/libs/portal/stalker/data-access/src/lib/stalker-portal-repair.service.ts index 930971a97..16ff6b37f 100644 --- a/libs/portal/stalker/data-access/src/lib/stalker-portal-repair.service.ts +++ b/libs/portal/stalker/data-access/src/lib/stalker-portal-repair.service.ts @@ -39,11 +39,17 @@ interface StalkerPortalModeOverride { sourceIsFullStalkerPortal: boolean; /** MAC + Stalker identity the repair probe authenticated as. */ identityFingerprint: string; + /** Login/password the repair outcome was negotiated with. */ + credentialsFingerprint: string; /** The proven-working configuration. */ portalUrl: string; isFullStalkerPortal: boolean; } +function stalkerCredentialsFingerprint(playlist: PlaylistMeta): string { + return JSON.stringify([playlist.username ?? '', playlist.password ?? '']); +} + /** * Lazy repair for playlists whose persisted portal endpoint or mode is * wrong. The flag used to be a URL-shape guess frozen at import, so a @@ -139,12 +145,14 @@ export class StalkerPortalRepairService implements StalkerPortalRepairApi { if ( stalkerIdentityFingerprint(playlist) !== - override.identityFingerprint + override.identityFingerprint || + stalkerCredentialsFingerprint(playlist) !== + override.credentialsFingerprint ) { - // The MAC or Stalker identity was edited after the repair. The - // override AND the token the repair authenticated for the - // PREVIOUS identity must go — otherwise requests and watchdog - // pings would pair the edited identity with a foreign session. + // The MAC, Stalker identity, or login was replaced after repair. + // The override AND its cached token belong to the previous + // account and must not be applied to a restored row sharing only + // the playlist ID, endpoint, and device identity. this.dropOverride(playlist._id); return playlist; } @@ -508,6 +516,7 @@ export class StalkerPortalRepairService implements StalkerPortalRepairApi { sourcePortalUrl: playlist.portalUrl, sourceIsFullStalkerPortal: storedMode, identityFingerprint: stalkerIdentityFingerprint(playlist), + credentialsFingerprint: stalkerCredentialsFingerprint(playlist), portalUrl: outcome.portalUrl, isFullStalkerPortal: outcome.isFullStalkerPortal, };