fix(stalker): reject superseded portal responses

This commit is contained in:
4gray committed 2026-08-09 14:58:07 +02:00
1 parent a4e74f425f
commit 5532825b30
9 files changed
+110 -21

No files matched your search

+1 -1
View File
@@ -7,4 +7,4 @@ Stalker setup now accepts a host or `/c` address, discovers the working API
endpoint and authentication mode, and rechecks connection details edited
later. Canceled or failed edits leave the saved playlist and active session
unchanged. Completed edits reject requests still holding the previous portal
mode.
configuration and discard their late responses.
+1 -1
View File
@@ -1262,7 +1262,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 `<base>/portal.php` → `<base>/server/load.php` → `<base>/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 `<base>/portal.php`, while canonical-shaped unreachable addresses still abort.
- 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; failure releases it without changing the saved or runtime connection. 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, so a same-endpoint mode change rejects stale snapshots 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.
- 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; failure releases it without changing the saved or runtime connection. 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. 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.
+7 -6
View File
@@ -224,12 +224,13 @@ edit and metadata absent from the form (such as playback `Referer`/`Origin`)
survives the replacement.
Runtime configuration authority combines the session fingerprint with the
observed full/simple mode. Both authenticated calls and direct simple-mode
requests cross that guard, so a same-endpoint mode-only Edit rejects stale
playlist objects in either direction before they can authenticate or issue a
token-free portal request. A different authority may rebase only after the
current persisted row proves that it owns the same playlist ID; this keeps
delete/restore and backup merge flows usable without letting an in-flight
stale request overrule Edit.
requests cross that guard before dispatch and again after transport, so a
same-endpoint mode-only Edit rejects stale playlist objects in either direction
before they can authenticate or issue a token-free portal request, and discards
an older portal response that completes after Edit commits. A different
authority may rebase only after the current persisted row proves that it owns
the same playlist ID; this keeps delete/restore and backup merge flows usable
without letting an in-flight stale request overrule Edit.
`PlaylistMetaUpdate` carries the persisted part as a transient
`stalkerSessionPatch` (`undefined` preserves, `null` clears, an object fully
replaces); `PlaylistsService` projects it onto the existing flat playlist
@@ -7,6 +7,7 @@ import {
import type { DataService } from '@iptvnator/services';
import { StalkerPortalError } from './stalker-portal-error';
import { isStalkerAuthorizationFailure } from './stalker-response-classification';
import { stalkerSessionFingerprint } from './stalker-session-store';
import type { StalkerTokenCache } from './stalker-token-cache';
/** Authenticated request + one-shot session renewal shared by all callers. */
@@ -16,7 +17,11 @@ export class StalkerAuthenticatedRequestClient {
private readonly tokens: StalkerTokenCache,
private readonly ensureToken: (
playlist: Playlist
) => Promise<{ token: string | null; serialNumber?: string }>
) => Promise<{ token: string | null; serialNumber?: string }>,
private readonly assertCurrent: (
playlist: Playlist,
sessionFingerprint: string
) => void
) {}
async request<T>(
@@ -24,22 +29,30 @@ export class StalkerAuthenticatedRequestClient {
params: Record<string, string | number>,
retryOnAuthFailure = true
): Promise<T> {
const { token, serialNumber } = await this.ensureToken(playlist);
// Bind the whole request to one immutable connection snapshot. An
// Edit can replace the authoritative endpoint/mode while transport is
// in flight; its old response must never reach a store or player.
const configuration = { ...playlist } as Playlist;
const sessionFingerprint =
stalkerSessionFingerprint(configuration);
const { token, serialNumber } =
await this.ensureToken(configuration);
try {
const response = await this.dataService.sendIpcEvent<T>(
STALKER_REQUEST,
{
url: playlist.portalUrl,
macAddress: playlist.macAddress,
url: configuration.portalUrl,
macAddress: configuration.macAddress,
params,
token,
...(serialNumber ? { serialNumber } : {}),
}
);
this.assertCurrent(configuration, sessionFingerprint);
if (isStalkerAuthorizationFailure(response)) {
return this.handleAuthorizationFailure<T>(
playlist,
configuration,
params,
token,
response,
@@ -55,12 +68,12 @@ export class StalkerAuthenticatedRequestClient {
throw error;
}
if (isStalkerAuthorizationFailure(error)) {
this.tokens.retireFailed(playlist._id, token);
this.tokens.retireFailed(configuration._id, token);
if (
retryOnAuthFailure &&
isFullStalkerPortalPlaylist(playlist)
isFullStalkerPortalPlaylist(configuration)
) {
return this.request<T>(playlist, params, false);
return this.request<T>(configuration, params, false);
}
}
// Transport evidence (especially HTTP 401/403) is consumed by
@@ -16,6 +16,7 @@ describe('Stalker edited-session coordination', () => {
} as Playlist;
let authenticate: jest.SpyInstance;
let sendIpcEvent: jest.Mock;
let resolveOldAuthentication: (
value: Awaited<ReturnType<StalkerSessionService['authenticate']>>
) => void = () => undefined;
@@ -28,12 +29,13 @@ describe('Stalker edited-session coordination', () => {
getPlaylistById = jest.fn(() => of(oldPlaylist));
updatePlaylistMeta = jest.fn(() => of(oldPlaylist));
updateStalkerSession = jest.fn(() => of(oldPlaylist));
sendIpcEvent = jest.fn();
TestBed.configureTestingModule({
providers: [
StalkerSessionService,
{
provide: DataService,
useValue: { sendIpcEvent: jest.fn() },
useValue: { sendIpcEvent },
},
{
provide: PlaylistsService,
@@ -218,6 +220,32 @@ describe('Stalker edited-session coordination', () => {
expect(authenticate).not.toHaveBeenCalled();
});
it('rejects an authenticated response completed after Edit commits', async () => {
service.setCachedToken(oldPlaylist._id, 'OLD_TOKEN', oldPlaylist);
let resolveOldResponse!: (value: unknown) => void;
sendIpcEvent.mockReturnValueOnce(
new Promise((resolve) => (resolveOldResponse = resolve))
);
const oldRequest = service.makeAuthenticatedRequest(oldPlaylist, {
type: 'itv',
action: 'get_genres',
});
while (sendIpcEvent.mock.calls.length === 0) {
await Promise.resolve();
}
const editedPlaylist = {
...oldPlaylist,
portalUrl: 'https://new.example.com/server/load.php',
stalkerToken: 'NEW_TOKEN',
} as Playlist;
updatePlaylistMeta.mockReturnValueOnce(of(editedPlaylist));
await service.replaceSessionAfterEdit(editedPlaylist);
resolveOldResponse({ js: { data: ['STALE_CATEGORY'] } });
await expect(oldRequest).rejects.toThrow(/stale/i);
});
it('persists a resolved full connection and session in one metadata write', async () => {
const editedPlaylist = {
...oldPlaylist,
@@ -189,7 +189,12 @@ describe('StalkerItvCacheService', () => {
});
const load = service.ensureLoaded(PLAYLIST);
await flushMicrotasks();
// The second request starts only after page-one progress is recorded.
// Wait for that observable boundary instead of a fixed microtask
// count: request guards may add network-free async hops.
while (callsFor('get_ordered_list') < 2) {
await Promise.resolve();
}
expect(service.isLoading(PLAYLIST)).toBe(true);
expect(service.progressOf(PLAYLIST)).toEqual({ loaded: 14, total: 28 });
@@ -99,7 +99,9 @@ export class StalkerSessionService {
private readonly requestClient = new StalkerAuthenticatedRequestClient(
this.dataService,
this.tokens,
(playlist) => this.ensureToken(playlist)
(playlist) => this.ensureToken(playlist),
(playlist, sessionFingerprint) =>
this.editedSessions.assertCurrent(playlist, sessionFingerprint)
);
/**
@@ -103,6 +103,41 @@ describe('executeStalkerRequest', () => {
expect(deps.dataService.sendIpcEvent).not.toHaveBeenCalled();
});
it('rejects a direct response completed after its mode becomes stale', async () => {
const deps = createDeps();
const simplePlaylist = {
_id: 'stalker-in-flight-simple',
title: 'In-flight simple snapshot',
portalUrl: 'https://portal.example.test/server/load.php',
macAddress: 'has-mac-address',
isFullStalkerPortal: false,
} as PlaylistMeta;
let resolveResponse!: (value: unknown) => void;
(deps.dataService.sendIpcEvent as jest.Mock).mockReturnValueOnce(
new Promise((resolve) => (resolveResponse = resolve))
);
(deps.stalkerSession.ensureToken as jest.Mock)
.mockResolvedValueOnce({ token: null })
.mockRejectedValueOnce(
new Error('Stale Stalker playlist configuration')
);
const request = executeStalkerRequest(
deps,
simplePlaylist,
CATEGORY_PARAMS
);
while (
(deps.dataService.sendIpcEvent as jest.Mock).mock.calls.length === 0
) {
await Promise.resolve();
}
resolveResponse({ js: ['STALE_CATEGORY'] });
await expect(request).rejects.toThrow(/stale/i);
expect(deps.stalkerSession.ensureToken).toHaveBeenCalledTimes(2);
});
});
describe('executeStalkerRequest portal-mode fallback', () => {
@@ -118,13 +118,18 @@ async function dispatchStalkerRequest<T>(
// authority guard. `ensureToken` is network-free in simple mode, and
// prevents a pre-Edit simple snapshot from issuing a token-free request
// after the same endpoint has been reclassified as full.
await deps.stalkerSession.ensureToken(toStalkerSessionPlaylist(playlist));
const sessionPlaylist = toStalkerSessionPlaylist(playlist);
await deps.stalkerSession.ensureToken(sessionPlaylist);
return deps.dataService.sendIpcEvent<T>(STALKER_REQUEST, {
const response = await deps.dataService.sendIpcEvent<T>(STALKER_REQUEST, {
url: playlist.portalUrl,
macAddress: playlist.macAddress,
params,
});
// Re-check after transport: Edit may have committed while the direct
// request was in flight. In simple mode this guard remains network-free.
await deps.stalkerSession.ensureToken(sessionPlaylist);
return response;
}
/**