diff --git a/CLAUDE.md b/CLAUDE.md index a02d72536..f692fec17 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1264,7 +1264,7 @@ engine` (restart required) or - Every resolved Edit commit is guarded by the source connection authority captured when Edit began. Electron checks it inside the per-playlist write queue; PWA performs the read, predicate, and cursor update in one IndexedDB readwrite transaction, so another tab cannot interleave a replacement. The one-time legacy mode-flag migration also scans and updates rows through one readwrite cursor transaction and never replays a pre-transaction snapshot. Delete/restore or replacement under the same playlist ID aborts both ordinary and post-navigation writes; the latter still merge concurrent title/EPG metadata when authority matches. - 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. +- 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. Same-tab Save first publishes its local authentication owner, drains an existing lazy repair through actual Web Lock request completion, and only then asks for the conflicting row lock. 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 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. diff --git a/apps/web/src/app/services/stalker-playlist-connection-editor.service.spec.ts b/apps/web/src/app/services/stalker-playlist-connection-editor.service.spec.ts index 6ff536f71..91b89bd86 100644 --- a/apps/web/src/app/services/stalker-playlist-connection-editor.service.spec.ts +++ b/apps/web/src/app/services/stalker-playlist-connection-editor.service.spec.ts @@ -107,7 +107,8 @@ describe('AppStalkerPlaylistConnectionEditorService', () => { expect.objectContaining({ portalUrl: sourcePlaylist.portalUrl, stalkerSerialNumber: sourcePlaylist.stalkerSerialNumber, - }) + }), + expect.any(Promise) ); expect(discovery.discover).toHaveBeenCalledWith( diff --git a/apps/web/src/app/services/stalker-playlist-connection-editor.service.ts b/apps/web/src/app/services/stalker-playlist-connection-editor.service.ts index 34374856d..ed50c4526 100644 --- a/apps/web/src/app/services/stalker-playlist-connection-editor.service.ts +++ b/apps/web/src/app/services/stalker-playlist-connection-editor.service.ts @@ -222,7 +222,8 @@ export class AppStalkerPlaylistConnectionEditorService implements StalkerPlaylis try { fence = await this.stalkerSession.beginEditDiscovery( playlist, - sourcePlaylist + sourcePlaylist, + repairDrain ); await repairDrain; this.editFences.set(playlist._id, fence); diff --git a/docs/architecture/stalker-portal.md b/docs/architecture/stalker-portal.md index 75e7d84e3..82a005627 100644 --- a/docs/architecture/stalker-portal.md +++ b/docs/architecture/stalker-portal.md @@ -241,6 +241,9 @@ 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. +When Save follows a lazy repair in the same tab, Edit publishes its local +authentication owner first, drains that repair through the actual Web Lock +request completion, and only then requests the row reservation itself. 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-edited-session-coordinator.spec.ts b/libs/portal/stalker/data-access/src/lib/stalker-edited-session-coordinator.spec.ts index 9f7c28015..b1f7f46c5 100644 --- a/libs/portal/stalker/data-access/src/lib/stalker-edited-session-coordinator.spec.ts +++ b/libs/portal/stalker/data-access/src/lib/stalker-edited-session-coordinator.spec.ts @@ -150,6 +150,35 @@ describe('Stalker edited-session coordination', () => { service.cancelEditDiscovery(fence); }); + it('publishes Edit ownership while draining local repair before requesting the row lock', async () => { + let finishRepairDrain: () => void = () => undefined; + const repairDrain = new Promise((resolve) => { + finishRepairDrain = resolve; + }); + const request = globalThis.navigator?.locks?.request as jest.Mock; + + const fencePromise = service.beginEditDiscovery( + oldPlaylist, + oldPlaylist, + repairDrain + ); + await Promise.resolve(); + + expect(request).not.toHaveBeenCalled(); + await expect(service.beginEditDiscovery(oldPlaylist)).rejects.toThrow( + /already in progress/i + ); + + finishRepairDrain(); + const fence = await fencePromise; + expect(request).toHaveBeenCalledWith( + 'iptvnator:playlist-authority', + { mode: 'shared' }, + expect.any(Function) + ); + service.cancelEditDiscovery(fence); + }); + it('blocks new authentication while a same-fingerprint edit owns the playlist', async () => { const textOnlyEdit = { ...oldPlaylist, diff --git a/libs/portal/stalker/data-access/src/lib/stalker-edited-session-coordinator.ts b/libs/portal/stalker/data-access/src/lib/stalker-edited-session-coordinator.ts index 352466f45..ce5ee895c 100644 --- a/libs/portal/stalker/data-access/src/lib/stalker-edited-session-coordinator.ts +++ b/libs/portal/stalker/data-access/src/lib/stalker-edited-session-coordinator.ts @@ -92,7 +92,8 @@ export class StalkerEditedSessionCoordinator { async beginEdit( playlist: Playlist, - sourcePlaylist: Playlist = playlist + sourcePlaylist: Playlist = playlist, + beforeCrossContextReservation: Promise = Promise.resolve() ): Promise { const playlistId = playlist._id; if (sourcePlaylist._id !== playlistId) { @@ -113,6 +114,11 @@ export class StalkerEditedSessionCoordinator { }); try { + // The local Edit owner is already published, blocking new auth. + // A same-tab repair may still hold the cross-context row lock; + // drain it before requesting that lock instead of failing Save. + await beforeCrossContextReservation; + this.assertFenceCurrent(fence, configurationFingerprint); const releaseCrossContextReservation = await acquireCrossContextEditReservation(playlistId); const pending = this.pendingEdits.get(playlistId); 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 4f56c2c8d..f74e8c2de 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 @@ -276,6 +276,10 @@ describe('StalkerPortalRepairService', () => { it('holds playlist authority from persisted preflight through the conditional commit', async () => { let rowAuthorityHeld = false; + let finishPhysicalRelease: () => void = () => undefined; + const physicalRelease = new Promise((resolve) => { + finishPhysicalRelease = resolve; + }); const request = jest.fn( async ( name: string, @@ -287,10 +291,12 @@ describe('StalkerPortalRepairService', () => { } rowAuthorityHeld = true; try { - return await callback({ + const result = await callback({ name, mode: options.mode ?? 'exclusive', } as Lock); + await physicalRelease; + return result; } finally { rowAuthorityHeld = false; } @@ -320,9 +326,22 @@ describe('StalkerPortalRepairService', () => { return of(next); }); - await expect( - service.repairPortal(MISCLASSIFIED) - ).resolves.toMatchObject({ isFullStalkerPortal: true }); + let repairSettled = false; + const repair = service.repairPortal(MISCLASSIFIED); + void repair.then(() => { + repairSettled = true; + }); + while (transformPlaylistMeta.mock.calls.length === 0) { + await Promise.resolve(); + } + await flushMicrotasks(); + expect(repairSettled).toBe(false); + expect(rowAuthorityHeld).toBe(true); + + finishPhysicalRelease(); + await expect(repair).resolves.toMatchObject({ + isFullStalkerPortal: true, + }); expect(rowAuthorityHeld).toBe(false); expect(request).toHaveBeenCalledWith( 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 index 0ff94be52..efb11aeda 100644 --- 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 @@ -47,6 +47,7 @@ export class StalkerRepairAuthorityCoordinator { return await operation(); } finally { reservation.release(); + await reservation.released; } } } diff --git a/libs/portal/stalker/data-access/src/lib/stalker-session.service.ts b/libs/portal/stalker/data-access/src/lib/stalker-session.service.ts index 26860f5fc..6e7a3464c 100644 --- a/libs/portal/stalker/data-access/src/lib/stalker-session.service.ts +++ b/libs/portal/stalker/data-access/src/lib/stalker-session.service.ts @@ -255,9 +255,14 @@ export class StalkerSessionService { */ beginEditDiscovery( playlist: Playlist, - sourcePlaylist: Playlist = playlist + sourcePlaylist: Playlist = playlist, + beforeCrossContextReservation: Promise = Promise.resolve() ): Promise { - return this.editedSessions.beginEdit(playlist, sourcePlaylist); + return this.editedSessions.beginEdit( + playlist, + sourcePlaylist, + beforeCrossContextReservation + ); } /** diff --git a/libs/services/src/lib/playlist-cross-context-lock.ts b/libs/services/src/lib/playlist-cross-context-lock.ts index 4448b1fa0..3461e7830 100644 --- a/libs/services/src/lib/playlist-cross-context-lock.ts +++ b/libs/services/src/lib/playlist-cross-context-lock.ts @@ -1,7 +1,11 @@ const PLAYLIST_AUTHORITY_BARRIER = 'iptvnator:playlist-authority'; export type PlaylistAuthorityReservation = - | { readonly status: 'acquired'; readonly release: () => void } + | { + readonly status: 'acquired'; + readonly release: () => void; + readonly released: Promise; + } | { readonly status: 'busy' } | { readonly status: 'unavailable' }; @@ -75,7 +79,11 @@ export async function reservePlaylistAuthority( typeof window !== 'undefined' && Boolean((window as Window & { electron?: unknown }).electron); if (typeof window === 'undefined' || isElectronRenderer) { - return { status: 'acquired', release: () => undefined }; + return { + status: 'acquired', + release: () => undefined, + released: Promise.resolve(), + }; } return { status: 'unavailable' }; } @@ -84,6 +92,7 @@ export async function reservePlaylistAuthority( const held = new Promise((resolve) => { releaseHeldLock = resolve; }); + let requestSettled = Promise.resolve(); const acquired = new Promise((resolve, reject) => { const request = locks.request( PLAYLIST_AUTHORITY_BARRIER, @@ -102,6 +111,7 @@ export async function reservePlaylistAuthority( } ) ); + requestSettled = request.then(() => undefined); void request.catch(reject); }); @@ -118,6 +128,7 @@ export async function reservePlaylistAuthority( releaseHeldLock(); } }, + released: requestSettled, }; }