fix(stalker): persist submitted identity after navigation

This commit is contained in:
4gray committed 2026-08-09 17:40:55 +02:00
1 parent 5184bc042c
commit ffae919cc8
7 files changed
+39 -54

No files matched your search

+1 -1
View File
@@ -1263,7 +1263,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. 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.
- 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`. Once Save starts, navigation or dialog destruction does not discard a later successful result: `get_profile` may already have pinned the submitted serial/device identity remotely and cannot be recalled, so the atomic persistence and state-only update complete while success UI is suppressed. 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. 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 only after the persisted row confirms ownership and only if no explicit Edit took ownership during that read, so a delayed stale request cannot remove valid runtime state or a token negotiated by the overlapping Edit. 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. Lazy repair captures that generation before any probe-history row read and rechecks it with the active Edit fence before reserving discovery. A repair that started earlier is therefore discarded even if it was restoring a `discarded` history record or had already verified its row, so it cannot probe alongside Edit or restore an older endpoint, mode or token afterwards.
- 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.
@@ -126,23 +126,6 @@ describe('AppStalkerPlaylistConnectionEditorService', () => {
});
});
it('releases a successful discovery fence when the resolved edit is discarded', async () => {
discovery.discover.mockResolvedValue({
status: 'resolved',
portalUrl: 'https://portal.example.com/portal.php',
isFullStalkerPortal: false,
});
await service.resolveConnection(draft);
service.discardResolvedConnection(draft._id);
expect(stalkerSession.cancelEditDiscovery).toHaveBeenCalledWith(
expect.objectContaining({ playlistId: draft._id })
);
expect(portalRepair.releasePlaylistEdit).toHaveBeenCalledWith(
draft._id
);
});
it('replaces a full-portal session with the confirmed authorization result', async () => {
discovery.discover.mockResolvedValue({
status: 'resolved',
@@ -77,13 +77,6 @@ export class AppStalkerPlaylistConnectionEditorService implements StalkerPlaylis
}
}
discardResolvedConnection(playlistId: string): void {
const fence = this.editFences.get(playlistId);
if (fence) {
this.releaseEditFence(playlistId, fence);
}
}
async resolveConnection(
playlist: PlaylistMeta
): Promise<StalkerPlaylistConnectionResult> {
+8 -7
View File
@@ -205,9 +205,11 @@ Changing any connection field disables the form while the same discovery
service validates the draft. Auth rejection or an unreachable portal leaves
the dialog open and writes nothing. Escape/backdrop closure is disabled for the
validation window. If navigation or another owner starts closing/destroys the
dialog while discovery is in flight, the successful result is discarded before
persistence and both the session and repair reservations are released. Before
discovery starts, Edit reserves the playlist ID; an
dialog while discovery is in flight, a successful result still crosses the
atomic persistence boundary: the submitted `get_profile` may already have
pinned the new serial/device identity remotely and cannot be recalled. The
state-only update also completes, while dialog close and success UI are
suppressed after destruction. Before discovery starts, Edit reserves the playlist ID; an
overlapping Edit cannot replace that owner. The reservation blocks every new
authentication (including a URL edit with the same normalized fingerprint) and
repair, and drains any work already in flight. Ownership is rechecked after
@@ -241,10 +243,9 @@ schema or backup-version migration is required.
The shared playlist UI exposes only
`STALKER_PLAYLIST_CONNECTION_EDITOR` and its
`resolved | auth-rejected | unreachable` result contract, plus the narrow
`discardResolvedConnection()` cleanup hook for a closing dialog. The web
composition layer implements the token with Stalker data-access; the UI library
must not import Stalker discovery directly.
`resolved | auth-rejected | unreachable` result contract. The web composition
layer implements the token with Stalker data-access; the UI library must not
import Stalker discovery directly.
**Lazy repair (existing playlists).** The flag is frozen in the DB, so
records persisted by the old guess stay broken without repair — but a large
@@ -58,7 +58,6 @@ describe('PlaylistInfoComponent', () => {
let dialogBeforeClosed: Subject<void>;
let stalkerConnectionEditor: {
applyResolvedConnection: jest.Mock;
discardResolvedConnection: jest.Mock;
resolveConnection: jest.Mock;
};
const originalElectron = window.electron;
@@ -117,7 +116,6 @@ describe('PlaylistInfoComponent', () => {
};
stalkerConnectionEditor = {
applyResolvedConnection: jest.fn().mockResolvedValue(undefined),
discardResolvedConnection: jest.fn(),
resolveConnection: jest.fn(
async (updatedPlaylist: PlaylistMeta) => ({
status: STALKER_PLAYLIST_CONNECTION_EDITOR_STATUS.RESOLVED,
@@ -832,7 +830,7 @@ describe('PlaylistInfoComponent', () => {
expect(dialogRef.close).toHaveBeenCalledTimes(1);
});
it('discards a resolved edit when the dialog closes before discovery finishes', async () => {
it('persists a resolved edit when the component is destroyed during discovery', async () => {
await createStalkerComponent();
const resolvedPlaylist = {
...component.playlistDetails.getRawValue(),
@@ -869,16 +867,20 @@ describe('PlaylistInfoComponent', () => {
});
await saving;
expect(
stalkerConnectionEditor.discardResolvedConnection
).toHaveBeenCalledWith('playlist-1');
expect(
stalkerConnectionEditor.applyResolvedConnection
).not.toHaveBeenCalled();
expect(store.dispatch).not.toHaveBeenCalled();
).toHaveBeenCalledWith(resolvedPlaylist);
expect(store.dispatch).toHaveBeenCalledWith(
PlaylistActions.updatePlaylistMeta({
playlist: resolvedPlaylist,
persist: false,
})
);
expect(snackBar.open).not.toHaveBeenCalled();
expect(dialogRef.close).not.toHaveBeenCalled();
});
it('discards a resolved edit while the dialog close animation is pending', async () => {
it('persists a resolved edit while the dialog close animation is pending', async () => {
await createStalkerComponent();
const resolvedPlaylist = {
...component.playlistDetails.getRawValue(),
@@ -915,13 +917,17 @@ describe('PlaylistInfoComponent', () => {
});
await saving;
expect(
stalkerConnectionEditor.discardResolvedConnection
).toHaveBeenCalledWith('playlist-1');
expect(
stalkerConnectionEditor.applyResolvedConnection
).not.toHaveBeenCalled();
expect(store.dispatch).not.toHaveBeenCalled();
).toHaveBeenCalledWith(resolvedPlaylist);
expect(store.dispatch).toHaveBeenCalledWith(
PlaylistActions.updatePlaylistMeta({
playlist: resolvedPlaylist,
persist: false,
})
);
expect(snackBar.open).not.toHaveBeenCalled();
expect(dialogRef.close).not.toHaveBeenCalled();
});
it('does not update UI state or report success when resolved persistence fails', async () => {
@@ -423,12 +423,6 @@ export class PlaylistInfoComponent {
);
return;
}
if (this.dialogClosing || this.destroyRef.destroyed) {
this.stalkerConnectionEditor.discardResolvedConnection(
result.playlist._id
);
return;
}
normalizedPlaylist = result.playlist;
resolvedStalkerConnection = true;
} else {
@@ -464,6 +458,16 @@ export class PlaylistInfoComponent {
})
);
// Save already authorized this connection change, and a full
// portal's completed get_profile may have pinned the submitted
// serial/device identity remotely. Navigation cannot recall that
// request, so the resolved identity/session is persisted above
// even when the dialog disappears. Only view-side completion is
// suppressed after destruction/close animation begins.
if (this.dialogClosing || this.destroyRef.destroyed) {
return;
}
this.snackBar.open(
this.translate.instant(
'HOME.PLAYLISTS.PLAYLIST_UPDATE_SUCCESS'
@@ -40,8 +40,6 @@ export interface StalkerPlaylistConnectionEditor {
): Promise<StalkerPlaylistConnectionResult>;
/** Atomically persists a resolved edit, then synchronizes in-run state. */
applyResolvedConnection(playlist: PlaylistMetaUpdate): Promise<void>;
/** Releases a resolved edit that the dialog closed without applying. */
discardResolvedConnection(playlistId: string): void;
}
export const STALKER_PLAYLIST_CONNECTION_EDITOR =