feat(settings): PIN-protected parental lock for categories (#285) (#1601)

* feat(settings): add PIN-protected parental lock for categories (#285)

Locks are per category (Xtream category ids, Stalker genre ids, M3U group
titles) and kept in one renderer lock store persisted to app_state /
localStorage; `categories.locked` is the SQLite index re-stamped from it.
While the lock is active the DB worker filters every content read, the PWA
data source, the Stalker store and the M3U channel list filter in memory,
and the enforcement service reloads the stores and steps off withheld
selections. Settings → Parental lock sets the PIN (PBKDF2, never in
Settings), the relock timeout and Lock now; lock toggles live in the
Xtream/M3U management dialogs and a new Stalker lock dialog, all behind
the PIN. Backups carry the locks per playlist entry.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): harden the parental lock after review

- The M3U group dialog opens only after the PIN, like the Xtream and Stalker
  dialogs: it lists locked group names and can rewrite the locks.
- Change PIN and Disable always verify the stored hash, even while the
  session is unlocked, so an app left unlocked cannot lose its lock.
- Stalker paging judges progress on the raw portal page: withheld ids the
  list has not seen count as progress, a page made only of locked rows
  requests the next one itself, and the VOD total is reduced by withheld
  ids so the grid stops asking once every visible row is in.
- Parental lock contract linked from the agent context map after the
  guidance reorganization; bridge helpers split out to stay under the
  file-size cap.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): guard locked categories on routes, PWA search and paging

- Xtream and Stalker `:categoryId` routes carry a parental-lock guard: a
  locked category reached by URL prompts for the PIN and redirects to the
  section root on refusal (Electron row ids are mapped to provider ids).
- PWA search filters withheld categories like the catalog reads.
- Electron warm-cache detection confirms an empty, lock-filtered read with
  the unfiltered existence check instead of refetching from the provider.
- A Stalker lock flip past page 1 drops withheld rows at once and restarts
  the list from page 1 instead of appending onto stale pages.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): compile the PIN hashing helper in the Node backend build

The web backend compiles the shared interfaces library without DOM typings,
so the DOM-only `SubtleCrypto` / `BufferSource` names broke its Docker
build. The helper now describes the WebCrypto surface it needs structurally
and reaches it through `globalThis`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): close the remaining parental-lock gaps from review

- Detail routes check the item's own category: a locked movie or series
  paired with an unlocked category id in the URL is still refused.
- `requestUnlock()` awaits the settings load before it can answer "not
  active", so a slow startup cannot open a management dialog unguarded.
- `SETTINGS_UPDATE` only persists the `parentalLockEnabled` mirror and
  releases the worker on switch-off; it no longer re-locks the worker on
  every ordinary settings save under a renderer that shows "unlocked".

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): cover PWA cold navigation, Stalker search and the PWA lock editor

- The Xtream detail guard hydrates the PWA session cache before judging an
  item on a cold navigation and fails closed when the catalog cannot place
  the item.
- The dedicated Stalker search route filters withheld genres, re-fires on
  lock changes, judges paging on the raw page and restarts from page 1 on a
  lock flip.
- The Xtream category dialog loads its lock candidates through the
  capability-selected data source; the PWA source now lists its raw
  categories with lock flags, so locks can be configured there too.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): arm the relock timer on enable and harden Stalker search relock

- The idle timer follows the unlocked transition instead of `active`, so the
  session that just enabled the lock still locks itself later.
- Stalker search closes an open detail whose genre became withheld on
  relock and advances by itself past pages made only of locked rows (only
  while they add ids the list has not seen).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): close lock editors on relock and clear withheld details opened from All

The Xtream, Stalker and M3U category editors are gated by the PIN only when
they open; an idle relock left them on screen listing locked names with a
lock-rewriting Save. Each now closes itself when the session relocks.

ParentalLockEnforcementService also judges the selected Xtream/Stalker
item by its own category: a detail opened from All, recently added or
search has no selected category to vanish with, so it stayed open after a
relock.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): fail closed on unreadable settings and finish relock clean-up

- Unreadable settings (IndexedDB load failure) left the feature switch at
  its default and announced "unlocked" to the main process. A stored PIN
  now stands in for the switch, and without one nothing is announced, so
  the worker keeps its mirrored locked default.
- Lock applies run one at a time and abandon superseded results; the
  Electron data source keys its in-flight share by lock version so a
  relock can never reuse an unlock refresh's unfiltered rows.
- The stored in-portal Xtream search is re-run on a lock change.
- Stalker live/radio selections are judged by tv_genre_id, and both live
  layouts drop the playback of a channel whose category became withheld.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): fail closed on an unreadable lock store and make lock writes reliable

- A lock store that cannot be read is no longer treated as empty: while
  the lock is active every category is withheld (renderer predicates and
  set-based filters alike) until the PIN is entered or the store reads
  again, and writes are refused meanwhile so an empty in-memory store can
  never wipe the persisted locks. The lock set now lives in its own
  ParentalLockLockStore service.
- The M3U group dialog's lock write is awaited and a failed save is
  reported in a snackbar instead of being silently dropped.
- The Electron categories.locked re-stamp clears and re-locks inside one
  transaction, so a failed restamp keeps the previous index.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): drop pre-relock Stalker search pages and fail closed on a corrupt lock store

- A Stalker search page issued before a relock was filtered with the
  pre-relock withheld set and could still be applied after it; the
  staleness check now includes the parental lock version.
- A lock store payload that does not parse or is not an object is a
  failed read (everything withheld until it reads again), no longer an
  empty store.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): close the startup, re-stamp, relock-refresh and switch-persistence gaps

- The window before the initial lock store read settles now withholds
  everything, like an unreadable store: settings can report the feature as
  on before the locks are known.
- The store commits before the SQLite index re-stamp; a failed re-stamp
  now rolls the store back, a failed rollback re-stamps on the next
  access, and every launch re-derives the index from the store.
- Xtream category/content reloads fail closed: a rejected reload empties
  the affected lists (content types drop back to idle) instead of keeping
  rows read under the previous lock state.
- Enabling/disabling the feature persists through one guarded path that
  undoes the in-memory switch and skips the Electron mirror on a failed
  settings write.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test(xtream): move the parental-lock reload specs beside the content spec

The content feature spec sits at the 1200-line spec cap.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): await the startup lock-index reconciliation and withhold genre-less rows when failing closed

- The lock store is readable only once the SQLite index has been re-derived
  from it, and a re-stamp that keeps failing keeps the session fail-closed,
  so catalog reads can never serve rows stamped unlocked by a stale index.
- While everything is withheld, Stalker rows without a genre are withheld
  as well (the store filter and the renderer predicate).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): await the enablement mirror, restore partial lock stamps and validate nested lock-store entries

- The Electron mirror of the feature switch is awaited; a mirror that
  cannot be written undoes the settings write, so a reload never starts
  from a mirror that disagrees with the persisted switch.
- A failed multi-type re-stamp rolls the store back AND re-stamps every
  touched type from it, since earlier types may already carry the new
  locks; a failed rollback keeps the playlist stale (fail-closed).
- A persisted lock store whose nested entries are not what writeLocks
  produces is a failed read, not an empty store.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): withhold the Xtream catalog at relock time, keep exact M3U titles in backups, roll back a failed relock-timeout save

- A relock now fails closed immediately: the selected detail is stepped
  off against the lock store, the catalog lists and stored search results
  are emptied, and the filtered reloads publish only while the captured
  lock version is still current.
- Backups carry M3U lock titles verbatim (exact dedup), since the locks
  match group titles exactly.
- A relock-timeout write that fails reverts the in-memory value and shows
  the settings save-failure snackbar.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): clear the lock index before a playlist's last lock leaves the store, retry failed PIN reads, guard backups on the lock store

- A write that removes a playlist's last lock clears the SQLite index
  first and drops the store key afterwards, so an interruption between the
  two can only leave a state the startup reconcile repairs toward locked.
- A PIN hash read failure is distinct from an absent PIN: the session stays
  locked and every PIN-protected step re-reads it first.
- Backup export awaits parental lock initialization and refuses to run
  while the lock store is not readable, since an absent lock field means
  "no opinion" on restore.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): withhold Electron Xtream reads while locks are unknown, persist the switch when settings are unreadable, re-stamp after a recovered read

- ElectronXtreamDataSource serves no categories, content or search hits
  while the lock store withholds everything; its SQLite index may still
  carry a stale stamp.
- setupPin decides whether to persist the switch from the settings value
  before the PIN is stored, since enabled follows hasPin while the switch
  is unknown.
- A lock store recovered by a later read marks its playlists stale so the
  index is re-derived, a persisted entry must carry all three lists, and a
  stale Stalker search page is dropped before touching the withheld-id
  bookkeeping.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): keep unlocked category routes reachable and defer a relock reload that overtakes the initial hydration

- The Xtream category guard no longer runs the item check on category-only
  routes (Number(null) is 0), which prompted for the PIN on every unlocked
  VOD and series category while the lock was active.
- A lock change during the initial Xtream hydration withholds the rows the
  hydration publishes and runs the filtered reload once it has settled,
  on every path that marks the content initialized.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): resolve hidden live categories before relocking playback and reload categories in the deferred hydration path

- The Xtream live layout resolves a playing channel's category through
  the unfiltered rows when the visible list lacks it (search can play a
  hidden category's channel); until that lookup lands the category is
  unknown and a relock stops the channel.
- A relock that overtakes the initial hydration now withholds the
  category publications too and reloads categories with the content.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): step off the M3U channel and Stalker selection before awaiting the Xtream relock reload

The Xtream store stays populated after leaving that portal, so its reload
runs on every apply; a locked M3U channel no longer keeps playing behind a
slow database or provider read.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): gate the workspace on parental lock init, edit only a readable lock store, guard the deferred reload, validate backup lock entries

- The workspace route resolver awaits ParentalLockService.initialize()
  next to the settings load, so no route or catalog activates before the
  PIN and lock store are known.
- Every lock write re-reads a failed store before building its edit, so a
  recovered store is edited rather than overwritten.
- The deferred hydration reload runs under the publish guard of the
  request that deferred it.
- Backup import validates every parental lock entry and rejects a damaged
  list instead of erasing the persisted locks on restore.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): discard stale hidden-category lookups and key withheld Stalker rows by their real identity

- A hidden-category lookup that lands after a later playback (same
  provider id, another playlist) no longer overwrites the newer channel's
  category; resolutions are generation- and playlist-checked.
- Withheld Stalker rows are keyed by id, stream_id, movie_id, series_id
  or the row's cmd/name, so id-less rows no longer collapse onto one key
  and stall paging past locked pages.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): gate the Electron cached category/content reads while locks are unknown

The warm-route hydration reads the cache directly; it now returns nothing
while the lock store withholds everything, like the live reads.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): retire in-flight searches on relock clearing and publish lock revisions after the stamps

- clearSearchResults() advances the search request version, so a search
  issued under the previous lock state cannot republish what a relock
  just cleared.
- A lock write publishes its store revision only once every touched type
  is stamped, so a reload triggered by it cannot read a later type
  through its old stamps.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): retire a resolving Stalker live playback when the session relocks

The embedded player defers selecting the channel until its stream
resolves, so the enforcement service's cleared selection could not retire
the request; it now carries the lock version it was issued under and is
dropped when a relock happened meanwhile.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(settings): one lock entry point per rail plus a right-click Lock/Unlock

- Stalker's dedicated lock button becomes the same "Manage categories"
  (tune) button the Xtream rail has; it opens the lock-only dialog, so
  every portal type shares one entry point and the rail header keeps
  three actions.
- Right-clicking a category (Xtream, Stalker) or an M3U group offers a
  single-row Lock / Unlock through the shared CategoryLockMenuComponent,
  behind the same PIN gate and lock store as the dialog.
- The settings hint explains where locks are set; group lock strings added
  to all locales (ru/de translated).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(settings): serialize lock-store writes and drop a deleted playlist's locks

- Lock-store mutations run through one write queue: each rewrites the
  whole persisted store, so overlapping edits could otherwise snapshot
  the same store and the later write would drop the earlier edit.
- Deleting a playlist removes its locks through the PLAYLIST_DELETE_CLEANUP
  hook; "Remove all playlists" clears the lock store once the deletion
  has succeeded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): apply single-row lock toggles inside the lock store's write queue

The right-click Lock/Unlock (portal categories and M3U groups) built the
new list before entering the queue, so two quick toggles shared one
snapshot and the second dropped the first. Lock writes now accept an edit
of the current list, evaluated inside the queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): retry a failed settings read before any parental-lock settings write

updateSettings writes the whole settings object, which after a failed
startup read is the defaults; enabling the lock or changing the relock
timeout then replaced the user's persisted preferences. The read is
retried first and the write refused while settings stay unreadable. The
settings writes move to parental-lock-settings-writer.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): show the locked-groups row on the M3U rail and roll the relock timeout back to the recovered value

- The M3U groups rail now renders the same "N locked · Enter PIN to show"
  row as the portal category rail, so locked groups no longer vanish
  without an in-context unlock.
- A failed relock-timeout write rolls back to the value read after the
  settings retry, not to the pre-retry default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): retry a failed clear-all of the lock store and keep restored new playlists free of stale locks

A lock-store clear that failed after "Remove all playlists" only logged,
so a later restore reusing a playlist id could inherit the deleted
playlist's locks. The in-memory store now empties at once and the
persisted clear is retried on the next access; a restore that creates a
playlist starts it from empty locks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): count radio playback as lock activity and read the lock store before a restore's stale-id check

- The idle relock no longer interrupts a playing radio station: playing
  <audio> counts as activity, like video.
- A restore retries a failed lock-store read before checking a reused id
  for stale locks, and aborts while the store stays unreadable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): drop withheld Stalker search rows at relock time and keep the M3U unlock row when every group is locked

- A relock during a page-1 Stalker search now filters the rows already on
  screen at once, so old unlocked results are not clickable while the
  replacement page is pending.
- When every M3U group is locked the groups rail still renders, with its
  "N locked · Enter PIN to show" row, instead of the plain empty state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(settings): keep the PIN dialog and the Stalker enforcement step off the initial path

Master (#1712) moved the UI component barrel and the Stalker data layer out
of main.js and tightened the initial budget to 2 MB. The parental-lock
prompt imported the PIN dialog through the ui/components barrel and the
enforcement service injected the Stalker store at startup, which pulled
both back in (2.55 MB, over budget). The PIN dialog now loads through a
local lazy file on the first prompt, and the Stalker step loads only while
a Stalker route is open: initial total 1.65 MB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): restore the lock index when an emptying write fails and publish rollbacks after re-stamping

- Removing a playlist's last lock clears the SQLite index first; if the
  clear or the store write then fails, the index is re-stamped from the
  previous locks at once. Title matching and multi-source discovery query
  the worker directly and trust the index, so the stale flag alone did not
  protect them.
- A rollback publishes its store revision only after every type is
  re-stamped, so a reload cannot read a later type through the attempted
  stamps.
- docs: restore the index rules the earlier surfaces rewrite dropped from
  the contract, now in the Lock store lifetime section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): keep the M3U groups view when every group is locked

With every group locked the filtered channel list is empty, so the
container showed its generic empty state and the groups rail's
"N locked · Enter PIN to show" row never appeared.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): fail closed when the lazy Stalker enforcement step cannot load

A rejected chunk (e.g. a stale PWA page after a deployment) escaped
applyStalker(), so a locked Stalker selection kept playing after a relock
and the Xtream step was skipped. The step now leaves the Stalker route on
a load failure, which clears the selection and stops playback, and the
Xtream step still runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): defer a stale Xtream hydration as soon as the catalog is withheld

On Electron a relock that overtook the initial content hydration waited
for the category reload before the content reload set the deferral flag;
the older unlocked hydration could publish its streams in that window.
withholdCatalog() now sets the flag itself, before anything is awaited.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): restore backup locks after the Xtream merge and snapshot the Stalker lock dialog's categories

- A backup restore now writes the parental locks last, so a failed Xtream
  merge leaves the playlist's previous locks in place instead of the
  backup's possibly smaller set.
- The Stalker lock dialog snapshots the category list before its lazy
  import and opens only if the route is unchanged, so another portal's
  categories can never be saved under this playlist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): fail closed on relock ahead of the apply queue and judge Xtream selections by the lock store

- On relock the synchronous fail-closed steps (M3U channel, Stalker
  selection, the locked Xtream detail, catalog lists, stored search) run
  immediately instead of queueing behind an earlier apply that may still
  wait on a slow or hung read.
- The post-reload Xtream checks decide by the lock store through the
  unfiltered category rows rather than by absence from the reloaded list,
  which also omits merely hidden categories; unreadable rows fail closed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): require the PIN for lock-bearing backup restores and fail closed during index re-stamps

- A backup carrying lock lists replaces the matching playlists' locks,
  possibly with an emptier set; the import now asks for the PIN (after the
  file was chosen) and aborts when it is refused.
- While a write re-stamps the SQLite index the playlist counts as stale,
  so a relock inside that window reloads fail-closed instead of through
  the old stamps. The internal store write now needs only a readable
  store, so a rollback can still land.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): drop parental-lock Xtream reloads once the playlist is switched

A reload issued for playlist A no longer publishes into the shared Xtream
store after the user opened playlist B: the store's reloads guard on the
playlist they read for, and the enforcement apply retires its search
refresh and selection checks on a playlist switch as on a newer lock
version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): re-ask the PIN before a relocked backup merge and keep the PIN cooldown across prompts

A backup merge now asks for the PIN again right before it replaces a
playlist's locks when the app relocked during the import, instead of
relying on the answer given at the start. The wrong-PIN count and the
30-second pause move from the dialog into the lock service, so
dismissing and reopening the prompt no longer resets them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): refuse lock removals that commit after a relock and keep the index stale until the store write lands

Lock edits that take a lock away now commit only while the session is
unlocked, checked inside the write queue at commit time, so an editor
save still in flight (or queued) when the app relocks cannot remove
locks. Adding locks stays allowed. The Xtream category dialog drops its
lock draft after a relock, and a backup restore re-asks the PIN only
when it would remove a lock. Clearing a playlist's last lock keeps its
index stale until the store write has landed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): clear an Xtream detail from a hidden category synchronously on relock

The synchronous relock step now clears a selected Xtream item whose
category the visible category list cannot place (a manually hidden
category opened through search), instead of leaving it usable until the
awaited reloads and lookup finish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): fail closed when the Electron bridge lacks the parental lock worker filter

A new runtime capability requires the lock-state and index-stamping IPC.
When Electron reads Xtream through the SQLite worker without it (a
partial or older preload), the locked session withholds every category
instead of trusting a worker that never learned the lock state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): re-check lock removals at their durable commit points

A lock removal that passed the unlocked check before its write is asked
again right after the store write and, for Xtream, after the index
stamps. A relock in between writes the previous store back or rolls the
stamps back before anything is published. The stale-index bookkeeping,
index stamping and store merge move into helpers to keep the lock store
within the file size limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): retry a failed revert of a refused lock removal and fail closed meanwhile

When writing the previous store back after a relock-refused removal
fails, the lock store now keeps a pending rewrite, is not readable (the
locked session withholds everything) and rewrites the persisted store
from memory on the next access, so a restart cannot load the removal.
A failed "Remove all playlists" clear shares the same retry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): authorize lock removals when issued and close genre-less Stalker details in fail-closed mode

A lock removal is now authorized right before its first write is issued;
a relock that lands after that is ordered after the write, which
completes. This drops the post-write rollback, whose own failure could
leave the persisted store diverged from memory across a restart. The
Stalker search closes a detail without a genre on relock while every
category is withheld.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): restore the previous locks when an Xtream rollback write fails

When an Xtream lock edit's re-stamp fails and the rollback store write
fails too, memory now goes back to the previous locks and a pending
rewrite persists them on the next store access before the index is
re-stamped, so the failed edit cannot take effect through that re-stamp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(stalker): cover page-one rows leaving the screen on relock while the reload hangs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): offer the portal unlock row in fail-closed mode

When the lock store cannot be read every portal category is withheld
but no locked ids are known, so the rail showed no "Enter PIN to show"
row. It now shows the row without a count in that state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): fail closed for direct worker title lookups and capture the Stalker lock dialog context before the PIN

Catalog title matching and multi-source discovery query the SQLite
worker directly; they now return nothing while the parental lock
withholds everything (unreadable store or a bridge without the worker
filter). The Stalker lock dialog captures its playlist, provider and
section before the PIN prompt and re-checks them after it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): retire multi-source alternatives on a lock change and keep reconcile off in-flight stamps

