diff --git a/CLAUDE.md b/CLAUDE.md index a6efda405..a02d72536 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1265,7 +1265,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. A metadata-only Save omits connection/mode fields from its queued update, so the stored connection stays byte-identical even if the dialog hydrated before a concurrent discovery committed; it skips discovery. A persisted `portalUrl` keeps the row on the Stalker save path even if legacy Xtream fields remain. 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, PWA acquires a shared playlist-authority barrier plus an exclusive origin-wide per-playlist Web Lock and verifies the persisted source authority while holding both. Add/delete, backup restore, and bulk replacement take the same row lock, while Delete All takes the barrier exclusively, so authority cannot change between preflight and the identity-bearing request. A concurrent Edit or stale dialog fails before remote discovery; a replacement waits for the current owner. PWA fails closed if Web Locks are unavailable, while Electron relies on its single-instance local 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. That late commit uses `transformPlaylistMeta()` inside the per-playlist write queue to merge only connection/session fields into the current row, so newer title/EPG/metadata edits win; its returned row feeds the state-only update together with discovery's transient session patch, so NgRx replaces or clears its session fields 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. +- `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 reads the persisted source or calls discovery, PWA takes the same playlist-authority barrier and row reservation as explicit Edit; contention or unavailable Web Locks declines repair without a remote request, and ownership is held through the conditional transform. This prevents repair in another tab from authenticating alongside Edit or crossing delete/restore. The persisted-row preflight still verifies that the caller 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. - 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 1c44a62d1..75e7d84e3 100644 --- a/docs/architecture/stalker-portal.md +++ b/docs/architecture/stalker-portal.md @@ -235,9 +235,12 @@ cannot be replaced between that preflight and the identity-bearing discovery request. Another tab fails before overlapping discovery, while a replacement waits for the existing Edit owner; a stale dialog also fails before it can touch the remote session. PWA fails closed when Web Locks are unavailable, while -Electron relies on its single-instance local 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. +Electron relies on its single-instance local owner. Lazy repair tries the same +barrier and row reservation before its persisted-source preflight; contention +or unavailable PWA locking declines repair without discovery, while an acquired +reservation stays held through its conditional row transform. 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 every asynchronous drain or authority rebase. Ordinary failure releases that reservation with the previous runtime untouched; if a bounded discovery result still has an abandoned authentication on the 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 7723eadeb..4f56c2c8d 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 @@ -31,6 +31,7 @@ async function flushMicrotasks(): Promise { } describe('StalkerPortalRepairService', () => { + const originalLockManager = globalThis.navigator?.locks; let service: StalkerPortalRepairService; let discover: jest.Mock; let transformPlaylistMeta: jest.Mock; @@ -50,6 +51,22 @@ describe('StalkerPortalRepairService', () => { let completePortalRepairDiscovery: jest.Mock; beforeEach(() => { + Object.defineProperty(globalThis.navigator, 'locks', { + configurable: true, + value: { + request: jest.fn( + async ( + name: string, + options: LockOptions, + callback: (lock: Lock | null) => Promise + ) => + callback({ + name, + mode: options.mode ?? 'exclusive', + } as Lock) + ), + }, + }); discover = jest.fn(); persistedRow = MISCLASSIFIED as Playlist; writtenRow = null; @@ -115,6 +132,13 @@ describe('StalkerPortalRepairService', () => { service = TestBed.inject(StalkerPortalRepairService); }); + afterEach(() => { + Object.defineProperty(globalThis.navigator, 'locks', { + configurable: true, + value: originalLockManager, + }); + }); + describe('shouldAttemptRepair', () => { it('triggers on the middleware plain-text auth bodies', () => { expect( @@ -215,6 +239,104 @@ describe('StalkerPortalRepairService', () => { }); describe('repairPortal', () => { + it('does not preflight or discover while another tab owns the playlist authority', async () => { + const request = jest.fn( + async ( + name: string, + options: LockOptions, + callback: (lock: Lock | null) => Promise + ) => { + if (name === 'iptvnator:playlist-authority') { + return callback({ + name, + mode: options.mode ?? 'shared', + } as Lock); + } + return callback(null); + } + ); + Object.defineProperty(globalThis.navigator, 'locks', { + configurable: true, + value: { request }, + }); + discover.mockResolvedValue({ + status: 'resolved', + portalUrl: MISCLASSIFIED.portalUrl, + isFullStalkerPortal: true, + }); + + await expect( + service.repairPortal(MISCLASSIFIED) + ).resolves.toBeNull(); + + expect(getPlaylistById).not.toHaveBeenCalled(); + expect(beginPortalRepairDiscovery).not.toHaveBeenCalled(); + expect(discover).not.toHaveBeenCalled(); + }); + + it('holds playlist authority from persisted preflight through the conditional commit', async () => { + let rowAuthorityHeld = false; + const request = jest.fn( + async ( + name: string, + options: LockOptions, + callback: (lock: Lock | null) => Promise + ) => { + if (name === 'iptvnator:playlist-authority') { + return callback({ name, mode: 'shared' } as Lock); + } + rowAuthorityHeld = true; + try { + return await callback({ + name, + mode: options.mode ?? 'exclusive', + } as Lock); + } finally { + rowAuthorityHeld = false; + } + } + ); + Object.defineProperty(globalThis.navigator, 'locks', { + configurable: true, + value: { request }, + }); + getPlaylistById.mockImplementation(() => { + expect(rowAuthorityHeld).toBe(true); + return of(persistedRow); + }); + discover.mockImplementation(async () => { + expect(rowAuthorityHeld).toBe(true); + return { + status: 'resolved', + portalUrl: MISCLASSIFIED.portalUrl, + isFullStalkerPortal: true, + token: 'LOCKED_REPAIR_TOKEN', + }; + }); + transformPlaylistMeta.mockImplementation((_id, transform) => { + expect(rowAuthorityHeld).toBe(true); + const next = transform(persistedRow) as Playlist; + writtenRow = next; + return of(next); + }); + + await expect( + service.repairPortal(MISCLASSIFIED) + ).resolves.toMatchObject({ isFullStalkerPortal: true }); + + expect(rowAuthorityHeld).toBe(false); + expect(request).toHaveBeenCalledWith( + 'iptvnator:playlist-authority', + { mode: 'shared' }, + expect.any(Function) + ); + expect(request).toHaveBeenCalledWith( + `iptvnator:playlist-authority:${MISCLASSIFIED._id}`, + { ifAvailable: true, mode: 'exclusive' }, + expect.any(Function) + ); + }); + it('persists a proven different mode and returns the patched playlist', async () => { discover.mockResolvedValue({ status: 'resolved', @@ -959,14 +1081,18 @@ describe('StalkerPortalRepairService', () => { completePortalRepairDiscovery.mockClear(); const repair = service.repairPortal(MISCLASSIFIED); + while (getPlaylistById.mock.calls.length === 0) { + await Promise.resolve(); + } expect(getPlaylistById).toHaveBeenCalledTimes(1); - // No pending repair exists yet on this history path, so Edit's - // drain resolves immediately while the row read is still live. - await service.fenceForPlaylistEdit(MISCLASSIFIED._id); + // Edit installs its generation fence immediately, then drains + // the published repair owner while the row read is still live. + const editDrain = service.fenceForPlaylistEdit(MISCLASSIFIED._id); historyRead.next(MISCLASSIFIED as Playlist); historyRead.complete(); await expect(repair).resolves.toBeNull(); + await editDrain; expect(beginPortalRepairDiscovery).not.toHaveBeenCalled(); expect(discover).not.toHaveBeenCalled(); 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 eeafb8c12..62614e628 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 @@ -22,6 +22,7 @@ import { type StalkerPortalModeOverride, type StalkerProbeRecord, } from './stalker-portal-repair-state'; +import { StalkerRepairAuthorityCoordinator } from './stalker-repair-authority-coordinator'; import { StalkerSessionService } from './stalker-session.service'; import { type StalkerPortalRepairApi, @@ -80,10 +81,7 @@ export class StalkerPortalRepairService implements StalkerPortalRepairApi { string, Map >(); - private readonly pendingRepairs = new Map< - string, - Promise - >(); + private readonly repairAuthority = new StalkerRepairAuthorityCoordinator(); /** Explicit Edit invalidates every repair that started before it. */ private readonly editGenerations = new Map(); private readonly editFenceCounts = new Map(); @@ -192,10 +190,7 @@ export class StalkerPortalRepairService implements StalkerPortalRepairApi { playlistId, (this.editGenerations.get(playlistId) ?? 0) + 1 ); - return ( - this.pendingRepairs.get(playlistId)?.catch(() => null) ?? - Promise.resolve() - ).then(() => undefined); + return this.repairAuthority.wait(playlistId).then(() => undefined); } /** Releases the repair fence when discovery or persistence fails. */ @@ -295,17 +290,17 @@ export class StalkerPortalRepairService implements StalkerPortalRepairApi { if ((this.editFenceCounts.get(playlistId) ?? 0) > 0) { return null; } - const editGeneration = this.editGenerations.get(playlistId) ?? 0; - const pending = this.pendingRepairs.get(playlistId); - if (pending) { - // Wait the in-flight probe out, then RE-ENTER: the caller may - // carry a different (edited) configuration whose fingerprint - // was never attempted — it must get its own probe instead of - // inheriting whatever the old repair concluded. - await pending; - return this.repairPortal(playlist); - } + return this.repairAuthority.run(playlistId, () => + this.repairPortalWithAuthority(playlist) + ); + } + + private async repairPortalWithAuthority( + playlist: PlaylistMeta + ): Promise { + const playlistId = playlist._id; + const editGeneration = this.editGenerations.get(playlistId) ?? 0; const fingerprint = stalkerRepairSourceFingerprint(playlist); const history = this.probeHistory.get(playlistId) ?? new Map(); @@ -366,11 +361,9 @@ export class StalkerPortalRepairService implements StalkerPortalRepairApi { const run = authenticationFence.drained.then(() => this.runRepair(playlist, editGeneration) ); - this.pendingRepairs.set(playlistId, run); try { return await run; } finally { - this.pendingRepairs.delete(playlistId); this.stalkerSession.completePortalRepairDiscovery( authenticationFence ); @@ -379,7 +372,7 @@ export class StalkerPortalRepairService implements StalkerPortalRepairApi { /** Lets request routing choose its effective row after repair settles. */ async waitForPendingRepair(playlistId: string): Promise { - await this.pendingRepairs.get(playlistId)?.catch(() => null); + await this.repairAuthority.wait(playlistId); } private reapplyIfChanged(playlist: PlaylistMeta): PlaylistMeta | null { diff --git a/libs/portal/stalker/data-access/src/lib/stalker-repair-authority-coordinator.ts b/libs/portal/stalker/data-access/src/lib/stalker-repair-authority-coordinator.ts new file mode 100644 index 000000000..0ff94be52 --- /dev/null +++ b/libs/portal/stalker/data-access/src/lib/stalker-repair-authority-coordinator.ts @@ -0,0 +1,52 @@ +import { reservePlaylistAuthority } from '@iptvnator/services'; +import type { PlaylistMeta } from '@iptvnator/shared/interfaces'; + +/** Shares one repair locally and reserves its source across PWA tabs. */ +export class StalkerRepairAuthorityCoordinator { + private readonly pending = new Map>(); + + async run( + playlistId: string, + operation: () => Promise + ): Promise { + const pending = this.pending.get(playlistId); + if (pending) { + await pending; + return this.run(playlistId, operation); + } + + // Publish before the Web Lock request yields so concurrent failures + // in this tab share one reservation and outcome. + const run = this.runReserved(playlistId, operation); + this.pending.set(playlistId, run); + try { + return await run; + } finally { + if (this.pending.get(playlistId) === run) { + this.pending.delete(playlistId); + } + } + } + + async wait(playlistId: string): Promise { + await this.pending.get(playlistId)?.catch(() => null); + } + + private async runReserved( + playlistId: string, + operation: () => Promise + ): Promise { + const reservation = await reservePlaylistAuthority(playlistId).catch( + () => ({ status: 'unavailable' as const }) + ); + if (reservation.status !== 'acquired') { + return null; + } + + try { + return await operation(); + } finally { + reservation.release(); + } + } +} diff --git a/libs/services/src/lib/playlist-cross-context-lock.ts b/libs/services/src/lib/playlist-cross-context-lock.ts index 6e8807055..4448b1fa0 100644 --- a/libs/services/src/lib/playlist-cross-context-lock.ts +++ b/libs/services/src/lib/playlist-cross-context-lock.ts @@ -1,5 +1,10 @@ const PLAYLIST_AUTHORITY_BARRIER = 'iptvnator:playlist-authority'; +export type PlaylistAuthorityReservation = + | { readonly status: 'acquired'; readonly release: () => void } + | { readonly status: 'busy' } + | { readonly status: 'unavailable' }; + function getLockManager(): LockManager | undefined { return globalThis.navigator?.locks; } @@ -60,19 +65,19 @@ export async function runWithPlaylistAuthorityReset( ); } -/** Holds one origin-wide edit reservation until persistence or cancellation. */ -export async function acquirePlaylistAuthorityEditReservation( +/** Tries to hold one origin-wide row reservation until its owner releases it. */ +export async function reservePlaylistAuthority( playlistId: string -): Promise<() => void> { +): Promise { const locks = getLockManager(); if (!locks) { const isElectronRenderer = typeof window !== 'undefined' && Boolean((window as Window & { electron?: unknown }).electron); if (typeof window === 'undefined' || isElectronRenderer) { - return () => undefined; + return { status: 'acquired', release: () => undefined }; } - throw new Error('Cross-context playlist edit locking is unavailable'); + return { status: 'unavailable' }; } let releaseHeldLock: () => void = () => undefined; @@ -101,14 +106,31 @@ export async function acquirePlaylistAuthorityEditReservation( }); if (!(await acquired)) { - throw new Error('Stalker playlist edit already in progress'); + return { status: 'busy' }; } let released = false; - return () => { - if (!released) { - released = true; - releaseHeldLock(); - } + return { + status: 'acquired', + release: () => { + if (!released) { + released = true; + releaseHeldLock(); + } + }, }; } + +/** Holds one origin-wide Edit reservation until persistence or cancellation. */ +export async function acquirePlaylistAuthorityEditReservation( + playlistId: string +): Promise<() => void> { + const reservation = await reservePlaylistAuthority(playlistId); + if (reservation.status === 'acquired') { + return reservation.release; + } + if (reservation.status === 'unavailable') { + throw new Error('Cross-context playlist edit locking is unavailable'); + } + throw new Error('Stalker playlist edit already in progress'); +}