The VOD multi-source host keys its discovery session to the parental
lock version: a lock change drops the discovered sources, retires
discoveries and switches in flight, and rediscovers through the
worker's new lock state. Stale-index entries of a write still stamping
are no longer retried by a concurrent reconcile, which could re-stamp
from a store the write had not committed yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): fail closed on a rejected worker lock sync, tear down Stalker synchronously and capture the Xtream dialog context before the PIN

- A rejected lock-state sync to the SQLite worker makes the locked
  session withhold everything until a later sync succeeds.
- The Stalker enforcement chunk is preloaded when a Stalker route
  opens; a relock runs it synchronously, or leaves the route at once
  while it is not loaded, instead of awaiting the chunk.
- Xtream "Manage categories" captures playlist, provider and section
  before the PIN prompt and re-checks them after it and after the
  dialog import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): keep the relock timeout behind the PIN and bind M3U group lock toggles to their playlist

A locked session can no longer change the relock timeout: the Settings
selector is disabled until the PIN is entered and the service refuses
the change while locked. An M3U right-click lock toggle now captures its
playlist before the PIN prompt and is saved only if that playlist is
still open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): reset a locked M3U channel however it becomes active

The enforcement service now checks the active M3U channel whenever it
changes while locked, so numeric zapping, next/previous and remote
commands, which select from the full channel list, cannot start a
channel of a locked group. Numeric zapping also skips such a channel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): bind the M3U group management result to its playlist

The groups view captures the playlist before the PIN prompt and drops
the management dialog's hidden and locked group lists once another
playlist is open, so they cannot be saved under that playlist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(parental-lock): record the accepted restart case of a failed rollback write

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): build bulk lock drafts only from a readable lock store

The Xtream and M3U management dialogs offer lock toggles, and the
Stalker lock dialog opens, only once the lock store has been read. A
draft built from the empty fail-closed snapshot would otherwise replace
the real locks with nothing on Save if storage recovered in between.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): keep the parental lock switch on the saved state and roll back to the recovered value

The Settings switch snaps back to the saved state when clicked and
follows it once the PIN action succeeds, so a cancelled or refused PIN
no longer leaves it showing the opposite state. A failed switch write is
undone to the value read after the settings retry instead of the
hard-coded inverse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): match noncanonical PWA Xtream category ids against their locks

The PWA data source compared raw provider category ids such as "009"
with locks stored as numbers, so such a category stayed visible while
locked. Both sides are now compared in canonical numeric form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): close the M3U group editor on any relock

The group management dialog lists every group name, locked ones
included, even when it opened without lock toggles (unreadable lock
store). It now closes on any relock, and the groups view re-checks the
lock state before opening it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: 4gray <fourgray@proton.me>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-09-27 16:38:34 +02:00
1 parent f0e51d2806
commit e45cd85a78
203 files changed
+15022 -432

No files matched your search

+1
View File
@@ -9,6 +9,7 @@ export * from './lib/playback-position-runtime-bridge.service';
export * from './lib/playback-position.service';
export * from './lib/playlist-delete-cleanup.token';
export * from './lib/playlist-delete-action.service';
export * from './lib/parental-lock';
export * from './lib/playlist-backup.service';
export * from './lib/playlist-cross-context-lock';
export * from './lib/playlist-refresh.service';
@@ -1,8 +1,12 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { CatalogTitleMatch } from '@iptvnator/shared/interfaces';
import {
CatalogTitleMatchService,
groupTitleMatchesByKey,
pickTitleMatch,
} from './catalog-title-match.service';
import { ParentalLockService } from './parental-lock/parental-lock.service';
describe('catalog title matching', () => {
const match = (
@@ -188,3 +192,31 @@ describe('catalog title matching', () => {
});
});
});
describe('CatalogTitleMatchService parental lock', () => {
afterEach(() => {
delete (window as { electron?: unknown }).electron;
});
it.each([false, true])(
'asks the worker only while the lock does not withhold everything (%s)',
async (withholds) => {
const dbMatchTitles = jest.fn().mockResolvedValue([]);
(window as { electron?: unknown }).electron = { dbMatchTitles };
TestBed.configureTestingModule({
providers: [
{
provide: ParentalLockService,
useValue: { withholdsEverything: signal(withholds) },
},
],
});
await TestBed.inject(CatalogTitleMatchService).matchTitles([
'Dune',
]);
expect(dbMatchTitles).toHaveBeenCalledTimes(withholds ? 0 : 1);
}
);
});
@@ -1,9 +1,10 @@
import { Injectable } from '@angular/core';
import { inject, Injectable } from '@angular/core';
import {
CatalogTitleMatch,
normalizeTitleKeys,
titleYearsCompatible,
} from '@iptvnator/shared/interfaces';
import { ParentalLockService } from './parental-lock/parental-lock.service';
/** What one caller is looking for, in catalog-match terms */
export interface CatalogTitleLookup {
@@ -99,6 +100,8 @@ export function pickTitleMatch(
*/
@Injectable({ providedIn: 'root' })
export class CatalogTitleMatchService {
private readonly parentalLock = inject(ParentalLockService);
get isAvailable(): boolean {
return (
typeof window !== 'undefined' &&
@@ -107,7 +110,14 @@ export class CatalogTitleMatchService {
}
async matchTitles(titles: string[]): Promise<CatalogTitleMatch[]> {
if (!this.isAvailable || titles.length === 0) {
// The worker filters locked rows by its own lock state and index;
// while the lock withholds everything (store unreadable, or a
// bridge without the worker filter) neither can be trusted.
if (
!this.isAvailable ||
titles.length === 0 ||
this.parentalLock.withholdsEverything()
) {
return [];
}
@@ -24,6 +24,8 @@ export interface XCategoryFromDb {
type: 'movies' | 'live' | 'series';
xtream_id: number;
hidden: boolean;
/** Parental lock index; see ParentalLockService. */
locked: boolean;
}
export interface XtreamContent {
@@ -429,16 +431,43 @@ export class DatabaseService {
playlistId: string,
categories: XtreamCategory[],
type: 'live' | 'movies' | 'series',
hiddenCategoryXtreamIds?: number[]
hiddenCategoryXtreamIds?: number[],
lockedCategoryXtreamIds?: number[]
): Promise<void> {
await window.electron.dbSaveCategories(
playlistId,
categories,
type,
hiddenCategoryXtreamIds
hiddenCategoryXtreamIds,
lockedCategoryXtreamIds
);
}
/**
* Re-stamps the parental lock index of one playlist/type from provider
* category ids. False when the bridge is missing or the write failed.
*/
async setCategoryLocks(
playlistId: string,
type: 'live' | 'movies' | 'series',
lockedXtreamIds: number[]
): Promise<boolean> {
if (typeof window.electron?.dbSetCategoryLocks !== 'function') {
return false;
}
try {
await window.electron.dbSetCategoryLocks(
playlistId,
type,
lockedXtreamIds
);
return true;
} catch (error) {
console.error('Error updating category locks:', error);
return false;
}
}
/**
* Get all categories for a playlist (including hidden, for management dialog)
*/
@@ -539,12 +568,20 @@ export class DatabaseService {
}
async getAppState(key: string): Promise<string | null> {
return (await this.readAppState(key))?.value ?? null;
}
/**
* Like {@link getAppState}, but a failed read (no bridge, rejected IPC)
* comes back as `null` instead of looking like an absent key.
*/
async readAppState(key: string): Promise<{ value: string | null } | null> {
if (typeof window.electron?.dbGetAppState !== 'function') {
return null;
}
try {
return await window.electron.dbGetAppState(key);
return { value: await window.electron.dbGetAppState(key) };
} catch (error) {
console.error('Error getting app state:', error);
return null;
@@ -0,0 +1,6 @@
export * from './parental-lock-idle-timer';
export * from './parental-lock-prompt.token';
export * from './parental-lock-lock-store.service';
export * from './parental-lock-playlist-cleanup';
export * from './parental-lock-storage';
export * from './parental-lock.service';
@@ -0,0 +1,94 @@
import { signal } from '@angular/core';
/**
* Electron bridge calls of the parental lock. Both are no-ops in the PWA,
* where there is no main process to inform.
*/
/**
* Tells the SQLite worker (through main) whether locked rows are withheld.
* Resolves false when the IPC rejected: the worker keeps its previous
* state, so the caller must not trust worker reads while locked.
*/
export async function syncParentalLockStateToMainProcess(
active: boolean
): Promise<boolean> {
const bridge = window.electron;
if (typeof bridge?.setParentalLockState !== 'function') {
return true;
}
try {
await bridge.setParentalLockState(active);
return true;
} catch (error) {
console.error('Failed to sync the parental lock state.', error);
return false;
}
}
/**
* Mirrors the feature switch into electron-conf so a reloaded renderer and a
* restarted worker start locked while the feature is on. Resolves false
* when the main process could not persist it — the caller must then not
* report the switch as changed, or a reload would start from the old
* mirror. True in the PWA, which has no mirror.
*/
export async function mirrorParentalLockEnabledSetting(
enabled: boolean
): Promise<boolean> {
const bridge = window.electron;
if (typeof bridge?.updateSettings !== 'function') {
return true;
}
try {
await bridge.updateSettings({ parentalLockEnabled: enabled });
return true;
} catch (error) {
console.error('Failed to mirror the parental lock switch.', error);
return false;
}
}
/**
* Electron reads Xtream through the SQLite worker, but the bridge lacks the
* lock-state or index IPC (a partial or older preload): the worker cannot
* withhold locked rows, so a locked session withholds everything.
*/
export function isParentalLockWorkerFilterMissing(runtime: {
supportsXtreamSqliteDataSource: boolean;
supportsParentalLockSqliteFilter: boolean;
}): boolean {
const missing =
runtime.supportsXtreamSqliteDataSource &&
!runtime.supportsParentalLockSqliteFilter;
if (missing) {
console.error(
'The parental lock bridge is incomplete; locked sessions withhold every category.'
);
}
return missing;
}
/**
* Whether the SQLite worker learned the current lock state. A rejected
* sync leaves the worker in its previous state, so a locked session must
* not trust worker reads until a later sync succeeds.
*/
export class ParentalLockWorkerSync {
readonly failed = signal(false);
/** Bumps whenever `failed` changes; part of the lock version. */
readonly changes = signal(0);
/**
* Syncs `active`. A sync superseded by a newer transition (`current()`
* no longer equals `active`) changes nothing.
*/
async sync(active: boolean, current: () => boolean): Promise<void> {
const failed = !(await syncParentalLockStateToMainProcess(active));
if (current() !== active || this.failed() === failed) {
return;
}
this.failed.set(failed);
this.changes.update((value) => value + 1);
}
}
@@ -0,0 +1,144 @@
import {
PARENTAL_LOCK_BUSY_RECHECK_MS,
ParentalLockIdleTimer,
} from './parental-lock-idle-timer';
interface FakeScheduler {
now: number;
timers: Map<number, { at: number; callback: () => void }>;
advance(ms: number): void;
}
function createScheduler(): FakeScheduler {
let nextHandle = 1;
const scheduler: FakeScheduler = {
now: 0,
timers: new Map(),
advance(ms: number) {
const target = scheduler.now + ms;
while (true) {
const due = [...scheduler.timers.entries()]
.filter(([, timer]) => timer.at <= target)
.sort((a, b) => a[1].at - b[1].at)[0];
if (!due) {
break;
}
scheduler.timers.delete(due[0]);
scheduler.now = due[1].at;
due[1].callback();
}
scheduler.now = target;
},
};
return Object.assign(scheduler, {
setTimeout: (callback: () => void, delay: number) => {
const handle = nextHandle++;
scheduler.timers.set(handle, {
at: scheduler.now + delay,
callback,
});
return handle;
},
clearTimeout: (handle: number) => {
scheduler.timers.delete(handle);
},
});
}
function createTarget() {
const listeners = new Map<
string,
Set<EventListenerOrEventListenerObject>
>();
return {
listeners,
addEventListener: jest.fn((type: string, listener) => {
listeners.set(
type,
(listeners.get(type) ?? new Set()).add(listener)
);
}),
removeEventListener: jest.fn((type: string, listener) => {
listeners.get(type)?.delete(listener);
}),
fire(type: string) {
for (const listener of listeners.get(type) ?? []) {
(listener as EventListener)(new Event(type));
}
},
};
}
function createTimer(options: { busy?: () => boolean } = {}) {
const scheduler = createScheduler() as FakeScheduler & {
setTimeout: (callback: () => void, delay: number) => number;
clearTimeout: (handle: number) => void;
};
const target = createTarget();
const onExpire = jest.fn();
const timer = new ParentalLockIdleTimer({
onExpire,
isBusy: options.busy,
now: () => scheduler.now,
setTimeout: scheduler.setTimeout,
clearTimeout: scheduler.clearTimeout,
target: target as unknown as Document,
});
return { timer, scheduler, target, onExpire };
}
describe('ParentalLockIdleTimer', () => {
it('expires after the configured minutes without interaction', () => {
const { timer, scheduler, onExpire } = createTimer();
timer.arm(15);
scheduler.advance(14 * 60_000);
expect(onExpire).not.toHaveBeenCalled();
scheduler.advance(60_000);
expect(onExpire).toHaveBeenCalledTimes(1);
expect(timer.armed).toBe(false);
});
it('restarts the countdown on user interaction', () => {
const { timer, scheduler, target, onExpire } = createTimer();
timer.arm(5);
scheduler.advance(4 * 60_000);
target.fire('keydown');
scheduler.advance(4 * 60_000);
expect(onExpire).not.toHaveBeenCalled();
scheduler.advance(60_000);
expect(onExpire).toHaveBeenCalledTimes(1);
});
it('defers expiry while playback is busy and fires once it stops', () => {
let busy = true;
const { timer, scheduler, onExpire } = createTimer({
busy: () => busy,
});
timer.arm(5);
scheduler.advance(5 * 60_000);
expect(onExpire).not.toHaveBeenCalled();
scheduler.advance(PARENTAL_LOCK_BUSY_RECHECK_MS);
expect(onExpire).not.toHaveBeenCalled();
busy = false;
scheduler.advance(PARENTAL_LOCK_BUSY_RECHECK_MS);
expect(onExpire).toHaveBeenCalledTimes(1);
});
it('never fires with 0 minutes and stops listening once disarmed', () => {
const { timer, scheduler, target, onExpire } = createTimer();
timer.arm(0);
expect(timer.armed).toBe(false);
expect(target.addEventListener).not.toHaveBeenCalled();
timer.arm(1);
expect(target.addEventListener).toHaveBeenCalled();
timer.disarm();
scheduler.advance(10 * 60_000);
expect(onExpire).not.toHaveBeenCalled();
expect(target.removeEventListener).toHaveBeenCalled();
});
});
@@ -0,0 +1,148 @@
/**
* Re-lock timer for the parental lock.
*
* Counts minutes since the last user interaction while unlocked. Playback is
* treated as interaction through `isBusy`: a film that runs for two hours
* without a click must not lock itself half way, so an expiry that lands on
* active playback is deferred and re-checked instead of fired.
*
* Listener shape mirrors `ControlsSurface` (document-level, capture phase,
* passive) so it costs nothing per event beyond a timestamp write.
*/
const ACTIVITY_EVENTS: readonly string[] = [
'pointerdown',
'pointermove',
'keydown',
'wheel',
'touchstart',
];
/** How often a deferred expiry re-checks whether playback has stopped. */
export const PARENTAL_LOCK_BUSY_RECHECK_MS = 60_000;
export interface ParentalLockIdleTimerOptions {
onExpire: () => void;
/** True while something (playback) should keep the app unlocked. */
isBusy?: () => boolean;
/** Injectable clock and scheduler for tests. */
now?: () => number;
setTimeout?: (callback: () => void, delayMs: number) => number;
clearTimeout?: (handle: number) => void;
target?: Pick<Document, 'addEventListener' | 'removeEventListener'>;
}
export class ParentalLockIdleTimer {
private readonly onExpire: () => void;
private readonly isBusy: () => boolean;
private readonly now: () => number;
private readonly schedule: (
callback: () => void,
delayMs: number
) => number;
private readonly cancel: (handle: number) => void;
private readonly target: Pick<
Document,
'addEventListener' | 'removeEventListener'
> | null;
private timeoutMs = 0;
private lastActivityAt = 0;
private handle: number | null = null;
private listening = false;
private readonly onActivity = () => {
this.lastActivityAt = this.now();
};
constructor(options: ParentalLockIdleTimerOptions) {
this.onExpire = options.onExpire;
this.isBusy = options.isBusy ?? (() => false);
this.now = options.now ?? (() => Date.now());
this.schedule =
options.setTimeout ??
((callback, delayMs) =>
window.setTimeout(callback, delayMs) as unknown as number);
this.cancel =
options.clearTimeout ?? ((handle) => window.clearTimeout(handle));
this.target =
options.target ??
(typeof document === 'undefined' ? null : document);
}
/**
* Starts (or restarts) the countdown. `minutes === 0` means "never by
* idle" — only an explicit lock or a restart locks again.
*/
arm(minutes: number): void {
this.disarm();
if (!Number.isFinite(minutes) || minutes <= 0) {
return;
}
this.timeoutMs = minutes * 60_000;
this.lastActivityAt = this.now();
this.listen();
this.scheduleCheck(this.timeoutMs);
}
disarm(): void {
if (this.handle !== null) {
this.cancel(this.handle);
this.handle = null;
}
this.unlisten();
}
get armed(): boolean {
return this.handle !== null;
}
private scheduleCheck(delayMs: number): void {
this.handle = this.schedule(
() => {
this.handle = null;
this.check();
},
Math.max(delayMs, 1_000)
);
}
private check(): void {
const idleFor = this.now() - this.lastActivityAt;
if (idleFor < this.timeoutMs) {
this.scheduleCheck(this.timeoutMs - idleFor);
return;
}
if (this.isBusy()) {
// Playback counts as presence; look again once it may have ended.
this.scheduleCheck(PARENTAL_LOCK_BUSY_RECHECK_MS);
return;
}
this.unlisten();
this.onExpire();
}
private listen(): void {
if (this.listening || !this.target) {
return;
}
this.listening = true;
for (const type of ACTIVITY_EVENTS) {
this.target.addEventListener(type, this.onActivity, {
capture: true,
passive: true,
});
}
}
private unlisten(): void {
if (!this.listening || !this.target) {
return;
}
this.listening = false;
for (const type of ACTIVITY_EVENTS) {
this.target.removeEventListener(type, this.onActivity, {
capture: true,
});
}
}
}
@@ -0,0 +1,530 @@
import { TestBed } from '@angular/core/testing';
import { ParentalLockStore } from '@iptvnator/shared/interfaces';
import { DatabaseService } from '../database-electron.service';
import { RuntimeCapabilitiesService } from '../runtime-capabilities.service';
import { ParentalLockLockStore } from './parental-lock-lock-store.service';
import { ParentalLockStorageService } from './parental-lock-storage';
describe('ParentalLockLockStore', () => {
const stored: ParentalLockStore = {
'pl-1': {
xtream: [{ categoryType: 'live', xtreamId: 7 }],
stalker: [],
m3u: [],
},
};
let storage: { readLocks: jest.Mock; writeLocks: jest.Mock };
let setCategoryLocks: jest.Mock;
let store: ParentalLockLockStore;
beforeEach(() => {
storage = {
readLocks: jest.fn(async () => JSON.parse(JSON.stringify(stored))),
writeLocks: jest.fn(async () => true),
};
setCategoryLocks = jest.fn(async () => true);
TestBed.configureTestingModule({
providers: [
ParentalLockLockStore,
{ provide: ParentalLockStorageService, useValue: storage },
{
provide: RuntimeCapabilitiesService,
useValue: { supportsXtreamSqliteDataSource: true },
},
{ provide: DatabaseService, useValue: { setCategoryLocks } },
],
});
store = TestBed.inject(ParentalLockLockStore);
});
it('is not readable until the initial read has settled', async () => {
let resolveRead: (locks: ParentalLockStore) => void = () => undefined;
storage.readLocks.mockReturnValue(
new Promise<ParentalLockStore>((resolve) => (resolveRead = resolve))
);
const load = store.load();
expect(store.readable()).toBe(false);
resolveRead({});
await load;
expect(store.readable()).toBe(true);
});
it('is not readable until the startup re-stamp has completed', async () => {
let resolveStamp: (ok: boolean) => void = () => undefined;
setCategoryLocks.mockImplementation(
() => new Promise<boolean>((resolve) => (resolveStamp = resolve))
);
const load = store.load();
await Promise.resolve();
await Promise.resolve();
expect(setCategoryLocks).toHaveBeenCalled();
expect(store.readable()).toBe(false);
setCategoryLocks.mockResolvedValue(true);
resolveStamp(true);
await load;
expect(store.readable()).toBe(true);
});
it('stays not readable while the startup re-stamp keeps failing', async () => {
setCategoryLocks.mockResolvedValue(false);
await store.load();
expect(store.readable()).toBe(false);
await expect(store.ensureReadable()).resolves.toBe(false);
setCategoryLocks.mockResolvedValue(true);
await expect(store.ensureReadable()).resolves.toBe(true);
expect(store.readable()).toBe(true);
});
it('builds an edit on the recovered store, never on the empty fail-closed one', async () => {
storage.readLocks.mockResolvedValueOnce(null);
await store.load();
await expect(store.setM3uLocks('pl-1', ['Adult'])).resolves.toBe(true);
expect(storage.writeLocks).toHaveBeenLastCalledWith({
'pl-1': {
xtream: [{ categoryType: 'live', xtreamId: 7 }],
stalker: [],
m3u: ['Adult'],
},
});
});
it('re-derives the index from a store recovered after a failed read', async () => {
storage.readLocks.mockResolvedValueOnce(null);
await store.load();
expect(store.readable()).toBe(false);
expect(setCategoryLocks).not.toHaveBeenCalled();
await expect(store.ensureReadable()).resolves.toBe(true);
expect(setCategoryLocks).toHaveBeenCalledWith('pl-1', 'live', [7]);
expect(store.readable()).toBe(true);
});
it('re-derives the SQLite index from the store on load', async () => {
await store.load();
// ensureReadable awaits the reconcile that load() started.
await store.ensureReadable();
expect(setCategoryLocks).toHaveBeenCalledWith('pl-1', 'live', [7]);
expect(setCategoryLocks).toHaveBeenCalledWith('pl-1', 'movies', []);
expect(setCategoryLocks).toHaveBeenCalledWith('pl-1', 'series', []);
});
it('clears the index before the last lock leaves the store', async () => {
await store.load();
await store.ensureReadable();
setCategoryLocks.mockClear();
storage.writeLocks.mockClear();
const order: string[] = [];
setCategoryLocks.mockImplementation(async () => {
order.push('stamp');
return true;
});
storage.writeLocks.mockImplementation(async () => {
order.push('persist');
return true;
});
await expect(store.setXtreamLocks('pl-1', 'live', [])).resolves.toBe(
true
);
expect(order).toEqual(['stamp', 'persist']);
expect(setCategoryLocks).toHaveBeenCalledWith('pl-1', 'live', []);
expect(storage.writeLocks).toHaveBeenLastCalledWith({});
});
it('restores the cleared index when saving the emptied store fails', async () => {
await store.load();
await store.ensureReadable();
setCategoryLocks.mockClear();
storage.writeLocks.mockResolvedValueOnce(false);
await expect(store.setXtreamLocks('pl-1', 'live', [])).resolves.toBe(
false
);
// Cleared first, then put back from the previous locks.
expect(setCategoryLocks.mock.calls).toEqual([
['pl-1', 'live', []],
['pl-1', 'live', [7]],
]);
expect(store.readable()).toBe(true);
});
it('publishes a rollback only after every type is re-stamped', async () => {
await store.load();
await store.ensureReadable();
const before = store.revision();
setCategoryLocks.mockClear();
const revisionsAtStamp: number[] = [];
let call = 0;
setCategoryLocks.mockImplementation(async () => {
revisionsAtStamp.push(store.revision());
call += 1;
// live ok, movies fails, then the rollback re-stamps succeed
return call !== 2;
});
await expect(
store.replacePlaylistLocks('pl-1', {
xtream: [{ categoryType: 'movies', xtreamId: 3 }],
stalker: [],
m3u: [],
})
).resolves.toBe(false);
expect(revisionsAtStamp.every((revision) => revision === before)).toBe(
true
);
expect(store.revision()).toBe(before + 1);
});
it('does not drop the key when clearing the index fails', async () => {
await store.load();
await store.ensureReadable();
storage.writeLocks.mockClear();
setCategoryLocks.mockResolvedValue(false);
await expect(store.setXtreamLocks('pl-1', 'live', [])).resolves.toBe(
false
);
expect(storage.writeLocks).not.toHaveBeenCalled();
expect(store.lockedXtreamIds('pl-1', 'live')).toEqual([7]);
});
it('publishes the revision only after every type is stamped', async () => {
await store.load();
await store.ensureReadable();
const before = store.revision();
let resolveStamp: (ok: boolean) => void = () => undefined;
setCategoryLocks.mockImplementation(
() => new Promise<boolean>((resolve) => (resolveStamp = resolve))
);
const writing = store.replacePlaylistLocks('pl-1', {
xtream: [{ categoryType: 'movies', xtreamId: 3 }],
stalker: [],
m3u: [],
});
for (
let i = 0;
i < 50 && storage.writeLocks.mock.calls.length === 0;
i += 1
) {
await Promise.resolve();
}
expect(storage.writeLocks).toHaveBeenCalled();
expect(store.revision()).toBe(before);
setCategoryLocks.mockResolvedValue(true);
resolveStamp(true);
await expect(writing).resolves.toBe(true);
expect(store.revision()).toBe(before + 1);
});
it('serializes overlapping edits so neither overwrites the other', async () => {
await store.load();
await store.ensureReadable();
let releaseFirst: (ok: boolean) => void = () => undefined;
storage.writeLocks.mockImplementationOnce(
() => new Promise<boolean>((resolve) => (releaseFirst = resolve))
);
const first = store.setM3uLocks('pl-1', ['Adult']);
const second = store.setStalkerLocks('pl-1', 'itv', ['9']);
for (let i = 0; i < 20; i += 1) {
await Promise.resolve();
}
expect(storage.writeLocks).toHaveBeenCalledTimes(1);
releaseFirst(true);
await expect(first).resolves.toBe(true);
await expect(second).resolves.toBe(true);
expect(storage.writeLocks).toHaveBeenLastCalledWith({
'pl-1': {
xtream: [{ categoryType: 'live', xtreamId: 7 }],
stalker: [{ categoryType: 'itv', categoryId: '9' }],
m3u: ['Adult'],
},
});
});
it("applies back-to-back single-row edits to each other's result", async () => {
await store.load();
await store.ensureReadable();
let releaseFirst: (ok: boolean) => void = () => undefined;
storage.writeLocks.mockImplementationOnce(
() => new Promise<boolean>((resolve) => (releaseFirst = resolve))
);
const first = store.setStalkerLocks('pl-1', 'itv', (current) => [
...current,
'1',
]);
const second = store.setStalkerLocks('pl-1', 'itv', (current) => [
...current,
'2',
]);
for (
let i = 0;
i < 50 && storage.writeLocks.mock.calls.length === 0;
i += 1
) {
await Promise.resolve();
}
releaseFirst(true);
await Promise.all([first, second]);
expect(store.lockedStalkerIds('pl-1', 'itv')).toEqual(['1', '2']);
});
it('drops a deleted playlist from the store and empties it on clearAll', async () => {
await store.load();
await store.ensureReadable();
setCategoryLocks.mockClear();
await expect(store.removePlaylist('missing')).resolves.toBe(true);
await expect(store.removePlaylist('pl-1')).resolves.toBe(true);
expect(storage.writeLocks).toHaveBeenLastCalledWith({});
expect(setCategoryLocks).not.toHaveBeenCalled();
expect(store.lockedXtreamIds('pl-1', 'live')).toEqual([]);
await expect(store.clearAll()).resolves.toBe(true);
expect(storage.writeLocks).toHaveBeenLastCalledWith({});
});
it('empties the store now and retries a failed persisted clear', async () => {
await store.load();
await store.ensureReadable();
storage.writeLocks.mockResolvedValueOnce(false);
await expect(store.clearAll()).resolves.toBe(false);
expect(store.lockedXtreamIds('pl-1', 'live')).toEqual([]);
storage.writeLocks.mockClear();
await expect(store.ensureReadable()).resolves.toBe(true);
expect(storage.writeLocks).toHaveBeenCalledWith({});
});
it('is not readable while a write is re-stamping the index', async () => {
await store.load();
await store.ensureReadable();
const readableAtStamp: boolean[] = [];
setCategoryLocks.mockImplementation(async () => {
readableAtStamp.push(store.readable());
return true;
});
await expect(
store.setXtreamLocks('pl-1', 'live', [7, 9])
).resolves.toBe(true);
await expect(store.setXtreamLocks('pl-1', 'live', [])).resolves.toBe(
true
);
expect(readableAtStamp.length).toBeGreaterThan(0);
expect(readableAtStamp.every((readable) => !readable)).toBe(true);
expect(store.readable()).toBe(true);
});
it('rolls the store back when the index re-stamp fails', async () => {
await store.load();
setCategoryLocks.mockResolvedValue(false);
await expect(
store.setXtreamLocks('pl-1', 'live', [7, 9])
).resolves.toBe(false);
expect(store.lockedXtreamIds('pl-1', 'live')).toEqual([7]);
expect(storage.writeLocks).toHaveBeenLastCalledWith(
expect.objectContaining({
'pl-1': expect.objectContaining({
xtream: [{ categoryType: 'live', xtreamId: 7 }],
}),
})
);
});
it('re-stamps every touched type from the restored store after a partial multi-type failure', async () => {
await store.load();
await store.ensureReadable();
setCategoryLocks.mockClear();
// live commits, movies fails: the index now carries the NEW live
// locks while the store is rolled back to the old ones.
setCategoryLocks
.mockResolvedValueOnce(true)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true)
.mockResolvedValue(true);
await expect(
store.replacePlaylistLocks('pl-1', {
xtream: [{ categoryType: 'movies', xtreamId: 3 }],
stalker: [],
m3u: [],
})
).resolves.toBe(false);
expect(store.lockedXtreamIds('pl-1', 'live')).toEqual([7]);
// Rollback re-stamps all three types from the restored store.
expect(setCategoryLocks.mock.calls.slice(3)).toEqual([
['pl-1', 'live', [7]],
['pl-1', 'movies', []],
['pl-1', 'series', []],
]);
expect(store.readable()).toBe(true);
});
it('restores the previous locks on the next access when even the rollback write failed', async () => {
await store.load();
await store.ensureReadable();
jest.spyOn(console, 'error').mockImplementation(() => undefined);
setCategoryLocks.mockClear();
setCategoryLocks.mockResolvedValueOnce(false);
storage.writeLocks
.mockResolvedValueOnce(true) // the new locks
.mockResolvedValueOnce(false); // the rollback
await expect(
store.setXtreamLocks('pl-1', 'live', [7, 9])
).resolves.toBe(false);
// The failed edit does not take effect: memory holds the previous
// locks and the store stays fail-closed until they are persisted.
expect(store.lockedXtreamIds('pl-1', 'live')).toEqual([7]);
expect(store.readable()).toBe(false);
await expect(store.ensureReadable()).resolves.toBe(true);
expect(storage.writeLocks).toHaveBeenLastCalledWith(
expect.objectContaining({
'pl-1': expect.objectContaining({
xtream: [{ categoryType: 'live', xtreamId: 7 }],
}),
})
);
// Re-stamped from the restored locks, not the failed edit.
expect(setCategoryLocks).toHaveBeenCalledWith('pl-1', 'live', [7]);
expect(store.readable()).toBe(true);
});
it('stays not readable until the store write of a cleared last lock lands', async () => {
await store.load();
await store.ensureReadable();
let finishWrite: (ok: boolean) => void = () => undefined;
storage.writeLocks.mockImplementationOnce(
() => new Promise<boolean>((resolve) => (finishWrite = resolve))
);
const revision = store.revision();
const clearing = store.setXtreamLocks('pl-1', 'live', []);
await waitFor(() => storage.writeLocks.mock.calls.length > 0);
// The index is already cleared; the store still holds the lock.
expect(setCategoryLocks).toHaveBeenCalledWith('pl-1', 'live', []);
expect(store.readable()).toBe(false);
expect(store.revision()).toBe(revision);
finishWrite(false);
await expect(clearing).resolves.toBe(false);
// Restored from the store, which kept the lock.
expect(setCategoryLocks).toHaveBeenLastCalledWith('pl-1', 'live', [7]);
expect(store.readable()).toBe(true);
expect(store.lockedXtreamIds('pl-1', 'live')).toEqual([7]);
});
it('refuses, at commit time, an edit that removes a lock while removal is gated', async () => {
await store.load();
await store.ensureReadable();
let unlocked = true;
store.setRemovalGate(() => unlocked);
jest.spyOn(console, 'warn').mockImplementation(() => undefined);
// An earlier write holds the queue while the app relocks: the edit
// queued behind it was built unlocked but commits locked.
let finishFirst: (ok: boolean) => void = () => undefined;
storage.writeLocks.mockImplementationOnce(
() => new Promise<boolean>((resolve) => (finishFirst = resolve))
);
const adding = store.setM3uLocks('pl-1', ['Adults']);
const removing = store.setXtreamLocks('pl-1', 'live', []);
await waitFor(() => storage.writeLocks.mock.calls.length > 0);
unlocked = false;
finishFirst(true);
await expect(adding).resolves.toBe(true);
await expect(removing).resolves.toBe(false);
expect(store.lockedXtreamIds('pl-1', 'live')).toEqual([7]);
// Adding stays allowed while locked; removing again once unlocked.
await expect(
store.setXtreamLocks('pl-1', 'live', [7, 9])
).resolves.toBe(true);
await expect(
store.replacePlaylistLocks('pl-1', {
xtream: [],
stalker: [],
m3u: [],
})
).resolves.toBe(false);
unlocked = true;
await expect(store.setM3uLocks('pl-1', [])).resolves.toBe(true);
expect(store.lockedGroupTitles('pl-1')).toEqual([]);
});
it('completes a removal whose write was issued before the app relocked', async () => {
// The parent authorized the removal; a relock that lands once its
// write is issued is ordered after it (no post-write rollback, which
// could itself fail and leave the persisted store diverged).
storage.readLocks.mockResolvedValue({
'pl-1': { xtream: [], stalker: [], m3u: ['Adults'] },
});
await store.load();
await store.ensureReadable();
let unlocked = true;
store.setRemovalGate(() => unlocked);
storage.writeLocks.mockImplementationOnce(async () => {
unlocked = false;
return true;
});
await expect(store.setM3uLocks('pl-1', [])).resolves.toBe(true);
expect(store.lockedGroupTitles('pl-1')).toEqual([]);
expect(storage.writeLocks).toHaveBeenCalledTimes(1);
expect(store.readable()).toBe(true);
});
it('does not re-stamp an in-flight write from the uncommitted store', async () => {
await store.load();
await store.ensureReadable();
setCategoryLocks.mockClear();
let finishWrite: (ok: boolean) => void = () => undefined;
storage.writeLocks.mockImplementationOnce(
() => new Promise<boolean>((resolve) => (finishWrite = resolve))
);
const clearing = store.setXtreamLocks('pl-1', 'live', []);
await waitFor(() => storage.writeLocks.mock.calls.length > 0);
// A PIN prompt or backup reaches ensureReadable() beside the write.
await expect(store.ensureReadable()).resolves.toBe(false);
finishWrite(true);
await expect(clearing).resolves.toBe(true);
// Only the write's own clear: memory still held [7] while it was in
// flight, and a reconcile stamping that would have re-locked rows
// the store no longer lists.
expect(setCategoryLocks.mock.calls).toEqual([['pl-1', 'live', []]]);
expect(store.readable()).toBe(true);
});
});
async function waitFor(condition: () => boolean): Promise<void> {
for (let i = 0; i < 50 && !condition(); i++) {
await Promise.resolve();
}
expect(condition()).toBe(true);
}
@@ -0,0 +1,546 @@
import { computed, inject, Injectable, signal } from '@angular/core';
import {
createEmptyParentalLockPlaylistLocks,
isParentalLockPlaylistLocksEmpty,
lockedStalkerCategoryIds,
lockedXtreamCategoryIds,
normalizeParentalLockPlaylistLocks,
ParentalLockPlaylistLocks,
ParentalLockStalkerCategoryType,
ParentalLockStore,
ParentalLockXtreamCategoryType,
} from '@iptvnator/shared/interfaces';
import { DatabaseService } from '../database-electron.service';
import { RuntimeCapabilitiesService } from '../runtime-capabilities.service';
import { ParentalLockStaleIndex } from './parental-lock-stale-index';
import { ParentalLockStorageService } from './parental-lock-storage';
import {
lockRemovalGate,
stampXtreamIndex,
withM3uLocks,
withPlaylistLocksInStore,
withStalkerLocks,
withXtreamLocks,
} from './parental-lock-store.util';
/**
* A full replacement list, or an edit of the CURRENT list. The edit form is
* evaluated inside the write queue, so single-row toggles issued back to
* back each see the previous toggle's result instead of one shared snapshot.
*/
export type LockListEdit<T> = readonly T[] | ((current: readonly T[]) => T[]);
function applyLockListEdit<T>(
edit: LockListEdit<T>,
current: readonly T[]
): T[] {
return typeof edit === 'function' ? edit(current) : [...edit];
}
const XTREAM_CATEGORY_TYPES: readonly ParentalLockXtreamCategoryType[] = [
'live',
'movies',
'series',
];
/**
* The lock store: WHICH categories are locked, per playlist, persisted
* through `ParentalLockStorageService`. Knows nothing about the PIN or the
* session state — `ParentalLockService` composes it and adds `active`.
*
* A store that could not be READ is a distinct state (`unreadable`): it is
* not "nothing is locked", and no write may be built on the empty in-memory
* store while it lasts, or the persisted locks would be wiped.
*/
@Injectable({ providedIn: 'root' })
export class ParentalLockLockStore {
private readonly storage = inject(ParentalLockStorageService);
private readonly runtime = inject(RuntimeCapabilitiesService);
private readonly databaseService = inject(DatabaseService);
private readonly locks = signal<ParentalLockStore>({});
private readonly revisionState = signal(0);
private readonly loadedState = signal(false);
private loading: Promise<void> | null = null;
/**
* Whether an edit may REMOVE a lock right now; set by
* `ParentalLockService` to "the session is not locked". Asked inside
* the write queue right before the edit's first write: an editor opened
* while unlocked may still be saving (or queued) when the app relocks.
* A relock that lands once the write is issued is ordered after it: the
* parent authorized that removal, so it completes.
*/
private mayRemoveLocks: () => boolean = () => true;
/**
* Mutations run one at a time: each rewrites the WHOLE persisted store
* from the in-memory copy, so two overlapping edits would snapshot the
* same store and the later write would silently drop the earlier edit.
*/
private writeQueue: Promise<unknown> = Promise.resolve();
/**
* The persisted store differs from the in-memory one and must be
* rewritten from it: "Remove all playlists" could not clear it, or a
* failed edit could not be rolled back. Retried on the next store
* access (before the index is re-stamped from memory); the store is not
* `readable` meanwhile.
*/
private readonly pendingRewrite = signal(false);
private readonly staleIndex = new ParentalLockStaleIndex();
/** The persisted store could not be read; see `ensureReadable()`. */
readonly unreadable = signal(false);
/**
* The store has been read, is trustworthy, and (on Electron) the SQLite
* index agrees with it. False while the initial read is still in flight
* — the settings can report the feature as on before the locks are
* known, and an empty in-memory store must not read as "nothing is
* locked" in that window — and while a re-stamp is outstanding, since
* Electron reads filter by the index alone.
*/
readonly readable = computed(
() =>
this.loadedState() &&
!this.unreadable() &&
!this.pendingRewrite() &&
this.staleIndex.isEmpty()
);
/** Bumps whenever the lock set changes; consumers re-query. */
readonly revision = this.revisionState.asReadonly();
readonly isEmpty = computed(() => Object.keys(this.locks()).length === 0);
/**
* Reads the persisted store once. On Electron the `categories.locked`
* index is then re-derived from it for every playlist that has locks:
* the store is authoritative, and a re-stamp that failed in an earlier
* session (or a database restored beside a newer store) must not leave
* the index behind indefinitely.
*/
load(): Promise<void> {
if (!this.loading) {
this.loading = (async () => {
const locks = await this.storage.readLocks();
if (locks === null) {
console.error('The parental lock store could not be read.');
this.unreadable.set(true);
} else {
this.locks.set(locks);
for (const playlistId of Object.keys(locks)) {
this.staleIndex.mark(playlistId);
}
// Awaited: catalog reads issued before the index agrees
// with the store would serve rows stamped unlocked, and
// nothing would reload them afterwards.
await this.reconcileXtreamIndex();
}
this.loadedState.set(true);
this.revisionState.update((value) => value + 1);
})();
}
return this.loading;
}
/**
* Re-reads a store that failed to read earlier. False while it still
* cannot be read.
*/
async ensureReadable(): Promise<boolean> {
await this.load();
if (this.pendingRewrite() && !(await this.rewritePersistedStore())) {
return false;
}
if (this.unreadable()) {
const locks = await this.storage.readLocks();
if (locks === null) {
return false;
}
this.locks.set(locks);
this.unreadable.set(false);
// The index may carry stamps from a write that failed before
// the read did; re-derive it from the recovered store as load()
// does.
for (const playlistId of Object.keys(locks)) {
this.staleIndex.mark(playlistId);
}
this.revisionState.update((value) => value + 1);
}
await this.reconcileXtreamIndex();
return this.readable();
}
/** Re-stamps every playlist whose index may lag behind the store. */
private async reconcileXtreamIndex(): Promise<void> {
if (!this.runtime.supportsXtreamSqliteDataSource) {
this.staleIndex.clear();
return;
}
if (
await this.staleIndex.reconcile((id) => this.stampXtreamLocks(id))
) {
this.revisionState.update((value) => value + 1);
}
}
setRemovalGate(gate: () => boolean): void {
this.mayRemoveLocks = gate;
}
locksFor(playlistId: string): ParentalLockPlaylistLocks {
return (
this.locks()[playlistId] ?? createEmptyParentalLockPlaylistLocks()
);
}
lockedXtreamIds(
playlistId: string,
categoryType: ParentalLockXtreamCategoryType
): number[] {
return lockedXtreamCategoryIds(this.locks()[playlistId], categoryType);
}
lockedStalkerIds(
playlistId: string,
categoryType: ParentalLockStalkerCategoryType
): string[] {
return lockedStalkerCategoryIds(this.locks()[playlistId], categoryType);
}
lockedGroupTitles(playlistId: string): string[] {
return this.locks()[playlistId]?.m3u ?? [];
}
/**
* Every mutation re-reads a store that failed to read BEFORE building
* the edit: `locksFor` on the empty fail-closed store would otherwise
* turn one type's edit into the playlist's entire lock set once the
* write goes through, discarding its other locks.
*/
async setXtreamLocks(
playlistId: string,
categoryType: ParentalLockXtreamCategoryType,
xtreamIds: LockListEdit<number>
): Promise<boolean> {
return this.enqueue(async () => {
if (!(await this.ensureReadable())) {
return false;
}
const previous = this.locksFor(playlistId);
const next = withXtreamLocks(
previous,
categoryType,
applyLockListEdit(
xtreamIds,
this.lockedXtreamIds(playlistId, categoryType)
)
);
return this.commitLocks(playlistId, previous, next, [categoryType]);
});
}
async setStalkerLocks(
playlistId: string,
categoryType: ParentalLockStalkerCategoryType,
categoryIds: LockListEdit<string>
): Promise<boolean> {
return this.enqueue(async () => {
if (!(await this.ensureReadable())) {
return false;
}
const previous = this.locksFor(playlistId);
const next = withStalkerLocks(
previous,
categoryType,
applyLockListEdit(
categoryIds,
this.lockedStalkerIds(playlistId, categoryType)
)
);
return this.persistEdit(playlistId, previous, next);
});
}
async setM3uLocks(
playlistId: string,
groupTitles: LockListEdit<string>
): Promise<boolean> {
return this.enqueue(async () => {
if (!(await this.ensureReadable())) {
return false;
}
const previous = this.locksFor(playlistId);
const next = withM3uLocks(
previous,
applyLockListEdit(
groupTitles,
this.lockedGroupTitles(playlistId)
)
);
return this.persistEdit(playlistId, previous, next);
});
}
/** Backup restore: replaces every lock of one playlist. */
async replacePlaylistLocks(
playlistId: string,
locks: ParentalLockPlaylistLocks
): Promise<boolean> {
return this.enqueue(async () => {
if (!(await this.ensureReadable())) {
return false;
}
return this.commitLocks(
playlistId,
this.locksFor(playlistId),
locks,
XTREAM_CATEGORY_TYPES
);
});
}
/**
* A deleted playlist's locks leave the store. No re-stamp: its category
* rows are deleted with it. True when there was nothing to remove.
*/
removePlaylist(playlistId: string): Promise<boolean> {
return this.enqueue(async () => {
if (!(await this.ensureReadable())) {
return false;
}
if (!this.locks()[playlistId]) {
return true;
}
return this.persistPlaylistLocks(
playlistId,
createEmptyParentalLockPlaylistLocks()
);
});
}
/** "Remove all playlists": every lock goes with them. */
clearAll(): Promise<boolean> {
return this.enqueue(async () => {
await this.load();
// The playlists are gone either way: the in-memory store empties
// now, and a failed persisted clear is retried on the next
// store access (`ensureReadable`) and by the next write, which
// rewrites the whole store from this empty copy.
this.locks.set({});
this.unreadable.set(false);
this.staleIndex.clear();
this.revisionState.update((value) => value + 1);
return this.rewritePersistedStore();
});
}
/** Stalker and M3U edits: no index, only the store write. */
private async persistEdit(
playlistId: string,
previous: ParentalLockPlaylistLocks,
next: ParentalLockPlaylistLocks
): Promise<boolean> {
return (
lockRemovalGate(previous, next, this.mayRemoveLocks)() &&
this.persistPlaylistLocks(playlistId, next)
);
}
/** Writes the in-memory store; a failure leaves `pendingRewrite` set. */
private async rewritePersistedStore(): Promise<boolean> {
const written = await this.storage.writeLocks(this.locks());
if (!written) {
console.error('The parental lock store could not be rewritten.');
}
if (written === this.pendingRewrite()) {
this.pendingRewrite.set(!written);
this.revisionState.update((value) => value + 1);
}
return written;
}
private enqueue<T>(task: () => Promise<T>): Promise<T> {
const run = this.writeQueue.then(task, task);
this.writeQueue = run.catch(() => undefined);
return run;
}
/**
* Persists `next` and re-stamps the touched types. Order matters for a
* playlist whose LAST lock goes away: its key leaves the store, and the
* startup reconcile finds playlists only through their key — a crash
* between the two writes would strand stamped rows for good. That case
* clears the index first (from `next`) and persists afterwards, so an
* interruption leaves the store with the lock and the index without it,
* which the next reconcile repairs toward locked. Every other write
* persists first and rolls back on a failed re-stamp.
*/
private async commitLocks(
playlistId: string,
previous: ParentalLockPlaylistLocks,
next: ParentalLockPlaylistLocks,
categoryTypes: readonly ParentalLockXtreamCategoryType[]
): Promise<boolean> {
const authorized = lockRemovalGate(previous, next, this.mayRemoveLocks);
const normalizedNext = normalizeParentalLockPlaylistLocks(next);
if (isParentalLockPlaylistLocksEmpty(normalizedNext)) {
if (!(await this.ensureReadable()) || !authorized()) {
return false;
}
// Stale until the STORE write has landed too: while it is
// pending the index is already cleared but the store still
// holds the lock, and a relock in that window must not reload
// through the cleared index.
this.markStaleWhileStamping(playlistId);
if (
(await this.stampXtreamLocks(
playlistId,
categoryTypes,
normalizedNext
)) &&
(await this.persistPlaylistLocks(playlistId, normalizedNext, {
publish: false,
}))
) {
this.staleIndex.unmark(playlistId);
this.revisionState.update((value) => value + 1);
return true;
}
// The clear (partly) reached the index but the store still holds
// the locks: put the index back at once — consumers that query
// the worker directly (title matching, multi-source discovery)
// trust `locked` and are not gated by the renderer's stale flag.
await this.restoreIndex(playlistId, previous, categoryTypes);
return false;
}
// The revision is published only once every type is stamped: a
// consumer reloading on the revision while the stamps are still
// running would read a later type through its old stamps, and a
// successful stamp emits nothing afterwards to reload it.
if (
!authorized() ||
!(await this.persistPlaylistLocks(playlistId, next, {
publish: false,
}))
) {
return false;
}
this.markStaleWhileStamping(playlistId);
if (await this.stampXtreamLocks(playlistId, categoryTypes)) {
this.staleIndex.unmark(playlistId);
this.revisionState.update((value) => value + 1);
return true;
}
await this.rollBack(playlistId, previous, categoryTypes);
return false;
}
/**
* The store commits before the SQLite index is re-stamped; a failed
* re-stamp would otherwise leave a category recorded (and shown) as
* locked while Electron reads, which filter by the index alone, still
* serve it. The store goes back to the previous locks and the touched
* types are re-stamped from it — a multi-type re-stamp may have
* committed some types before the failing one. If either step fails,
* the playlist is marked stale, which keeps the session fail-closed and
* re-stamps it on the next access.
*/
private async rollBack(
playlistId: string,
previous: ParentalLockPlaylistLocks,
categoryTypes: readonly ParentalLockXtreamCategoryType[]
): Promise<void> {
// Published once, after the re-stamp: a reload on an earlier
// revision would read a later type through the attempted stamps.
const restored = await this.persistPlaylistLocks(playlistId, previous, {
publish: false,
});
if (!restored) {
// Memory goes back to the previous locks anyway, and the
// persisted copy is rewritten from it on the next access: the
// failed edit must not take effect through a later re-stamp.
this.locks.set(
withPlaylistLocksInStore(this.locks(), playlistId, previous)
);
this.pendingRewrite.set(true);
}
const restamped =
restored &&
(await this.stampXtreamLocks(playlistId, categoryTypes));
if (!restored || !restamped) {
console.error('Failed to roll back the parental lock index.');
this.staleIndex.mark(playlistId);
} else {
this.staleIndex.unmark(playlistId);
}
this.revisionState.update((value) => value + 1);
}
/**
* From the store change until every stamp has landed the SQLite index
* does not agree with the store: `readable` must be false for that whole
* window, or a relock inside it would reload through the old stamps.
* Only Electron has the index.
*/
private markStaleWhileStamping(playlistId: string): void {
if (this.runtime.supportsXtreamSqliteDataSource) {
this.staleIndex.markInFlight(playlistId);
}
}
/** Re-stamps the index from `locks`; marks it stale when that fails. */
private async restoreIndex(
playlistId: string,
locks: ParentalLockPlaylistLocks,
categoryTypes: readonly ParentalLockXtreamCategoryType[]
): Promise<void> {
if (!(await this.stampXtreamLocks(playlistId, categoryTypes, locks))) {
console.error('Failed to restore the parental lock index.');
this.staleIndex.mark(playlistId);
} else {
this.staleIndex.unmark(playlistId);
}
this.revisionState.update((value) => value + 1);
}
/**
* Re-stamps the Electron `categories.locked` index for a playlist from
* the store, e.g. after a refresh recreated the rows.
*/
async stampXtreamLocks(
playlistId: string,
categoryTypes: readonly ParentalLockXtreamCategoryType[] = XTREAM_CATEGORY_TYPES,
locks: ParentalLockPlaylistLocks = this.locksFor(playlistId)
): Promise<boolean> {
return (
!this.runtime.supportsXtreamSqliteDataSource ||
stampXtreamIndex(
(id, type, ids) =>
this.databaseService.setCategoryLocks(id, type, ids),
playlistId,
categoryTypes,
locks
)
);
}
private async persistPlaylistLocks(
playlistId: string,
locks: ParentalLockPlaylistLocks,
options: { publish?: boolean } = {}
): Promise<boolean> {
// Every public mutation runs `ensureReadable()` before it builds its
// edit. Here only the STORE must be known: the index of the
// playlist being written is deliberately stale while it is
// re-stamped, and a rollback must still be able to write.
if (this.unreadable()) {
return false;
}
const next = withPlaylistLocksInStore(this.locks(), playlistId, locks);
if (!(await this.storage.writeLocks(next))) {
return false;
}
this.locks.set(next);
if (options.publish !== false) {
this.revisionState.update((value) => value + 1);
}
return true;
}
}
@@ -0,0 +1,27 @@
import { inject, Provider } from '@angular/core';
import { PLAYLIST_DELETE_CLEANUP } from '../playlist-delete-cleanup.token';
import { ParentalLockService } from './parental-lock.service';
/**
* Removes a deleted playlist's locks from the persisted lock store. Every
* single-playlist deletion runs `PlaylistsService.deletePlaylist`, which
* calls the `PLAYLIST_DELETE_CLEANUP` hooks after the row is gone; "remove
* all playlists" clears the store through `ParentalLockService.clearAllLocks`
* instead.
*/
export function provideParentalLockPlaylistCleanup(): Provider {
return {
provide: PLAYLIST_DELETE_CLEANUP,
multi: true,
useFactory: () => {
const parentalLock = inject(ParentalLockService);
return async (playlistId: string) => {
if (!(await parentalLock.removePlaylistLocks(playlistId))) {
throw new Error(
'The parental locks of the deleted playlist could not be removed.'
);
}
};
},
};
}
@@ -0,0 +1,38 @@
import { InjectionToken } from '@angular/core';
import type { ParentalLockPinThrottle } from '@iptvnator/shared/interfaces';
export type ParentalLockPromptMode = 'unlock' | 'set';
export interface ParentalLockPromptRequest {
/** `unlock` asks for the current PIN, `set` asks for a new one twice. */
mode: ParentalLockPromptMode;
/**
* Unlock only: resolves whether the typed PIN matches. The prompt keeps
* asking on a mismatch and applies its own attempt cooldown.
*/
verify?: (pin: string) => Promise<boolean>;
/**
* Unlock only: the wrong-PIN count and cooldown, owned by the lock
* service so they survive the prompt being dismissed and reopened.
*/
throttle?: ParentalLockPinThrottle;
/** Optional translation key overriding the mode's default title. */
titleKey?: string;
/** Optional translation key overriding the mode's default description. */
descriptionKey?: string;
}
/**
* The UI half of the parental lock: shows a PIN prompt and resolves with the
* accepted PIN, or `null` when the user dismissed it.
*
* Provided by the application (which may depend on UI libraries) so the
* lock service in this data-access library stays free of dialogs.
*/
export interface ParentalLockPrompt {
requestPin(request: ParentalLockPromptRequest): Promise<string | null>;
}
export const PARENTAL_LOCK_PROMPT = new InjectionToken<ParentalLockPrompt>(
'PARENTAL_LOCK_PROMPT'
);
@@ -0,0 +1,51 @@
import { persistParentalLockEnabled } from './parental-lock-settings-writer';
describe('persistParentalLockEnabled', () => {
it('rolls a failed write back to the value recovered by the settings retry', async () => {
jest.spyOn(console, 'error').mockImplementation(() => undefined);
let failure: 'load' | 'save' | null = 'load';
let stored: boolean | undefined = undefined;
const settings = {
storageFailure: () => failure,
parentalLockEnabled: () => stored,
// The retried read recovers: the switch was already off.
loadSettings: jest.fn(async () => {
failure = null;
stored = false;
}),
updateSettings: jest
.fn()
.mockRejectedValueOnce(new Error('disk full'))
.mockResolvedValue(undefined),
};
await expect(persistParentalLockEnabled(settings, false)).resolves.toBe(
false
);
// Undone to the recovered `false`, not the hard-coded inverse.
expect(settings.updateSettings).toHaveBeenLastCalledWith({
parentalLockEnabled: false,
});
});
it('undoes to the inverse when the switch was never persisted', async () => {
jest.spyOn(console, 'error').mockImplementation(() => undefined);
const settings = {
storageFailure: () => null,
loadSettings: jest.fn(),
updateSettings: jest
.fn()
.mockRejectedValueOnce(new Error('disk full'))
.mockResolvedValue(undefined),
};
await expect(persistParentalLockEnabled(settings, true)).resolves.toBe(
false
);
expect(settings.updateSettings).toHaveBeenLastCalledWith({
parentalLockEnabled: false,
});
});
});
@@ -0,0 +1,99 @@
import { normalizeParentalLockRelockMinutes } from '@iptvnator/shared/interfaces';
import { SettingsStore } from '../settings-store.service';
import { mirrorParentalLockEnabledSetting } from './parental-lock-bridge';
type SettingsWriter = Pick<
InstanceType<typeof SettingsStore>,
'updateSettings' | 'loadSettings'
> & {
storageFailure?: () => 'load' | 'save' | null;
parentalLockEnabled?: () => boolean | undefined;
};
/**
* `updateSettings` writes the WHOLE settings object. After a failed startup
* read that object is the defaults, so a parental-lock write would replace
* the user's persisted player, portal and UI preferences. The read is
* retried first (a transient failure recovers here), and the write is
* refused while settings stay unreadable.
*/
export async function ensureParentalLockSettingsReadable(
settings: SettingsWriter
): Promise<boolean> {
if (settings.storageFailure?.() !== 'load') {
return true;
}
await settings.loadSettings();
return settings.storageFailure?.() !== 'load';
}
/**
* Persists the feature switch. `updateSettings` patches the in-memory value
* before the write; on a failed write that patch is undone (the second write
* fails the same way and is ignored), so the toggle cannot show a state the
* next launch will not have. The Electron mirror is written after the
* settings and undoes them the same way when it fails: a reloaded renderer
* and a restarted worker start from the mirror.
*/
export async function persistParentalLockEnabled(
settings: SettingsWriter,
enabled: boolean
): Promise<boolean> {
if (!(await ensureParentalLockSettingsReadable(settings))) {
return false;
}
// Read AFTER the retry, as for the relock timeout: a recovered read may
// already hold `enabled` (e.g. disable() entered while the unknown
// switch followed the stored PIN), and undoing to the inverse would
// then write the opposite of what was persisted.
const previous = settings.parentalLockEnabled?.() ?? !enabled;
const undo = () =>
settings
.updateSettings({ parentalLockEnabled: previous })
.catch(() => undefined);
try {
await settings.updateSettings({ parentalLockEnabled: enabled });
} catch (error) {
console.error('Failed to persist the parental lock switch.', error);
await undo();
return false;
}
if (!(await mirrorParentalLockEnabledSetting(enabled))) {
await undo();
return false;
}
return true;
}
/**
* False when the value could not be persisted; the in-memory patch is undone
* so the timer on screen never differs from the one the next launch uses.
*/
export async function persistParentalLockRelockMinutes(
settings: SettingsWriter,
minutes: number,
readCurrent: () => number
): Promise<boolean> {
if (!(await ensureParentalLockSettingsReadable(settings))) {
return false;
}
// Read AFTER the retry: a recovered read replaces the defaults, and a
// rollback to the pre-retry value would write the default back.
const previous = readCurrent();
try {
await settings.updateSettings({
parentalLockRelockMinutes:
normalizeParentalLockRelockMinutes(minutes),
});
return true;
} catch (error) {
console.error('Failed to persist the relock timeout.', error);
await settings
.updateSettings({
parentalLockRelockMinutes:
normalizeParentalLockRelockMinutes(previous),
})
.catch(() => undefined);
return false;
}
}
@@ -0,0 +1,77 @@
import { computed, signal } from '@angular/core';
/**
* Playlists whose SQLite `categories.locked` index may lag behind the lock
* store: a re-stamp in progress, or one that failed (with its rollback) and
* is retried on the next store access. The lock store is not `readable`
* while any playlist is listed.
*/
export class ParentalLockStaleIndex {
private readonly playlists = new Set<string>();
/**
* Listed while a queued write is stamping them: stale (not `readable`)
* but not retryable — a reconcile running beside the write would
* re-stamp from a store the write has not committed yet.
*/
private readonly inFlight = new Set<string>();
private readonly count = signal(0);
readonly isEmpty = computed(() => this.count() === 0);
/** The retryable entries: not the ones a write is still stamping. */
ids(): string[] {
return [...this.playlists].filter((id) => !this.inFlight.has(id));
}
/** Stale and retryable (a failed stamp or rollback). */
mark(playlistId: string): void {
this.inFlight.delete(playlistId);
this.playlists.add(playlistId);
this.count.set(this.playlists.size);
}
/** Stale while the write in progress stamps it. */
markInFlight(playlistId: string): void {
this.inFlight.add(playlistId);
this.playlists.add(playlistId);
this.count.set(this.playlists.size);
}
unmark(...playlistIds: string[]): void {
for (const playlistId of playlistIds) {
this.playlists.delete(playlistId);
this.inFlight.delete(playlistId);
}
this.count.set(this.playlists.size);
}
clear(): void {
this.unmark(...this.playlists);
}
/**
* Re-stamps every listed playlist through `stamp`; the ones that
* succeed leave the list. True when any did.
*/
async reconcile(
stamp: (playlistId: string) => Promise<boolean>
): Promise<boolean> {
const restamped: string[] = [];
for (const playlistId of this.ids()) {
try {
if (await stamp(playlistId)) {
restamped.push(playlistId);
}
} catch (error) {
console.error(
'Failed to reconcile the parental lock index.',
error
);
}
}
if (restamped.length > 0) {
this.unmark(...restamped);
}
return restamped.length > 0;
}
}
@@ -0,0 +1,90 @@
import { TestBed } from '@angular/core/testing';
import { PARENTAL_LOCK_STORE_KEY } from '@iptvnator/shared/interfaces';
import { DatabaseService } from '../database-electron.service';
import { RuntimeCapabilitiesService } from '../runtime-capabilities.service';
import { ParentalLockStorageService } from './parental-lock-storage';
describe('ParentalLockStorageService.readLocks', () => {
const runtime = { supportsAppStateStorage: false };
const databaseService = {
readAppState: jest.fn<
Promise<{ value: string | null } | null>,
[string]
>(),
};
let service: ParentalLockStorageService;
beforeEach(() => {
localStorage.clear();
runtime.supportsAppStateStorage = false;
databaseService.readAppState.mockReset();
TestBed.configureTestingModule({
providers: [
ParentalLockStorageService,
{ provide: RuntimeCapabilitiesService, useValue: runtime },
{ provide: DatabaseService, useValue: databaseService },
],
});
service = TestBed.inject(ParentalLockStorageService);
});
it('reads an absent store as empty', async () => {
await expect(service.readLocks()).resolves.toEqual({});
});
it('normalizes a stored store', async () => {
localStorage.setItem(
PARENTAL_LOCK_STORE_KEY,
JSON.stringify({
p: { xtream: [], stalker: [], m3u: ['Adult'], junk: 1 },
})
);
await expect(service.readLocks()).resolves.toEqual({
p: { xtream: [], stalker: [], m3u: ['Adult'] },
});
});
it.each([
['truncated JSON', '{"p":{"m3u":["Adu'],
['an array payload', '[]'],
['a scalar payload', '"locks"'],
[
'a corrupt nested list',
'{"p":{"xtream":"corrupt","stalker":[],"m3u":[]}}',
],
[
'a corrupt nested entry',
'{"p":{"xtream":[],"stalker":[],"m3u":[1]}}',
],
['a playlist entry missing a list', '{"p":{}}'],
[
'an entry the normalizer would drop',
'{"p":{"xtream":[{"categoryType":"live","xtreamId":"nope"}],"stalker":[],"m3u":[]}}',
],
])('treats %s as a failed read, not an empty store', async (_, raw) => {
localStorage.setItem(PARENTAL_LOCK_STORE_KEY, raw);
await expect(service.readLocks()).resolves.toBeNull();
});
it('treats a throwing localStorage as a failed read', async () => {
const getItem = jest
.spyOn(Storage.prototype, 'getItem')
.mockImplementation(() => {
throw new Error('SecurityError');
});
try {
await expect(service.readLocks()).resolves.toBeNull();
} finally {
getItem.mockRestore();
}
});
it('keeps an Electron read failure apart from a missing key', async () => {
runtime.supportsAppStateStorage = true;
databaseService.readAppState.mockResolvedValueOnce(null);
await expect(service.readLocks()).resolves.toBeNull();
databaseService.readAppState.mockResolvedValueOnce({ value: null });
await expect(service.readLocks()).resolves.toEqual({});
});
});
@@ -0,0 +1,104 @@
import { inject, Injectable } from '@angular/core';
import {
isWellFormedParentalLockStore,
normalizeParentalLockStore,
PARENTAL_LOCK_PIN_KEY,
PARENTAL_LOCK_STORE_KEY,
ParentalLockStore,
} from '@iptvnator/shared/interfaces';
import { DatabaseService } from '../database-electron.service';
import { RuntimeCapabilitiesService } from '../runtime-capabilities.service';
/**
* Persistence for the parental lock: the hashed PIN and the lock store.
*
* Both live OUTSIDE `Settings` on purpose. Settings are logged (redacted,
* but still), exported in backups and mirrored to the main process; a PIN
* hash belongs in none of those places. Electron keeps them in the SQLite
* `app_state` table, the PWA in localStorage.
*/
@Injectable({ providedIn: 'root' })
export class ParentalLockStorageService {
private readonly runtime = inject(RuntimeCapabilitiesService);
private readonly databaseService = inject(DatabaseService);
private get usesAppState(): boolean {
return this.runtime.supportsAppStateStorage;
}
/**
* The stored PIN hash (`hash: null` when none was set up), or `null`
* when the read itself failed — the service then retries before every
* PIN-protected operation instead of treating the PIN as absent.
*/
async readPinHash(): Promise<{ hash: string | null } | null> {
const result = await this.read(PARENTAL_LOCK_PIN_KEY);
if (result === null) {
return null;
}
const value = result.value;
return { hash: value && value.trim() !== '' ? value : null };
}
async writePinHash(hash: string): Promise<boolean> {
return this.write(PARENTAL_LOCK_PIN_KEY, hash);
}
/**
* The lock store, or `null` when it could not be READ — distinct from an
* absent store, which is `{}`. A failed read must not look like "nothing
* is locked": the service withholds everything until it can read again.
* A stored payload that does not parse, or is not an object, counts as
* a failed read too: corruption must not become an empty store.
*/
async readLocks(): Promise<ParentalLockStore | null> {
const result = await this.read(PARENTAL_LOCK_STORE_KEY);
if (result === null) {
return null;
}
if (!result.value) {
return {};
}
let parsed: unknown;
try {
parsed = JSON.parse(result.value);
} catch {
return null;
}
if (!isWellFormedParentalLockStore(parsed)) {
return null;
}
return normalizeParentalLockStore(parsed);
}
async writeLocks(store: ParentalLockStore): Promise<boolean> {
return this.write(
PARENTAL_LOCK_STORE_KEY,
JSON.stringify(normalizeParentalLockStore(store))
);
}
/** `null` when the read itself failed; an absent key is `{ value: null }`. */
private async read(key: string): Promise<{ value: string | null } | null> {
if (this.usesAppState) {
return this.databaseService.readAppState(key);
}
try {
return { value: localStorage.getItem(key) };
} catch {
return null;
}
}
private async write(key: string, value: string): Promise<boolean> {
if (this.usesAppState) {
return this.databaseService.setAppState(key, value);
}
try {
localStorage.setItem(key, value);
return localStorage.getItem(key) === value;
} catch {
return false;
}
}
}
@@ -0,0 +1,34 @@
import { removesParentalLocks } from './parental-lock-store.util';
describe('removesParentalLocks', () => {
const previous = {
xtream: [{ categoryType: 'live' as const, xtreamId: 7 }],
stalker: [{ categoryType: 'vod' as const, categoryId: '3' }],
m3u: ['Adults'],
};
it('is false when every previous lock is kept, extra locks or not', () => {
expect(removesParentalLocks(previous, previous)).toBe(false);
expect(
removesParentalLocks(previous, {
...previous,
m3u: ['Adults', 'News'],
})
).toBe(false);
});
it('is true when any portal list drops a lock', () => {
expect(
removesParentalLocks(previous, { ...previous, xtream: [] })
).toBe(true);
expect(
removesParentalLocks(previous, {
...previous,
stalker: [{ categoryType: 'itv', categoryId: '3' }],
})
).toBe(true);
expect(removesParentalLocks(previous, { ...previous, m3u: [] })).toBe(
true
);
});
});
@@ -0,0 +1,146 @@
import {
isParentalLockPlaylistLocksEmpty,
lockedXtreamCategoryIds,
normalizeParentalLockPlaylistLocks,
ParentalLockPlaylistLocks,
ParentalLockStalkerCategoryType,
ParentalLockStore,
ParentalLockXtreamCategoryType,
} from '@iptvnator/shared/interfaces';
/**
* Pure builders for the next lock set of one playlist: each replaces the
* entries of ONE category type (or the M3U group list) and leaves the other
* types untouched, so a dialog editing Live TV cannot drop the Movies locks.
*/
export function withXtreamLocks(
current: ParentalLockPlaylistLocks,
categoryType: ParentalLockXtreamCategoryType,
xtreamIds: readonly number[]
): ParentalLockPlaylistLocks {
return {
...current,
xtream: [
...current.xtream.filter(
(entry) => entry.categoryType !== categoryType
),
...[...new Set(xtreamIds)].map((xtreamId) => ({
categoryType,
xtreamId,
})),
],
};
}
export function withStalkerLocks(
current: ParentalLockPlaylistLocks,
categoryType: ParentalLockStalkerCategoryType,
categoryIds: readonly string[]
): ParentalLockPlaylistLocks {
return {
...current,
stalker: [
...current.stalker.filter(
(entry) => entry.categoryType !== categoryType
),
...[...new Set(categoryIds)].map((categoryId) => ({
categoryType,
categoryId,
})),
],
};
}
export function withM3uLocks(
current: ParentalLockPlaylistLocks,
groupTitles: readonly string[]
): ParentalLockPlaylistLocks {
return { ...current, m3u: [...new Set(groupTitles)] };
}
/** Whether `next` drops any lock that `previous` holds. */
export function removesParentalLocks(
previous: ParentalLockPlaylistLocks,
next: ParentalLockPlaylistLocks
): boolean {
const xtream = new Set(
next.xtream.map((lock) => `${lock.categoryType}:${lock.xtreamId}`)
);
const stalker = new Set(
next.stalker.map((lock) => `${lock.categoryType}:${lock.categoryId}`)
);
const m3u = new Set(next.m3u);
return (
previous.xtream.some(
(lock) => !xtream.has(`${lock.categoryType}:${lock.xtreamId}`)
) ||
previous.stalker.some(
(lock) => !stalker.has(`${lock.categoryType}:${lock.categoryId}`)
) ||
previous.m3u.some((title) => !m3u.has(title))
);
}
/**
* Whether an edit from `previous` to `next` may be issued: adding locks
* always may, removing one only while `mayRemove()` says so (logged when
* refused). Returned as a function so the answer is taken at the moment
* the edit's first write is issued.
*/
export function lockRemovalGate(
previous: ParentalLockPlaylistLocks,
next: ParentalLockPlaylistLocks,
mayRemove: () => boolean
): () => boolean {
const removes = removesParentalLocks(previous, next);
return () => {
if (!removes || mayRemove()) {
return true;
}
console.warn('A parental lock edit was refused: the app is locked.');
return false;
};
}
/** `store` with one playlist's locks replaced; an empty set drops its key. */
export function withPlaylistLocksInStore(
store: ParentalLockStore,
playlistId: string,
locks: ParentalLockPlaylistLocks
): ParentalLockStore {
const normalized = normalizeParentalLockPlaylistLocks(locks);
const next: ParentalLockStore = { ...store };
if (isParentalLockPlaylistLocksEmpty(normalized)) {
delete next[playlistId];
} else {
next[playlistId] = normalized;
}
return next;
}
/**
* Stamps the SQLite `categories.locked` index of one playlist from `locks`,
* type by type. Every type is attempted; false when any of them failed.
*/
export async function stampXtreamIndex(
setCategoryLocks: (
playlistId: string,
categoryType: ParentalLockXtreamCategoryType,
lockedXtreamIds: number[]
) => Promise<boolean>,
playlistId: string,
categoryTypes: readonly ParentalLockXtreamCategoryType[],
locks: ParentalLockPlaylistLocks
): Promise<boolean> {
let success = true;
for (const categoryType of categoryTypes) {
success =
(await setCategoryLocks(
playlistId,
categoryType,
lockedXtreamCategoryIds(locks, categoryType)
)) && success;
}
return success;
}
@@ -0,0 +1,619 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { webcrypto } from 'node:crypto';
import { hashParentalLockPin } from '@iptvnator/shared/interfaces';
import { DatabaseService } from '../database-electron.service';
import { RuntimeCapabilitiesService } from '../runtime-capabilities.service';
import { SettingsStore } from '../settings-store.service';
import {
PARENTAL_LOCK_PROMPT,
ParentalLockPromptRequest,
} from './parental-lock-prompt.token';
import { ParentalLockStorageService } from './parental-lock-storage';
import { ParentalLockService } from './parental-lock.service';
describe('ParentalLockService', () => {
const originalElectron = window.electron;
let parentalLockEnabled: ReturnType<typeof signal<boolean>>;
let parentalLockRelockMinutes: ReturnType<typeof signal<number>>;
let storageFailure: ReturnType<typeof signal<'load' | 'save' | null>>;
let updateSettings: jest.Mock;
let storage: {
pinHash: string | null;
locks: Record<string, unknown>;
readPinHash: jest.Mock;
writePinHash: jest.Mock;
readLocks: jest.Mock;
writeLocks: jest.Mock;
};
let prompt: { requestPin: jest.Mock };
let setCategoryLocks: jest.Mock;
let setParentalLockState: jest.Mock;
let updateBridgeSettings: jest.Mock;
let runtime: {
supportsXtreamSqliteDataSource: boolean;
supportsParentalLockSqliteFilter: boolean;
};
beforeAll(() => {
if (!globalThis.crypto?.subtle) {
Object.defineProperty(globalThis, 'crypto', {
configurable: true,
value: webcrypto,
});
}
});
beforeEach(() => {
parentalLockEnabled = signal(false);
parentalLockRelockMinutes = signal(15);
storageFailure = signal<'load' | 'save' | null>(null);
updateSettings = jest.fn(async (patch: Record<string, unknown>) => {
if ('parentalLockEnabled' in patch) {
parentalLockEnabled.set(patch['parentalLockEnabled'] === true);
}
if ('parentalLockRelockMinutes' in patch) {
parentalLockRelockMinutes.set(
patch['parentalLockRelockMinutes'] as number
);
}
});
storage = {
pinHash: null,
locks: {},
readPinHash: jest.fn(async () => ({ hash: storage.pinHash })),
writePinHash: jest.fn(async (hash: string) => {
storage.pinHash = hash;
return true;
}),
readLocks: jest.fn(async () => storage.locks),
writeLocks: jest.fn(async (locks: Record<string, unknown>) => {
storage.locks = locks;
return true;
}),
};
prompt = { requestPin: jest.fn() };
runtime = {
supportsXtreamSqliteDataSource: true,
supportsParentalLockSqliteFilter: true,
};
setCategoryLocks = jest.fn(async () => true);
setParentalLockState = jest.fn(async () => undefined);
updateBridgeSettings = jest.fn(async () => undefined);
Object.defineProperty(window, 'electron', {
configurable: true,
writable: true,
value: {
setParentalLockState,
updateSettings: updateBridgeSettings,
},
});
TestBed.configureTestingModule({
providers: [
ParentalLockService,
{
provide: SettingsStore,
useValue: {
parentalLockEnabled,
parentalLockRelockMinutes,
storageFailure,
loadSettings: jest.fn(async () => undefined),
updateSettings,
},
},
{ provide: ParentalLockStorageService, useValue: storage },
{ provide: PARENTAL_LOCK_PROMPT, useValue: prompt },
{
provide: RuntimeCapabilitiesService,
useValue: runtime,
},
{ provide: DatabaseService, useValue: { setCategoryLocks } },
],
});
});
afterEach(() => {
Object.defineProperty(window, 'electron', {
configurable: true,
writable: true,
value: originalElectron,
});
});
async function createService(): Promise<ParentalLockService> {
const service = TestBed.inject(ParentalLockService);
await service.initialize();
TestBed.flushEffects();
return service;
}
it('is inactive while the feature is off and reports that to the main process', async () => {
const service = await createService();
expect(service.enabled()).toBe(false);
expect(service.active()).toBe(false);
expect(service.hasPin()).toBe(false);
expect(setParentalLockState).toHaveBeenLastCalledWith(false);
await expect(service.requestUnlock()).resolves.toBe(true);
expect(prompt.requestPin).not.toHaveBeenCalled();
});
it('stands in the stored PIN for the switch when settings could not be read', async () => {
storage.pinHash = await hashParentalLockPin('1234');
storageFailure.set('load');
// Defaults-by-failure: the store reports the feature as off.
parentalLockEnabled.set(false);
const service = await createService();
expect(service.enabled()).toBe(true);
expect(service.active()).toBe(true);
expect(setParentalLockState).toHaveBeenLastCalledWith(true);
});
it('never announces an unlocked state on unreadable settings without a PIN', async () => {
storageFailure.set('load');
const service = await createService();
expect(service.enabled()).toBe(false);
expect(setParentalLockState).not.toHaveBeenCalled();
});
it('withholds every category while the lock store cannot be read', async () => {
storage.pinHash = await hashParentalLockPin('1234');
parentalLockEnabled.set(true);
storage.readLocks.mockResolvedValue(null);
const service = await createService();
expect(service.active()).toBe(true);
expect(service.withholdsEverything()).toBe(true);
expect(service.isXtreamCategoryLocked('p', 'live', 1)).toBe(true);
expect(service.isStalkerCategoryLocked('p', 'itv', '1')).toBe(true);
expect(service.isStalkerCategoryLocked('p', 'itv', undefined)).toBe(
true
);
expect(service.isM3uGroupLocked('p', 'News')).toBe(true);
// Nothing is known about the persisted locks: a write built on the
// empty in-memory store would wipe them.
await expect(service.setM3uLocks('p', ['Adult'])).resolves.toBe(false);
expect(storage.writeLocks).not.toHaveBeenCalled();
// The store reads again: the real locks apply and writes resume.
storage.readLocks.mockResolvedValue({
p: { xtream: [], stalker: [], m3u: ['Adult'] },
});
await expect(service.setM3uLocks('p', ['Adult', 'XXX'])).resolves.toBe(
true
);
TestBed.flushEffects();
expect(service.withholdsEverything()).toBe(false);
expect(service.isM3uGroupLocked('p', 'News')).toBe(false);
expect(service.isM3uGroupLocked('p', 'XXX')).toBe(true);
});
it('withholds every category while locked when the worker filter bridge is missing', async () => {
jest.spyOn(console, 'error').mockImplementation(() => undefined);
runtime.supportsParentalLockSqliteFilter = false;
storage.pinHash = await hashParentalLockPin('1234');
parentalLockEnabled.set(true);
const service = await createService();
expect(service.active()).toBe(true);
expect(service.locksReadable()).toBe(true);
expect(service.withholdsEverything()).toBe(true);
expect(service.isXtreamCategoryLocked('p', 'live', 1)).toBe(true);
prompt.requestPin.mockResolvedValue('1234');
await expect(service.requestUnlock()).resolves.toBe(true);
expect(service.withholdsEverything()).toBe(false);
});
it('withholds everything while locked when the worker lock-state sync rejects', async () => {
jest.spyOn(console, 'error').mockImplementation(() => undefined);
setParentalLockState.mockRejectedValue(new Error('no handler'));
storage.pinHash = await hashParentalLockPin('1234');
parentalLockEnabled.set(true);
const service = await createService();
const version = service.version();
await Promise.resolve();
await Promise.resolve();
expect(service.active()).toBe(true);
expect(service.withholdsEverything()).toBe(true);
expect(service.version()).toBeGreaterThan(version);
// The sync of the next transition succeeds: normal filtering again.
setParentalLockState.mockResolvedValue(undefined);
prompt.requestPin.mockResolvedValue('1234');
await service.requestUnlock();
TestBed.flushEffects();
await Promise.resolve();
await Promise.resolve();
service.lock();
TestBed.flushEffects();
await Promise.resolve();
await Promise.resolve();
expect(service.withholdsEverything()).toBe(false);
});
it('withholds everything while the initial lock store read is in flight', async () => {
storage.pinHash = await hashParentalLockPin('1234');
parentalLockEnabled.set(true);
let resolveLocks: (locks: Record<string, unknown>) => void = () =>
undefined;
storage.readLocks.mockReturnValue(
new Promise((resolve) => (resolveLocks = resolve))
);
const service = TestBed.inject(ParentalLockService);
const initialization = service.initialize();
await Promise.resolve();
expect(service.active()).toBe(true);
expect(service.withholdsEverything()).toBe(true);
expect(service.isM3uGroupLocked('p', 'News')).toBe(true);
resolveLocks({});
await initialization;
expect(service.withholdsEverything()).toBe(false);
expect(service.isM3uGroupLocked('p', 'News')).toBe(false);
});
it('rolls the switch back when enabling cannot be persisted', async () => {
prompt.requestPin.mockResolvedValue('1234');
updateSettings.mockImplementationOnce(async () => {
// updateSettings patches memory before the write fails.
parentalLockEnabled.set(true);
throw new Error('QuotaExceededError');
});
const service = await createService();
await expect(service.setupPin()).resolves.toBe(false);
expect(service.hasPin()).toBe(true);
expect(service.enabled()).toBe(false);
expect(service.unlocked()).toBe(false);
expect(updateBridgeSettings).not.toHaveBeenCalled();
});
it('retries a failed settings read before persisting the switch', async () => {
storageFailure.set('load');
prompt.requestPin.mockResolvedValue('1234');
const service = await createService();
// Storage recovers: the retry reads the persisted settings back.
const loadSettings = TestBed.inject(SettingsStore)
.loadSettings as jest.Mock;
loadSettings.mockImplementationOnce(async () => {
storageFailure.set(null);
});
await expect(service.setupPin()).resolves.toBe(true);
expect(loadSettings).toHaveBeenCalledTimes(2);
expect(updateSettings).toHaveBeenCalledWith({
parentalLockEnabled: true,
});
expect(updateBridgeSettings).toHaveBeenCalledWith({
parentalLockEnabled: true,
});
});
it('rolls a failed relock write back to the value recovered by the retry', async () => {
storageFailure.set('load');
const service = await createService();
const loadSettings = TestBed.inject(SettingsStore)
.loadSettings as jest.Mock;
loadSettings.mockImplementationOnce(async () => {
storageFailure.set(null);
parentalLockRelockMinutes.set(60);
});
updateSettings.mockImplementationOnce(async () => {
parentalLockRelockMinutes.set(30);
throw new Error('QuotaExceededError');
});
await expect(service.setRelockMinutes(30)).resolves.toBe(false);
expect(updateSettings).toHaveBeenLastCalledWith({
parentalLockRelockMinutes: 60,
});
});
it('refuses parental-lock settings writes while settings stay unreadable', async () => {
storageFailure.set('load');
prompt.requestPin.mockResolvedValue('1234');
const service = await createService();
// Writing now would replace the persisted settings with defaults.
await expect(service.setupPin()).resolves.toBe(false);
await expect(service.setRelockMinutes(30)).resolves.toBe(false);
expect(updateSettings).not.toHaveBeenCalled();
expect(prompt.requestPin).not.toHaveBeenCalled();
});
it('keeps the session locked on a failed PIN read and retries before unlocking', async () => {
storage.pinHash = await hashParentalLockPin('1234');
parentalLockEnabled.set(true);
storage.readPinHash.mockResolvedValueOnce(null);
prompt.requestPin.mockImplementation(
async (request: ParentalLockPromptRequest) =>
(await request.verify?.('1234')) ? '1234' : null
);
const service = await createService();
expect(service.active()).toBe(true);
expect(service.hasPin()).toBe(false);
await expect(service.requestUnlock()).resolves.toBe(true);
expect(service.hasPin()).toBe(true);
expect(service.unlocked()).toBe(true);
});
it('refuses a relock timeout change while the session is locked', async () => {
storage.pinHash = await hashParentalLockPin('1234');
parentalLockEnabled.set(true);
const service = await createService();
expect(service.active()).toBe(true);
await expect(service.setRelockMinutes(0)).resolves.toBe(false);
expect(updateSettings).not.toHaveBeenCalledWith(
expect.objectContaining({ parentalLockRelockMinutes: 0 })
);
expect(service.relockMinutes()).toBe(15);
});
it('rolls the relock timeout back when it cannot be persisted', async () => {
updateSettings.mockImplementationOnce(async () => {
parentalLockRelockMinutes.set(30);
throw new Error('QuotaExceededError');
});
const service = await createService();
await expect(service.setRelockMinutes(30)).resolves.toBe(false);
expect(service.relockMinutes()).toBe(15);
expect(updateSettings).toHaveBeenLastCalledWith({
parentalLockRelockMinutes: 15,
});
});
it('rolls the switch back when the Electron mirror cannot be written', async () => {
prompt.requestPin.mockResolvedValue('1234');
updateBridgeSettings.mockRejectedValueOnce(new Error('ipc'));
const service = await createService();
await expect(service.setupPin()).resolves.toBe(false);
expect(service.enabled()).toBe(false);
expect(service.unlocked()).toBe(false);
expect(updateSettings).toHaveBeenLastCalledWith({
parentalLockEnabled: false,
});
});
it('starts locked with the feature on and unlocks through the prompt', async () => {
storage.pinHash = await hashParentalLockPin('1234');
parentalLockEnabled.set(true);
prompt.requestPin.mockImplementation(
async (request: ParentalLockPromptRequest) =>
(await request.verify?.('1234')) ? '1234' : null
);
const service = await createService();
expect(service.active()).toBe(true);
expect(setParentalLockState).toHaveBeenLastCalledWith(true);
const unlocked = service.requestUnlock();
const concurrent = service.requestUnlock();
await expect(unlocked).resolves.toBe(true);
await expect(concurrent).resolves.toBe(true);
expect(prompt.requestPin).toHaveBeenCalledTimes(1);
TestBed.flushEffects();
expect(service.unlocked()).toBe(true);
expect(service.active()).toBe(false);
expect(setParentalLockState).toHaveBeenLastCalledWith(false);
service.lock();
TestBed.flushEffects();
expect(service.active()).toBe(true);
expect(setParentalLockState).toHaveBeenLastCalledWith(true);
});
it('does not open a gate before the settings have loaded', async () => {
storage.pinHash = await hashParentalLockPin('1234');
prompt.requestPin.mockResolvedValue(null);
let releaseSettings!: () => void;
const settingsStore = TestBed.inject(SettingsStore) as unknown as {
loadSettings: jest.Mock;
};
settingsStore.loadSettings.mockImplementation(
() =>
new Promise<void>((resolve) => {
releaseSettings = () => {
parentalLockEnabled.set(true);
resolve();
};
})
);
const service = TestBed.inject(ParentalLockService);
void service.initialize();
// Enabled is still the default false here: the answer must wait for
// the load instead of reading that as "feature off".
const gate = service.requestUnlock();
releaseSettings();
await expect(gate).resolves.toBe(false);
expect(prompt.requestPin).toHaveBeenCalledTimes(1);
});
it('stays locked when the prompt is dismissed', async () => {
storage.pinHash = await hashParentalLockPin('1234');
parentalLockEnabled.set(true);
prompt.requestPin.mockResolvedValue(null);
const service = await createService();
await expect(service.requestUnlock()).resolves.toBe(false);
expect(service.active()).toBe(true);
});
it('setupPin stores a hash, enables the feature and leaves the parent unlocked', async () => {
prompt.requestPin.mockResolvedValue('9876');
const service = await createService();
await expect(service.setupPin()).resolves.toBe(true);
TestBed.flushEffects();
expect(storage.writePinHash).toHaveBeenCalledTimes(1);
expect(storage.pinHash).not.toContain('9876');
expect(updateSettings).toHaveBeenCalledWith({
parentalLockEnabled: true,
});
expect(updateBridgeSettings).toHaveBeenCalledWith({
parentalLockEnabled: true,
});
expect(service.enabled()).toBe(true);
expect(service.unlocked()).toBe(true);
expect(service.hasPin()).toBe(true);
});
it('disable requires the PIN and keeps the locks', async () => {
storage.pinHash = await hashParentalLockPin('1234');
storage.locks = { 'p-1': { m3u: ['Adult'] } };
parentalLockEnabled.set(true);
prompt.requestPin.mockResolvedValueOnce(null);
const service = await createService();
await expect(service.disable()).resolves.toBe(false);
expect(service.enabled()).toBe(true);
prompt.requestPin.mockResolvedValueOnce('1234');
await expect(service.disable()).resolves.toBe(true);
expect(service.enabled()).toBe(false);
expect(service.lockedGroupTitles('p-1')).toEqual(['Adult']);
});
it('arms the idle timer for the session that just enabled the feature', async () => {
jest.useFakeTimers();
try {
prompt.requestPin.mockResolvedValue('9876');
parentalLockRelockMinutes.set(5);
const service = await createService();
await expect(service.setupPin()).resolves.toBe(true);
TestBed.flushEffects();
expect(service.unlocked()).toBe(true);
// `active` never changed (unlocked before and after enabling), so
// the timer must be armed by the unlocked transition itself.
jest.advanceTimersByTime(5 * 60_000 + 1_500);
TestBed.flushEffects();
expect(service.unlocked()).toBe(false);
expect(service.active()).toBe(true);
} finally {
jest.useRealTimers();
}
});
it('changePin and disable verify the stored PIN even while the session is unlocked', async () => {
storage.pinHash = await hashParentalLockPin('1234');
parentalLockEnabled.set(true);
prompt.requestPin.mockImplementation(
async (request: ParentalLockPromptRequest) =>
request.mode === 'set'
? '5678'
: (await request.verify?.('1234'))
? '1234'
: null
);
const service = await createService();
await service.requestUnlock();
TestBed.flushEffects();
expect(service.unlocked()).toBe(true);
prompt.requestPin.mockClear();
// A dismissed verification prompt aborts the change.
prompt.requestPin.mockResolvedValueOnce(null);
await expect(service.changePin()).resolves.toBe(false);
expect(prompt.requestPin).toHaveBeenCalledTimes(1);
expect(prompt.requestPin.mock.calls[0][0].mode).toBe('unlock');
expect(storage.writePinHash).not.toHaveBeenCalled();
prompt.requestPin.mockClear();
await expect(service.changePin()).resolves.toBe(true);
expect(
prompt.requestPin.mock.calls.map((call) => call[0].mode)
).toEqual(['unlock', 'set']);
expect(storage.writePinHash).toHaveBeenCalledTimes(1);
prompt.requestPin.mockClear();
prompt.requestPin.mockResolvedValueOnce(null);
await expect(service.disable()).resolves.toBe(false);
expect(service.enabled()).toBe(true);
expect(prompt.requestPin.mock.calls[0][0].mode).toBe('unlock');
});
it('persists locks per portal, stamps the Xtream column and bumps the version', async () => {
const service = await createService();
const versionBefore = service.version();
await expect(
service.setXtreamLocks('p-1', 'live', [3, 3, 9])
).resolves.toBe(true);
await expect(
service.setStalkerLocks('p-2', 'itv', ['12'])
).resolves.toBe(true);
await expect(service.setM3uLocks('p-3', ['XXX'])).resolves.toBe(true);
expect(setCategoryLocks).toHaveBeenCalledWith('p-1', 'live', [3, 9]);
expect(service.lockedXtreamIds('p-1', 'live')).toEqual([3, 9]);
expect(service.lockedXtreamIds('p-1', 'movies')).toEqual([]);
expect(service.lockedStalkerIds('p-2', 'itv')).toEqual(['12']);
expect(service.lockedGroupTitles('p-3')).toEqual(['XXX']);
expect(service.version()).toBeGreaterThan(versionBefore);
expect(storage.writeLocks).toHaveBeenCalledTimes(3);
});
it('answers "locked" only while the lock is active', async () => {
storage.pinHash = await hashParentalLockPin('1234');
storage.locks = {
'p-1': {
xtream: [{ categoryType: 'live', xtreamId: 3 }],
stalker: [{ categoryType: 'vod', categoryId: '7' }],
m3u: ['XXX'],
},
};
parentalLockEnabled.set(true);
prompt.requestPin.mockResolvedValue('1234');
const service = await createService();
expect(service.isXtreamCategoryLocked('p-1', 'live', 3)).toBe(true);
expect(service.isXtreamCategoryLocked('p-1', 'live', 4)).toBe(false);
expect(service.isStalkerCategoryLocked('p-1', 'vod', 7)).toBe(true);
expect(service.isM3uGroupLocked('p-1', 'XXX')).toBe(true);
await service.requestUnlock();
expect(service.isXtreamCategoryLocked('p-1', 'live', 3)).toBe(false);
expect(service.isM3uGroupLocked('p-1', 'XXX')).toBe(false);
});
it('replacePlaylistLocks re-stamps every Xtream type', async () => {
const service = await createService();
await service.replacePlaylistLocks('p-1', {
xtream: [{ categoryType: 'movies', xtreamId: 5 }],
stalker: [],
m3u: [],
});
expect(setCategoryLocks).toHaveBeenCalledWith('p-1', 'live', []);
expect(setCategoryLocks).toHaveBeenCalledWith('p-1', 'movies', [5]);
expect(setCategoryLocks).toHaveBeenCalledWith('p-1', 'series', []);
});
});
@@ -0,0 +1,548 @@
import {
computed,
effect,
inject,
Injectable,
signal,
untracked,
} from '@angular/core';
import {
createParentalLockPinThrottle,
hashParentalLockPin,
normalizeParentalLockRelockMinutes,
ParentalLockPlaylistLocks,
ParentalLockStalkerCategoryType,
ParentalLockXtreamCategoryType,
verifyParentalLockPin,
} from '@iptvnator/shared/interfaces';
import { RuntimeCapabilitiesService } from '../runtime-capabilities.service';
import { SettingsStore } from '../settings-store.service';
import { ParentalLockIdleTimer } from './parental-lock-idle-timer';
import {
LockListEdit,
ParentalLockLockStore,
} from './parental-lock-lock-store.service';
import {
PARENTAL_LOCK_PROMPT,
ParentalLockPromptRequest,
} from './parental-lock-prompt.token';
import {
isParentalLockWorkerFilterMissing,
ParentalLockWorkerSync,
} from './parental-lock-bridge';
import {
ensureParentalLockSettingsReadable,
persistParentalLockEnabled,
persistParentalLockRelockMinutes,
} from './parental-lock-settings-writer';
import { ParentalLockStorageService } from './parental-lock-storage';
/**
* Parental lock: hides locked categories everywhere until the PIN is
* entered.
*
* Source of truth for WHICH categories are locked is the lock store held
* here (persisted through `ParentalLockStorageService`); the Electron
* `categories.locked` column is only a query index derived from it, so the
* SQLite worker can filter reads server-side.
*
* `active` is the enforcement flag: feature enabled and no PIN entered.
* Everything that renders catalog content asks this service — the Xtream
* data sources, the Stalker store, the M3U channel list, the workspace
* rails — and re-queries when `version` changes. The unlock lives in memory
* only: a restart always locks again, and so does the idle timer.
*/
@Injectable({ providedIn: 'root' })
export class ParentalLockService {
private readonly settingsStore = inject(SettingsStore);
private readonly storage = inject(ParentalLockStorageService);
private readonly locks = inject(ParentalLockLockStore);
private readonly prompt = inject(PARENTAL_LOCK_PROMPT, { optional: true });
/**
* Electron reads Xtream through the SQLite worker, but the bridge lacks
* the lock-state or index IPC (a partial or older preload): the worker
* cannot withhold locked rows, so the locked session withholds all.
*/
private readonly workerFilterMissing = isParentalLockWorkerFilterMissing(
inject(RuntimeCapabilitiesService)
);
private readonly unlockedState = signal(false);
/** Shared by every unlock prompt: a reopened dialog keeps the cooldown. */
private readonly pinThrottle = createParentalLockPinThrottle();
private readonly pinHash = signal<string | null>(null);
/** The PIN hash could not be read; retried before PIN-protected steps. */
private readonly pinUnreadable = signal(false);
private readonly versionState = signal(0);
private readonly workerSync = new ParentalLockWorkerSync();
// The main process starts LOCKED whenever the feature is on (mirrored
// setting). Reporting our state before settings have loaded would send a
// spurious "unlocked" and open a window of unfiltered reads.
private readonly settingsReady = signal(false);
private readonly busyProbes = new Set<() => boolean>();
private readonly idleTimer = new ParentalLockIdleTimer({
onExpire: () => this.lock(),
isBusy: () => [...this.busyProbes].some((probe) => probe()),
});
private initialization: Promise<void> | null = null;
private pendingUnlock: Promise<boolean> | null = null;
/**
* The persisted feature switch could not be read (IndexedDB failure):
* `SettingsStore` then serves defaults, which would read as "off".
*/
private readonly switchUnknown = computed(
() => this.settingsStore.storageFailure?.() === 'load'
);
/**
* The feature switch from settings. While the switch is unknown a stored
* PIN stands in for it: the PIN exists only once a parent set the lock
* up, so failing toward "locked" costs one PIN entry, whereas failing
* toward "off" would expose every locked category precisely during a
* storage failure.
*/
readonly enabled = computed(() =>
this.switchUnknown()
? this.pinHash() !== null || this.pinUnreadable()
: this.settingsStore.parentalLockEnabled?.() === true
);
/** Feature on and the PIN has been entered this session. */
readonly unlocked = computed(() => this.enabled() && this.unlockedState());
/** Locked categories must currently be withheld. */
readonly active = computed(() => this.enabled() && !this.unlockedState());
/** A PIN exists; enabling is only possible once this is true. */
readonly hasPin = computed(() => this.pinHash() !== null);
/** The lock store is read and trustworthy; backups must not run without it. */
readonly locksReadable = computed(() => this.locks.readable());
/**
* Locked, and the lock store could not be read: which categories are
* locked is unknown, so EVERY category is withheld — the renderer-side
* filters treat every id as locked — until the PIN is entered or the
* store reads again. Failing toward "nothing is locked" would expose the
* protected content precisely during a storage failure.
*/
readonly withholdsEverything = computed(
() =>
this.active() &&
(this.workerFilterMissing ||
this.workerSync.failed() ||
!this.locks.readable())
);
/** Bumps whenever `active` or the lock store changes; consumers re-query. */
readonly version = computed(
() =>
this.versionState() +
this.locks.revision() +
this.workerSync.changes()
);
readonly relockMinutes = computed(() =>
normalizeParentalLockRelockMinutes(
this.settingsStore.parentalLockRelockMinutes?.()
)
);
constructor() {
// Lock edits that take a lock away need an unlocked session at the
// moment they commit, not only when their editor opened.
this.locks.setRemovalGate(() => !this.active());
effect(() => {
const active = this.active();
if (!this.settingsReady()) {
return;
}
untracked(() => {
this.versionState.update((value) => value + 1);
// Unknown switch and no PIN to stand in for it: the main
// process keeps its mirrored (locked) default rather than
// being told "unlocked" on the strength of default settings.
if (!this.switchUnknown() || this.hasPin()) {
void this.workerSync.sync(active, () => this.active());
}
});
});
// The idle timer follows the UNLOCKED transition, not `active`:
// enabling the feature from an unlocked session (setupPin) never
// changes `active`, yet that session must still lock itself later.
effect(() => {
const unlocked = this.unlocked();
const minutes = this.relockMinutes();
untracked(() => {
if (unlocked) {
this.idleTimer.arm(minutes);
} else {
this.idleTimer.disarm();
}
});
});
}
/** Loads the persisted PIN hash and lock store once. */
initialize(): Promise<void> {
if (!this.initialization) {
this.initialization = (async () => {
const [pinRead] = await Promise.all([
this.storage.readPinHash(),
this.locks.load(),
this.settingsStore.loadSettings(),
]);
this.applyPinRead(pinRead);
this.versionState.update((value) => value + 1);
this.settingsReady.set(true);
})().catch((error) => {
console.error('Failed to load the parental lock state.', error);
this.settingsReady.set(true);
});
}
return this.initialization;
}
/**
* Something that should keep the app unlocked while true, e.g. a playing
* video. Returns the unregister function.
*/
registerBusyProbe(probe: () => boolean): () => void {
this.busyProbes.add(probe);
return () => this.busyProbes.delete(probe);
}
/**
* Asks for the PIN when the lock is active. Resolves true when the app
* is unlocked afterwards (already unlocked, feature off, or the PIN was
* accepted). Concurrent callers share one prompt.
*/
async requestUnlock(
options: Pick<
ParentalLockPromptRequest,
'titleKey' | 'descriptionKey'
> = {}
): Promise<boolean> {
// `enabled` is false until the settings have loaded; deciding "not
// active" before that would open a gate during a slow startup.
await this.initialize();
if (!this.active()) {
return true;
}
// A store that failed to read at startup may read now; do not send
// the user through the PIN for categories that are not locked.
await this.locks.ensureReadable();
if (this.pendingUnlock) {
return this.pendingUnlock;
}
this.pendingUnlock = this.promptForUnlock(options).finally(() => {
this.pendingUnlock = null;
});
return this.pendingUnlock;
}
private async promptForUnlock(
options: Pick<ParentalLockPromptRequest, 'titleKey' | 'descriptionKey'>
): Promise<boolean> {
await this.ensurePin();
const hash = this.pinHash();
if (!this.prompt || !hash) {
return false;
}
const pin = await this.prompt.requestPin({
mode: 'unlock',
verify: (candidate) => verifyParentalLockPin(candidate, hash),
throttle: this.pinThrottle,
...options,
});
if (pin === null) {
return false;
}
this.unlockedState.set(true);
return true;
}
/** Locks immediately; the next locked surface needs the PIN again. */
lock(): void {
this.unlockedState.set(false);
}
/**
* Sets a new PIN through the prompt and turns the feature on. The
* parent who just typed the PIN stays unlocked. Returns whether it
* happened.
*/
async setupPin(): Promise<boolean> {
await this.initialize();
if (!this.prompt || !(await this.ensureSettingsReadable())) {
return false;
}
// Decided BEFORE the PIN is stored: with the settings switch
// unknown, `enabled` follows `hasPin`, and would read as on the
// moment the PIN lands — skipping the persistence the next launch
// depends on.
const needsPersist =
this.settingsStore.parentalLockEnabled?.() !== true;
const pin = await this.prompt.requestPin({ mode: 'set' });
if (pin === null) {
return false;
}
if (!(await this.storePin(pin))) {
return false;
}
this.unlockedState.set(true);
if (needsPersist && !(await this.persistEnabled(true))) {
this.unlockedState.set(false);
return false;
}
return true;
}
private persistEnabled(enabled: boolean): Promise<boolean> {
return persistParentalLockEnabled(this.settingsStore, enabled);
}
private ensureSettingsReadable(): Promise<boolean> {
return ensureParentalLockSettingsReadable(this.settingsStore);
}
/** Verifies the current PIN, then replaces it. */
async changePin(): Promise<boolean> {
await this.initialize();
await this.ensurePin();
if (!this.prompt || !this.hasPin()) {
return false;
}
if (!(await this.verifyCurrentPin())) {
return false;
}
const pin = await this.prompt.requestPin({ mode: 'set' });
if (pin === null) {
return false;
}
return this.storePin(pin);
}
/** Turns the feature off after the PIN was entered; locks are kept. */
async disable(): Promise<boolean> {
if (!this.enabled()) {
return true;
}
if (!(await this.verifyCurrentPin())) {
return false;
}
if (!(await this.persistEnabled(false))) {
return false;
}
this.unlockedState.set(false);
return true;
}
/**
* Always asks for the PIN, unlocked session or not: changing the PIN or
* switching the feature off must not be possible just because a parent
* left the app unlocked. Unlike `requestUnlock()` this never short-cuts
* on `active`.
*/
private async verifyCurrentPin(): Promise<boolean> {
await this.initialize();
await this.ensurePin();
const hash = this.pinHash();
if (!this.prompt || !hash) {
return false;
}
const pin = await this.prompt.requestPin({
mode: 'unlock',
verify: (candidate) => verifyParentalLockPin(candidate, hash),
throttle: this.pinThrottle,
titleKey: 'PARENTAL_LOCK.PIN_DIALOG.CONFIRM_TITLE',
descriptionKey: 'PARENTAL_LOCK.PIN_DIALOG.CONFIRM_DESCRIPTION',
});
return pin !== null;
}
/**
* False when the value could not be persisted; the in-memory patch
* `updateSettings` applied before the failed write is undone so the
* timer on screen never differs from the one the next launch uses.
*/
async setRelockMinutes(minutes: number): Promise<boolean> {
// A locked session must not lengthen or switch off its own relock
// timer (Settings disables the selector until the PIN is entered).
if (this.active()) {
return false;
}
return persistParentalLockRelockMinutes(
this.settingsStore,
minutes,
() => this.relockMinutes()
);
}
// -- Lock store (ParentalLockLockStore; predicates add `active`) -------
locksFor(playlistId: string): ParentalLockPlaylistLocks {
return this.locks.locksFor(playlistId);
}
lockedXtreamIds(
playlistId: string,
categoryType: ParentalLockXtreamCategoryType
): number[] {
return this.locks.lockedXtreamIds(playlistId, categoryType);
}
lockedStalkerIds(
playlistId: string,
categoryType: ParentalLockStalkerCategoryType
): string[] {
return this.locks.lockedStalkerIds(playlistId, categoryType);
}
lockedGroupTitles(playlistId: string): string[] {
return this.locks.lockedGroupTitles(playlistId);
}
/** Whether the category is locked AND currently withheld. */
isXtreamCategoryLocked(
playlistId: string,
categoryType: ParentalLockXtreamCategoryType,
xtreamId: number
): boolean {
return (
this.active() &&
(this.withholdsEverything() ||
this.lockedXtreamIds(playlistId, categoryType).includes(
xtreamId
))
);
}
isStalkerCategoryLocked(
playlistId: string,
categoryType: ParentalLockStalkerCategoryType,
categoryId: string | number | null | undefined
): boolean {
if (!this.active()) {
return false;
}
// Fail-closed mode withholds rows without a genre too: "unknown
// genre" is not "no locked genre" while the locks are unknown.
if (this.withholdsEverything()) {
return true;
}
if (categoryId === null || categoryId === undefined) {
return false;
}
return this.lockedStalkerIds(playlistId, categoryType).includes(
String(categoryId)
);
}
isM3uGroupLocked(playlistId: string, groupTitle: string): boolean {
return (
this.active() &&
(this.withholdsEverything() ||
this.lockedGroupTitles(playlistId).includes(groupTitle))
);
}
async setXtreamLocks(
playlistId: string,
categoryType: ParentalLockXtreamCategoryType,
xtreamIds: LockListEdit<number>
): Promise<boolean> {
await this.initialize();
return this.locks.setXtreamLocks(playlistId, categoryType, xtreamIds);
}
async setStalkerLocks(
playlistId: string,
categoryType: ParentalLockStalkerCategoryType,
categoryIds: LockListEdit<string>
): Promise<boolean> {
await this.initialize();
return this.locks.setStalkerLocks(
playlistId,
categoryType,
categoryIds
);
}
async setM3uLocks(
playlistId: string,
groupTitles: LockListEdit<string>
): Promise<boolean> {
await this.initialize();
return this.locks.setM3uLocks(playlistId, groupTitles);
}
/** Retries a failed lock-store read; false while it still fails. */
async ensureLocksReadable(): Promise<boolean> {
await this.initialize();
return this.locks.ensureReadable();
}
/** Playlist deletion: its locks leave the store. */
async removePlaylistLocks(playlistId: string): Promise<boolean> {
await this.initialize();
return this.locks.removePlaylist(playlistId);
}
/** "Remove all playlists": the whole lock store is emptied. */
async clearAllLocks(): Promise<boolean> {
await this.initialize();
return this.locks.clearAll();
}
/** Backup restore: replaces every lock of one playlist. */
async replacePlaylistLocks(
playlistId: string,
locks: ParentalLockPlaylistLocks
): Promise<boolean> {
await this.initialize();
return this.locks.replacePlaylistLocks(playlistId, locks);
}
/**
* Re-stamps the Electron `categories.locked` index for a playlist from
* the store, e.g. after a refresh recreated the rows.
*/
stampXtreamLocks(
playlistId: string,
categoryTypes?: readonly ParentalLockXtreamCategoryType[]
): Promise<boolean> {
return this.locks.stampXtreamLocks(playlistId, categoryTypes);
}
private applyPinRead(read: { hash: string | null } | null): void {
if (read === null) {
console.error('The parental lock PIN could not be read.');
this.pinUnreadable.set(true);
return;
}
this.pinHash.set(read.hash);
this.pinUnreadable.set(false);
}
/**
* Retries a PIN read that failed at startup. A failed read is not an
* absent PIN: the session stays locked (`enabled` treats it as set),
* and every PIN-protected step re-reads first so the parent can still
* unlock, change the PIN or switch the feature off once storage answers.
*/
private async ensurePin(): Promise<void> {
if (!this.pinUnreadable()) {
return;
}
this.applyPinRead(await this.storage.readPinHash());
}
private async storePin(pin: string): Promise<boolean> {
try {
const hash = await hashParentalLockPin(pin);
if (!(await this.storage.writePinHash(hash))) {
return false;
}
this.pinHash.set(hash);
this.pinUnreadable.set(false);
return true;
} catch (error) {
console.error('Failed to store the parental lock PIN.', error);
return false;
}
}
}
@@ -69,8 +69,7 @@ describe('PlaylistBackupService Xtream source pins', () => {
const backup = await service.exportBackup();
const entry = backup.manifest
.playlists[0] as XtreamPlaylistBackupEntry;
const entry = backup.manifest.playlists[0] as XtreamPlaylistBackupEntry;
// Without this every "main source" choice vanishes on restore, with
// nothing in the archive to say it was ever made.
expect(entry.userState.sourcePins).toEqual([
@@ -161,7 +160,8 @@ describe('PlaylistBackupService Xtream source pins', () => {
await Promise.all([firstImport, secondImport]);
expect(
replacePins.mock.calls.map(
([, pins]) => (pins as Array<{ contentId: number }>)[0].contentId
([, pins]) =>
(pins as Array<{ contentId: number }>)[0].contentId
)
).toEqual([501, 502]);
});
@@ -229,9 +229,11 @@ describe('PlaylistBackupService export → import round-trip', () => {
}),
]);
expect(state.epgUrls).toEqual(['https://epg.example.com/guide.xml']);
expect(
state.playlists.map((playlist) => playlist._id)
).toEqual(['m3u-1', 'xtream-1', 'stalker-1']);
expect(state.playlists.map((playlist) => playlist._id)).toEqual([
'm3u-1',
'xtream-1',
'stalker-1',
]);
// Exporting the restored state must reproduce the original
// manifest byte for byte (modulo the export timestamp): any field
@@ -14,6 +14,23 @@ describe('PlaylistBackupService', () => {
localStorage.clear();
});
it('refuses to export while the parental lock store is not readable', async () => {
const initialize = jest.fn().mockResolvedValue(undefined);
const service = createPlaylistBackupService({
parentalLock: {
initialize,
locksReadable: jest.fn(() => false),
locksFor: jest.fn(() => ({ xtream: [], stalker: [], m3u: [] })),
replacePlaylistLocks: jest.fn().mockResolvedValue(true),
},
});
await expect(service.exportBackup()).rejects.toThrow(
/parental lock store/
);
expect(initialize).toHaveBeenCalled();
});
it('exports self-contained M3U data and strips Stalker session fields', async () => {
const playlistsService = {
addPlaylist: jest.fn((playlist: Playlist) => of(playlist)),
@@ -56,18 +56,13 @@ export function createPlaylistBackupService(
? 'consumed'
: 'superseded';
}
if (
pendingSnapshot.revision !== expectedSnapshot.revision
) {
if (pendingSnapshot.revision !== expectedSnapshot.revision) {
return 'superseded';
}
await apply(pendingSnapshot.state);
if (
!pendingRestoreService.clear(
playlistId,
pendingSnapshot.state
)
!pendingRestoreService.clear(playlistId, pendingSnapshot.state)
) {
return 'consume-failed';
}
@@ -125,6 +120,14 @@ export function createPlaylistBackupService(
clearForPlaylist: jest.fn().mockResolvedValue(true),
},
pendingRestoreService,
parentalLock: {
initialize: jest.fn().mockResolvedValue(undefined),
locksReadable: jest.fn(() => true),
ensureLocksReadable: jest.fn().mockResolvedValue(true),
requestUnlock: jest.fn().mockResolvedValue(true),
locksFor: jest.fn(() => ({ xtream: [], stalker: [], m3u: [] })),
replacePlaylistLocks: jest.fn().mockResolvedValue(true),
},
...overrides,
});
+218 -16
View File
@@ -6,7 +6,10 @@ import { DatabaseService } from './database-electron.service';
import { VodSourcePinService } from './vod-source-pin.service';
import { PlaybackPositionService } from './playback-position.service';
import { XtreamPendingRestoreService } from './xtream-pending-restore.service';
import { ParentalLockService } from './parental-lock/parental-lock.service';
import { removesParentalLocks } from './parental-lock/parental-lock-store.util';
import {
isParentalLockPlaylistLocksEmpty,
isM3uRecentlyViewedItem,
normalizeXtreamPendingRestoreState,
M3uPlaylistBackupEntry,
@@ -25,6 +28,15 @@ import {
XtreamBackupSourcePin,
XtreamPendingRestoreState,
createRandomId,
isWellFormedParentalLockGroupTitles,
isWellFormedParentalLockStalkerCategories,
isWellFormedParentalLockXtreamCategories,
normalizeParentalLockGroupTitles,
normalizeParentalLockStalkerCategories,
normalizeParentalLockXtreamCategories,
ParentalLockPlaylistLocks,
StalkerBackupLockedCategory,
XtreamBackupHiddenCategory,
} from '@iptvnator/shared/interfaces';
export interface PlaylistBackupExportPayload {
@@ -65,9 +77,19 @@ export class PlaylistBackupService {
private readonly pendingRestoreService = inject(
XtreamPendingRestoreService
);
private readonly parentalLock = inject(ParentalLockService);
private backupImportTail?: Promise<void>;
async exportBackup(): Promise<PlaylistBackupExportPayload> {
// Locks are written only when present, and an absent field means
// "no opinion" on restore — so an export must never run against an
// empty in-memory store that merely has not loaded, or could not.
await this.parentalLock.initialize();
if (!this.parentalLock.locksReadable()) {
throw new Error(
'The parental lock store could not be read; the backup would omit its locks.'
);
}
const playlists = await firstValueFrom(
this.playlistsService.getAllData()
);
@@ -96,9 +118,9 @@ export class PlaylistBackupService {
}
importBackup(json: string): Promise<PlaylistBackupImportSummary> {
const importResult = (
this.backupImportTail ?? Promise.resolve()
).then(() => this.executeImportBackup(json));
const importResult = (this.backupImportTail ?? Promise.resolve()).then(
() => this.executeImportBackup(json)
);
this.backupImportTail = importResult.then(
() => undefined,
() => undefined
@@ -110,6 +132,24 @@ export class PlaylistBackupService {
json: string
): Promise<PlaylistBackupImportSummary> {
const manifest = this.parseManifest(json);
// A backup carrying lock lists REPLACES the matching playlists'
// locks, possibly with an emptier set: that is a lock edit, and lock
// edits sit behind the PIN. Asked here, after the file was chosen.
const carriesLocks = manifest.playlists.some((entry) => {
const state = entry.userState as {
lockedCategories?: unknown;
lockedGroupTitles?: unknown;
};
return (
state?.lockedCategories !== undefined ||
state?.lockedGroupTitles !== undefined
);
});
if (carriesLocks && !(await this.parentalLock.requestUnlock())) {
throw new PlaylistBackupError(
'Enter the parental PIN to restore a backup that carries parental locks.'
);
}
const existingPlaylists = await firstValueFrom(
this.playlistsService.getAllData()
);
@@ -167,6 +207,11 @@ export class PlaylistBackupService {
await this.restoreXtreamEntry(targetId, entry);
}
// Last: a failed Xtream restore above must leave the
// playlist's previous locks in place rather than commit the
// backup's (possibly smaller) lock set for a failed merge.
await this.restoreParentalLocks(targetId, entry, isMerge);
if (isMerge) {
summary.merged += 1;
} else {
@@ -243,6 +288,7 @@ export class PlaylistBackupService {
? playlist.hiddenGroupTitles
: []
),
...this.optionalLockedGroupTitles(playlist._id),
},
};
}
@@ -269,6 +315,7 @@ export class PlaylistBackupService {
favorites: [],
recentlyViewed: [],
playbackPositions: [],
...this.optionalLockedXtreamCategories(playlist._id),
// NOT `[]`. Pins are Electron-only, so out here we cannot
// read them — which is not the same as knowing there are
// none. Restore treats the collection as authoritative and
@@ -321,6 +368,7 @@ export class PlaylistBackupService {
...this.mapHiddenCategories(movieCategories, 'movies'),
...this.mapHiddenCategories(seriesCategories, 'series'),
],
...this.optionalLockedXtreamCategories(playlist._id),
favorites: favorites.map((item) => ({
xtreamId: item.xtream_id,
contentType: item.type as XtreamContentType,
@@ -416,6 +464,7 @@ export class PlaylistBackupService {
: {}),
},
userState: {
...this.optionalLockedStalkerCategories(playlist._id),
favorites: this.extractStalkerItems(playlist.favorites),
recentlyViewed: this.extractStalkerItems(
playlist.recentlyViewed
@@ -502,6 +551,19 @@ export class PlaylistBackupService {
`M3U backup "${entry.title}" is missing raw playlist data.`
);
}
// Restore replaces the playlist's locks with the archive's,
// and the normalizer drops what it does not understand — a
// damaged lock list would erase the persisted protection.
if (
entry.userState?.lockedGroupTitles !== undefined &&
!isWellFormedParentalLockGroupTitles(
entry.userState.lockedGroupTitles
)
) {
throw new PlaylistBackupError(
`M3U backup "${entry.title}" has invalid parental locks.`
);
}
break;
case 'xtream':
if (
@@ -529,6 +591,17 @@ export class PlaylistBackupService {
);
}
if (
entry.userState.lockedCategories !== undefined &&
!isWellFormedParentalLockXtreamCategories(
entry.userState.lockedCategories
)
) {
throw new PlaylistBackupError(
`Xtream backup "${entry.title}" has invalid parental locks.`
);
}
// Absent in archives written before multi-source existed, so
// its absence is not damage — only a wrong type is.
if (
@@ -549,6 +622,16 @@ export class PlaylistBackupService {
`Stalker backup "${entry.title}" is missing connection metadata.`
);
}
if (
entry.userState?.lockedCategories !== undefined &&
!isWellFormedParentalLockStalkerCategories(
entry.userState.lockedCategories
)
) {
throw new PlaylistBackupError(
`Stalker backup "${entry.title}" has invalid parental locks.`
);
}
break;
default:
throw new PlaylistBackupError(
@@ -706,11 +789,12 @@ export class PlaylistBackupService {
playlistId: string,
existing: Playlist | null
): Promise<Playlist> {
const parsedPlaylist = await this.playlistsService.handlePlaylistParsing(
'TEXT',
entry.source.rawM3u,
entry.title
);
const parsedPlaylist =
await this.playlistsService.handlePlaylistParsing(
'TEXT',
entry.source.rawM3u,
entry.title
);
const now = new Date().toISOString();
return {
@@ -829,7 +913,6 @@ export class PlaylistBackupService {
});
}
private async restoreXtreamEntry(
playlistId: string,
entry: XtreamPlaylistBackupEntry
@@ -859,13 +942,12 @@ export class PlaylistBackupService {
return;
}
const restoreResult =
await this.pendingRestoreService.applyAndConsume(
playlistId,
restoreSnapshot,
(pendingState) =>
this.applyXtreamRestoreState(playlistId, pendingState)
);
const restoreResult = await this.pendingRestoreService.applyAndConsume(
playlistId,
restoreSnapshot,
(pendingState) =>
this.applyXtreamRestoreState(playlistId, pendingState)
);
if (restoreResult !== 'consumed') {
throw new PlaylistBackupError(
`Clearing pending restore state for "${playlistId}" failed.`
@@ -1011,6 +1093,126 @@ export class PlaylistBackupService {
}
}
// Parental locks are written only when the playlist has some: an archive
// without the field says nothing about locks (older builds wrote none),
// so an unlocked playlist stays byte-identical to a pre-lock export.
private optionalLockedXtreamCategories(playlistId: string): {
lockedCategories?: XtreamBackupHiddenCategory[];
} {
const locked = this.parentalLock
.locksFor(playlistId)
.xtream.map((entry) => ({
categoryType: entry.categoryType,
xtreamId: entry.xtreamId,
}));
return locked.length > 0 ? { lockedCategories: locked } : {};
}
private optionalLockedStalkerCategories(playlistId: string): {
lockedCategories?: StalkerBackupLockedCategory[];
} {
const locked = this.parentalLock
.locksFor(playlistId)
.stalker.map((entry) => ({ ...entry }));
return locked.length > 0 ? { lockedCategories: locked } : {};
}
private optionalLockedGroupTitles(playlistId: string): {
lockedGroupTitles?: string[];
} {
// Exact titles: M3U locks match `channel.group.title` verbatim, so
// the trimming `uniqueStrings` would turn a lock on " Adult " into
// one on "Adult" and weaken the restored lock.
const locked = normalizeParentalLockGroupTitles(
this.parentalLock.locksFor(playlistId).m3u
);
return locked.length > 0 ? { lockedGroupTitles: locked } : {};
}
/**
* Parental locks travel next to the hidden state of each entry. Absent
* fields mean the archive predates the lock (or was written by a build
* that could not read it) and leave the playlist's locks alone.
*/
private async restoreParentalLocks(
playlistId: string,
entry: PlaylistBackupEntry,
isMerge: boolean
): Promise<void> {
// The stale-id check below and the merge base both read the store; an
// empty fail-closed snapshot would let a reused id keep a deleted
// playlist's locks once a later read recovers them.
if (!(await this.parentalLock.ensureLocksReadable())) {
throw new PlaylistBackupError(
`Restoring the parental locks for "${playlistId}" failed: the lock store could not be read.`
);
}
// A playlist created by this restore owns no locks yet: whatever the
// store holds under a reused id belongs to a deleted playlist (a
// cleanup that failed), and must not be inherited.
const current = isMerge
? this.parentalLock.locksFor(playlistId)
: { xtream: [], stalker: [], m3u: [] };
const staleOnNewId =
!isMerge &&
!isParentalLockPlaylistLocksEmpty(
this.parentalLock.locksFor(playlistId)
);
let next: ParentalLockPlaylistLocks | null = staleOnNewId
? current
: null;
if (entry.portalType === 'm3u') {
const titles = entry.userState.lockedGroupTitles;
if (Array.isArray(titles)) {
next = {
...current,
m3u: normalizeParentalLockGroupTitles(titles),
};
}
} else if (entry.portalType === 'xtream') {
const categories = entry.userState.lockedCategories;
if (Array.isArray(categories)) {
next = {
...current,
xtream: normalizeParentalLockXtreamCategories(categories),
};
}
} else if (Array.isArray(entry.userState.lockedCategories)) {
next = {
...current,
stalker: normalizeParentalLockStalkerCategories(
entry.userState.lockedCategories
),
};
}
// Taking a lock away needs an unlocked session when it commits. The
// PIN asked at the start may be stale by now (idle relock or "Lock
// now" during a long import): ask again if the session relocked.
// A restore that only adds locks is not asked.
if (
next &&
removesParentalLocks(
this.parentalLock.locksFor(playlistId),
next
) &&
!(await this.parentalLock.requestUnlock())
) {
throw new PlaylistBackupError(
`Restoring the parental locks for "${playlistId}" needs the parental PIN: the app locked again during the restore.`
);
}
if (
next &&
!(await this.parentalLock.replacePlaylistLocks(playlistId, next))
) {
throw new PlaylistBackupError(
`Restoring the parental locks for "${playlistId}" failed.`
);
}
}
private mapHiddenCategories(
categories: Array<{
hidden: boolean;
@@ -41,8 +41,7 @@ describe('PlaylistBackupService Xtream hidden categories (issue #1017)', () => {
const backup = await service.exportBackup();
const entry = backup.manifest
.playlists[0] as XtreamPlaylistBackupEntry;
const entry = backup.manifest.playlists[0] as XtreamPlaylistBackupEntry;
const expectedHiddenCategories = [
{ categoryType: 'live', xtreamId: 101 },
{ categoryType: 'movies', xtreamId: 201 },
@@ -92,9 +91,7 @@ describe('PlaylistBackupService Xtream hidden categories (issue #1017)', () => {
'xtream-1',
expect.objectContaining({
state: expect.objectContaining({
hiddenCategories: [
{ categoryType: 'live', xtreamId: 101 },
],
hiddenCategories: [{ categoryType: 'live', xtreamId: 101 }],
}),
}),
expect.any(Function)
@@ -107,11 +104,151 @@ describe('PlaylistBackupService Xtream hidden categories (issue #1017)', () => {
);
});
it('keeps the previous locks when the Xtream part of a merge fails', async () => {
const collaborators = createRestoreCollaborators();
const replacePlaylistLocks = jest.fn().mockResolvedValue(true);
const service = createPlaylistBackupService({
...collaborators,
parentalLock: {
initialize: jest.fn().mockResolvedValue(undefined),
locksReadable: jest.fn(() => true),
ensureLocksReadable: jest.fn().mockResolvedValue(true),
requestUnlock: jest.fn().mockResolvedValue(true),
locksFor: jest.fn(() => ({ xtream: [], stalker: [], m3u: [] })),
replacePlaylistLocks,
},
});
collaborators.databaseService.updateCategoryVisibility.mockRejectedValue(
new Error('SQLITE_BUSY')
);
const summary = await service.importBackup(
JSON.stringify(createXtreamManifest([]))
);
expect(summary.failed).toBe(1);
expect(replacePlaylistLocks).not.toHaveBeenCalled();
});
it('never lets a newly created playlist inherit stale locks under a reused id', async () => {
const collaborators = createRestoreCollaborators();
// Empty library: the restore CREATES the playlist (no merge match).
collaborators.playlistsService.getAllData.mockReturnValue(of([]));
const replacePlaylistLocks = jest.fn().mockResolvedValue(true);
const service = createPlaylistBackupService({
...collaborators,
parentalLock: {
initialize: jest.fn().mockResolvedValue(undefined),
locksReadable: jest.fn(() => true),
ensureLocksReadable: jest.fn().mockResolvedValue(true),
requestUnlock: jest.fn().mockResolvedValue(true),
// A failed cleanup left locks under the id the restore reuses.
locksFor: jest.fn(() => ({
xtream: [{ categoryType: 'live', xtreamId: 1 }],
stalker: [],
m3u: [],
})),
replacePlaylistLocks,
},
});
const manifest = createXtreamManifest([]);
delete (
manifest.playlists[0].userState as { lockedCategories?: unknown }
).lockedCategories;
await service.importBackup(JSON.stringify(manifest));
expect(replacePlaylistLocks).toHaveBeenCalledWith(expect.any(String), {
xtream: [],
stalker: [],
m3u: [],
});
});
it('asks for the PIN before restoring lock lists and aborts when it is refused', async () => {
const collaborators = createRestoreCollaborators();
const requestUnlock = jest.fn().mockResolvedValue(false);
const replacePlaylistLocks = jest.fn().mockResolvedValue(true);
const service = createPlaylistBackupService({
...collaborators,
parentalLock: {
initialize: jest.fn().mockResolvedValue(undefined),
locksReadable: jest.fn(() => true),
ensureLocksReadable: jest.fn().mockResolvedValue(true),
requestUnlock,
locksFor: jest.fn(() => ({ xtream: [], stalker: [], m3u: [] })),
replacePlaylistLocks,
},
});
const manifest = createXtreamManifest([]);
(
manifest.playlists[0].userState as { lockedCategories?: unknown }
).lockedCategories = [];
await expect(
service.importBackup(JSON.stringify(manifest))
).rejects.toThrow(/parental PIN/);
expect(requestUnlock).toHaveBeenCalled();
expect(replacePlaylistLocks).not.toHaveBeenCalled();
expect(
collaborators.playlistsService.addPlaylist
).not.toHaveBeenCalled();
});
it('asks again before a merge replaces locks once the app relocked mid-import', async () => {
const collaborators = createRestoreCollaborators();
// Accepted at the start, refused after an idle relock or "Lock now"
// landed while the import was running.
const requestUnlock = jest
.fn()
.mockResolvedValueOnce(true)
.mockResolvedValue(false);
const replacePlaylistLocks = jest.fn().mockResolvedValue(true);
const service = createPlaylistBackupService({
...collaborators,
parentalLock: {
initialize: jest.fn().mockResolvedValue(undefined),
locksReadable: jest.fn(() => true),
ensureLocksReadable: jest.fn().mockResolvedValue(true),
requestUnlock,
locksFor: jest.fn(() => ({
xtream: [{ categoryType: 'live', xtreamId: 1 }],
stalker: [],
m3u: [],
})),
replacePlaylistLocks,
},
});
const manifest = createXtreamManifest([]);
(
manifest.playlists[0].userState as { lockedCategories?: unknown }
).lockedCategories = [];
const summary = await service.importBackup(JSON.stringify(manifest));
expect(requestUnlock).toHaveBeenCalledTimes(2);
expect(replacePlaylistLocks).not.toHaveBeenCalled();
expect(summary).toEqual(
expect.objectContaining({ merged: 0, failed: 1 })
);
expect(summary.errors[0]).toMatch(/locked again/);
});
it('rejects a damaged parental lock list instead of erasing the persisted locks', async () => {
const collaborators = createRestoreCollaborators();
const service = createPlaylistBackupService(collaborators);
const manifest = createXtreamManifest([]);
(
manifest.playlists[0].userState as { lockedCategories?: unknown }
).lockedCategories = [{}];
await expect(
service.importBackup(JSON.stringify(manifest))
).rejects.toThrow(/invalid parental locks/);
expect(
collaborators.databaseService.updateCategoryVisibility
).not.toHaveBeenCalled();
});
it('rejects entries with missing user-state collections instead of wiping user data', async () => {
const collaborators = createRestoreCollaborators();
@@ -121,9 +258,8 @@ describe('PlaylistBackupService Xtream hidden categories (issue #1017)', () => {
// treated as an authoritative "empty" state: the merge path would
// unhide every category and delete favorites/recent/positions.
const manifest = createXtreamManifest([]);
delete (
manifest.playlists[0] as unknown as { userState?: unknown }
).userState;
delete (manifest.playlists[0] as unknown as { userState?: unknown })
.userState;
await expect(
service.importBackup(JSON.stringify(manifest))
@@ -20,6 +20,16 @@ describe('RuntimeCapabilitiesService', () => {
expect(service.supportsPortalConnectivityGuard).toBe(false);
});
it('offers the parental lock worker filter only with both bridge methods', () => {
const service = new RuntimeCapabilitiesService();
testWindow.electron = { setParentalLockState: jest.fn() };
expect(service.supportsParentalLockSqliteFilter).toBe(false);
testWindow.electron['dbSetCategoryLocks'] = jest.fn();
expect(service.supportsParentalLockSqliteFilter).toBe(true);
testWindow.electron = undefined;
expect(service.supportsParentalLockSqliteFilter).toBe(false);
});
it('reports browser PWA capabilities when the Electron bridge is absent', () => {
testWindow.electron = undefined;
@@ -180,6 +180,19 @@ export class RuntimeCapabilitiesService {
].every((methodName) => this.hasElectronMethod(methodName));
}
/**
* The worker-side parental lock filter: the lock state reaches the
* SQLite worker and the `categories.locked` index can be stamped. When
* the Xtream SQLite data source is used without it, the worker cannot
* withhold locked rows and the lock service fails closed instead.
*/
get supportsParentalLockSqliteFilter(): boolean {
return (
this.hasElectronMethod('setParentalLockState') &&
this.hasElectronMethod('dbSetCategoryLocks')
);
}
get supportsXtreamSqliteDataSource(): boolean {
return [
'dbGetPlaylist',
@@ -0,0 +1,115 @@
import {
DEFAULT_DASHBOARD_RAILS_SETTINGS,
DEFAULT_PARENTAL_LOCK_RELOCK_MINUTES,
DEFAULT_TMDB_SETTINGS,
Language,
Settings,
StartupBehavior,
StreamFormat,
Theme,
VideoPlayer,
} from '@iptvnator/shared/interfaces';
/** Defaults and boot-time helpers of `SettingsStore`, split out for size. */
export const DEFAULT_SETTINGS: Settings = {
player: VideoPlayer.VideoJs,
webPlayerSharedControls: true,
playerAmbientMode: false,
playerUpNextRail: true,
fullscreenChannelPanel: true,
vodAutoFailover: false,
m3uVodDetails: true,
streamFormat: StreamFormat.AutoStreamFormat,
openStreamOnDoubleClick: false,
language: Language.ENGLISH,
showCaptions: false,
showDashboard: true,
startupBehavior: StartupBehavior.FirstView,
startupWindowMode: 'normal',
updateChannel: 'stable',
showExternalPlaybackBar: true,
stripCountryPrefix: false,
theme: Theme.SystemTheme,
mpvPlayerPath: '',
mpvPlayerArguments: '',
mpvReuseInstance: false,
vlcPlayerPath: '',
vlcPlayerArguments: '',
vlcReuseInstance: false,
remoteControl: false,
remoteControlPort: 8765,
epgUrl: [],
downloadFolder: '',
recordingFolder: '',
embeddedMpvFrameCopy: false,
embeddedMpvExtraOptions: '',
embeddedMpvAutoReconnect: true,
portalConnectivityGuard: true,
coverSize: 'medium',
showCoverTitles: true,
epgViewMode: 'timeline',
epgOffsetMinutes: 0,
dashboardRails: DEFAULT_DASHBOARD_RAILS_SETTINGS,
preferUploadedEpgOverXtream: false,
trustedPrivateNetworkEpgUrls: [],
trustedInsecureTlsHosts: [],
tmdb: DEFAULT_TMDB_SETTINGS,
parentalLockEnabled: false,
parentalLockRelockMinutes: DEFAULT_PARENTAL_LOCK_RELOCK_MINUTES,
};
/**
* Which half of the settings persistence round-trip failed, if any.
*
* Settings live in the renderer's IndexedDB, which can be unavailable for
* reasons the app cannot control (a second instance holding the Chromium
* storage lock, a corrupted profile, storage blocked by security software).
* Both failures used to be swallowed: `updateSettings` patches the in-memory
* state before persisting, so a failed write still looked applied until the
* next restart (issue #1156). Recording the failure lets the settings UI say
* so instead of pretending the change stuck.
*/
export type SettingsStorageFailure = 'load' | 'save';
export interface SettingsStorageState {
storageFailure: SettingsStorageFailure | null;
}
let embeddedMpvPrepareScheduled = false;
export function scheduleEmbeddedMpvPrepare(): void {
if (
embeddedMpvPrepareScheduled ||
typeof window === 'undefined' ||
!window.electron?.prepareEmbeddedMpv
) {
return;
}
embeddedMpvPrepareScheduled = true;
const prepare = () => {
void window.electron
.prepareEmbeddedMpv?.()
.then((support) => {
if (!support?.supported) {
embeddedMpvPrepareScheduled = false;
}
})
.catch((error) => {
embeddedMpvPrepareScheduled = false;
console.warn('Failed to prepare embedded MPV.', error);
});
};
const idleWindow = window as typeof window & {
requestIdleCallback?: (
callback: IdleRequestCallback,
options?: IdleRequestOptions
) => number;
};
if (idleWindow.requestIdleCallback) {
idleWindow.requestIdleCallback(prepare, { timeout: 5000 });
} else {
window.setTimeout(prepare, 2000);
}
}
+33 -99
View File
@@ -32,109 +32,18 @@ import {
normalizeAppUpdateChannel,
normalizeEpgOffsetMinutes,
normalizeDashboardRailsSettings,
normalizeParentalLockRelockMinutes,
normalizeStartupWindowMode,
DEFAULT_PARENTAL_LOCK_RELOCK_MINUTES,
} from '@iptvnator/shared/interfaces';
const DEFAULT_SETTINGS: Settings = {
player: VideoPlayer.VideoJs,
webPlayerSharedControls: true,
playerAmbientMode: false,
playerUpNextRail: true,
fullscreenChannelPanel: true,
vodAutoFailover: false,
m3uVodDetails: true,
streamFormat: StreamFormat.AutoStreamFormat,
openStreamOnDoubleClick: false,
language: Language.ENGLISH,
showCaptions: false,
showDashboard: true,
startupBehavior: StartupBehavior.FirstView,
startupWindowMode: 'normal',
updateChannel: 'stable',
showExternalPlaybackBar: true,
stripCountryPrefix: false,
theme: Theme.SystemTheme,
mpvPlayerPath: '',
mpvPlayerArguments: '',
mpvReuseInstance: false,
vlcPlayerPath: '',
vlcPlayerArguments: '',
vlcReuseInstance: false,
remoteControl: false,
remoteControlPort: 8765,
epgUrl: [],
downloadFolder: '',
recordingFolder: '',
embeddedMpvFrameCopy: false,
embeddedMpvExtraOptions: '',
embeddedMpvAutoReconnect: true,
portalConnectivityGuard: true,
coverSize: 'medium',
showCoverTitles: true,
epgViewMode: 'timeline',
epgOffsetMinutes: 0,
dashboardRails: DEFAULT_DASHBOARD_RAILS_SETTINGS,
preferUploadedEpgOverXtream: false,
trustedPrivateNetworkEpgUrls: [],
trustedInsecureTlsHosts: [],
tmdb: DEFAULT_TMDB_SETTINGS,
};
import {
DEFAULT_SETTINGS,
scheduleEmbeddedMpvPrepare,
SettingsStorageState,
} from './settings-store.defaults';
/**
* Which half of the settings persistence round-trip failed, if any.
*
* Settings live in the renderer's IndexedDB, which can be unavailable for
* reasons the app cannot control (a second instance holding the Chromium
* storage lock, a corrupted profile, storage blocked by security software).
* Both failures used to be swallowed: `updateSettings` patches the in-memory
* state before persisting, so a failed write still looked applied until the
* next restart (issue #1156). Recording the failure lets the settings UI say
* so instead of pretending the change stuck.
*/
export type SettingsStorageFailure = 'load' | 'save';
interface SettingsStorageState {
storageFailure: SettingsStorageFailure | null;
}
let embeddedMpvPrepareScheduled = false;
function scheduleEmbeddedMpvPrepare(): void {
if (
embeddedMpvPrepareScheduled ||
typeof window === 'undefined' ||
!window.electron?.prepareEmbeddedMpv
) {
return;
}
embeddedMpvPrepareScheduled = true;
const prepare = () => {
void window.electron
.prepareEmbeddedMpv?.()
.then((support) => {
if (!support?.supported) {
embeddedMpvPrepareScheduled = false;
}
})
.catch((error) => {
embeddedMpvPrepareScheduled = false;
console.warn('Failed to prepare embedded MPV.', error);
});
};
const idleWindow = window as typeof window & {
requestIdleCallback?: (
callback: IdleRequestCallback,
options?: IdleRequestOptions
) => number;
};
if (idleWindow.requestIdleCallback) {
idleWindow.requestIdleCallback(prepare, { timeout: 5000 });
} else {
window.setTimeout(prepare, 2000);
}
}
export type { SettingsStorageFailure } from './settings-store.defaults';
export const SettingsStore = signalStore(
{ providedIn: 'root' },
@@ -180,6 +89,12 @@ export const SettingsStore = signalStore(
dashboardRails: normalizeDashboardRailsSettings(
storedSettings.dashboardRails
),
parentalLockEnabled:
storedSettings.parentalLockEnabled === true,
parentalLockRelockMinutes:
normalizeParentalLockRelockMinutes(
storedSettings.parentalLockRelockMinutes
),
});
void this.sanitizeEmbeddedMpvSelection().catch(
(error) => {
@@ -232,6 +147,20 @@ export const SettingsStore = signalStore(
),
}
: {}),
...(settings.parentalLockEnabled !== undefined
? {
parentalLockEnabled:
settings.parentalLockEnabled === true,
}
: {}),
...(settings.parentalLockRelockMinutes !== undefined
? {
parentalLockRelockMinutes:
normalizeParentalLockRelockMinutes(
settings.parentalLockRelockMinutes
),
}
: {}),
});
// Save the complete settings object, not just the partial update
const completeSettings = this.getSettings();
@@ -344,6 +273,11 @@ export const SettingsStore = signalStore(
store.trustedInsecureTlsHosts?.() ??
DEFAULT_SETTINGS.trustedInsecureTlsHosts,
tmdb: store.tmdb?.() ?? DEFAULT_SETTINGS.tmdb,
parentalLockEnabled: store.parentalLockEnabled?.() === true,
parentalLockRelockMinutes:
normalizeParentalLockRelockMinutes(
store.parentalLockRelockMinutes?.()
),
};
},