diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 4721aee5..0570b4cb 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -3,7 +3,7 @@ name: Bug report about: Create a report to help us improve title: "" labels: "" -assignees: Sp5rky +assignees: imSp4rky --- **Describe the bug** @@ -57,7 +57,7 @@ Add any other context about the problem here. --- -**⚠️ Important:** +**Important:** - **DO NOT include service-specific implementation code** unless you have explicit rights to share it - **DO NOT share credentials, API keys, WVD files, or authentication tokens** diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 2f3d79e1..32605565 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -3,7 +3,7 @@ name: Feature request about: Suggest an idea for this project title: "" labels: "" -assignees: Sp5rky +assignees: imSp4rky --- **Feature Category** @@ -49,5 +49,5 @@ Add any other context or screenshots about the feature request here. --- -**⚠️ Note:** +**Note:** This project focuses on the core framework and tooling. Service-specific feature requests should focus on what the framework should support, not specific service implementations. diff --git a/CHANGELOG.md b/CHANGELOG.md index 070b4423..3b526a6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,267 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm This changelog is automatically generated using [git-cliff](https://git-cliff.org). +## [6.0.0] - 2026-10-13 + +### Features + +- *binary*: Add custom binary registration for services +- *cdm*: Send license_type and privacy_mode with the request to the server +- *click*: Change the minimum time for slow +- *downloader*: Adaptive worker scaling, tail boost, session parity, resume fixes +- *downloader*: Fan large segment batches across worker processes +- *downloader*: Resume failed downloads from completed segments across runs +- *dl*: Run user post-download scripts with metadata variables +- *dl*: Add --require-audio/--require-video and --warn-only alias +- *drm*: Let a track pin the DRM system it licenses with +- *dl*: Add --no-attachments to skip cover art and subtitle fonts +- *dl*: Add --cdm to pin one CDM device for a run +- *post-scripts*: Add wait option to block until the script exits +- *post-scripts*: Show a spinner while waiting for a script +- *services*: Add services_repo_force and compact refresh output +- *serve*: Hot-reload service repos on a timer without a restart +- *serve*: Gate server_cdm per service and let clients follow it +- *kv*: Show a progress bar while adding keys to a vault +- *serve*: [**breaking**] Gate the server's own proxies behind server_proxy +- *vaults*: Batch HTTP json vault writes with InsertKeys +- *remote*: Forward HLS segment filters to remote clients +- *serve*: Add --quiet mode and developer dashboard API +- *serve*: [**breaking**] Add server-held accounts for remote sessions +- *serve*: Forward per-session service logs to remote-dl clients +- *proxy*: Mask proxy credentials in console and API output +- *remote*: Spoof a type-only CDM so server_cdm clients need no local .wvd/.prd +- *serve*: Add operator dashboard endpoints and per-key rate limits +- *audio*: Support DTS:X Profile 2 with MP4 muxing +- *dl*: Add --no-postscript to skip post-scripts for one run +- *api*: Report the live title and the client's command line to the dashboard +- *vaults*: Flag and skip wrong content keys from poisoned vaults +- *remote*: Verify server-CDM vault keys on the client and report bad pairs +- *dl*: Add --proxy-download for a separate download proxy +- *vaults*: Report bad keys to the vault that served them +- *service*: Add GEOBLOCK negative geofence +- *dash*: Add merge_segments to append segments during the download +- *manifests*: Extend merge_segments rolling merge to HLS and ISM +- *export*: Write mediaexport files and read legacy exports through the package +- *proxies*: Add Control D proxy provider +- *export*: Record each track's KIDs +- *import*: Build tracks from direct-file export rows +- *export*: Name export files after their titles and tracks +- *export*: Separate export file name parts with dots +- *remote*: Keep slow remote session requests alive with a heartbeat +- *remote*: Cap server CDM licensing by height per API key and service +- *remote*: List only configured services on the dashboard +- *serve*: Relay service prompts from download jobs to the REST client +- *remote*: Let a remote client license with its own device identity +- *dl*: Add --latest-episodes N to download the N newest episodes +- *setup*: Add unshackle setup command and cross-platform install scripts +- *remote*: License with the client's device when the user picked one +- *dl*: Add --all-drm to license Widevine and PlayReady per track +- *dl*: Add --audio-description-only and --forced-subs-only +- *serve*: Log CDM calls for the dashboard +- *serve*: Reload unshackle.yaml on SIGHUP without a restart +- *serve*: Add --cdm-only for a CDM backend with no REST API +- *service*: Add wait_for_approval and return the cache for a login with no prompt +- *serve*: Relay approval messages to jobs and proxy remote downloads +- *search*: Add ANONYMOUS_SEARCH to skip the login for a service +- *dl*: Add --sample and --include-sample +- *dl*: Load the DRM system a cdm entry lists first +- *api*: Forward exact_lang to the service context + +### Bug Fixes + +- *downloader*: Release hedge loser file handles before merge sweep +- *downloader*: Validate 206 on byte-range segments and force identity encoding +- *downloader*: Stop leaked racers holding segment handles after a failed batch +- *dash*: License ClearKeyCENC before decrypt +- *subtitle*: Convert ASS to SRT in the SDH-strip fallback +- *api*: Keep sub_format "original" working through the API +- *webvtt*: Don't shorten cues when splicing boundary duplicates +- *api*: Reject backslash traversal in safe_cache_key +- *downloader*: Honor Retry-After with cancel-safe backoff, add fault-injection bench and tests +- *downloader*: Keep speed-limited batches in a single process +- *downloader*: Fail closed on rnet content codings outside the old allowlist +- *downloader*: Accept a 200 whose body is exactly the requested byte-range slice +- *downloader*: Report rolling speed on the multiprocess progress bar +- *downloaders*: Submit segments in a window so progress can drain +- *api*: Pass adaptive_workers and download_processes to dl.result +- *downloader*: Validate Content-Range before placing 206 bytes +- *downloader*: Harden ranged reads, teardown and multiprocess sessions +- *titles*: Drop folder {year?} when it repeats the dated season label +- *cli*: Work around rich-click's patched click classes +- *vaults*: Look tables up by the name the vault stores +- *hls*: Keep ad-filtered segments out of DRM key state +- *music*: Remux songs into the container of their codec +- *api*: Survive Windows errno 13 on the job progress file +- *api*: Guard two more Windows errno 13 paths in the serve layer +- *dl*: Accept a clamped 206 and report audio-description-only titles +- *services*: Match service aliases without case +- *downloader*: Keep retrying while a cut connection makes progress +- *downloader*: Bound requests after a cut and stop retry nesting +- *subtitle*: Keep WebVTT-only cue markup out of converted subtitles +- *proxies*: Resolve windscribevpn hostname prefixes and uk alias +- *mux*: Give each parallel mux its own chapters temp file +- *remote*: Carry the full title and track state across the remote API +- *HTTP*: Simplify key retrieval condition in get_key method +- *tracks*: Match resolutions per range and codec +- *remote*: Resolve service names against the remote server +- *remote*: Send only the active profile's cache files to the server +- *utils*: Preserve _ssl_context when copying SSLCiphers adapter +- *util*: Remove : +- *cli*: Show banner when dl -q is used +- *serve*: License multi-key PlayReady through server CDM instead of vault subset +- *remote*: Raise GET timeout to 120s so large catalogs load +- *cdm*: Scope remote CDM licence state to its session +- *remote*: Pass fallback language to ISM re-parse +- *ism*: Signal Dolby Vision and Atmos from Smooth manifests +- *dash*: Number SegmentTimeline segments from startNumber +- *remote*: Match re-parsed manifest tracks by ID before attributes +- *remote*: Send per-track MPD fragments for service-built AdaptationSets +- *dl*: Repair damaged cookie files without rewriting them +- *kv*: Keep copy log rows single-spaced +- *dl*: Fall back to local vaults when the server CDM returns no key +- *cli*: Stop service tags from renaming CLI options +- *dl*: Log vault writes under their own title +- *dl*: Specify 'subtitle tracks' in error log message +- *remote*: Keep option choices and optional title in remote -h +- *audio*: Accept immersive channel layouts like 5.1.4 +- *serve*: Resolve DRM keys for manifests with no ContentProtection PSSH +- *dl*: Reject local proxies when --remote targets another machine +- *dl*: End a cancelled track by raising instead of returning short +- *services*: Name the build a compiled service is missing +- *serve*: Lock shared session state and throttle progress writes +- *downloader*: Correct truncation, ranged sizing, and session carry +- *dl*: Cache server-CDM keys to the local vaults +- *drm*: License every PlayReady header until all KIDs are covered +- *dash*: Treat a missing FFprobe as no PSSH instead of crashing +- *api*: License every PlayReady header in the server CDM path +- *api*: Reach every PlayReady header on all server CDM routes +- *api*: Let the server CDM see service-supplied keys and HLS track DRM +- *api*: Tell the service that the client sent a cookie jar +- *api*: Stop serve leaking server credentials, paths, and cross-tenant data +- *api*: Keep error URLs readable and mask host paths in dashboard logs +- *api*: Reject a NUL byte in output_dir before resolving it +- *manifests*: Flag DASH audio using the standard description role +- *api*: Serialize the job progress replace to stop Windows errno 13 +- *api*: Decode challenge bytes to UTF-8 for PlayReady license request +- *proxy*: Check the proxy exit IP before any service request +- *cookies*: Find Firefox profiles in the XDG config directory +- *naming*: Correct language tag rule matching and add state conditions +- *config*: Keep no and yes as language tags +- *import*: Inject only the imported title's keys into each track +- *main*: Remove unwanted - +- *serve*: Defer service hot reload while a remote session uses it +- *remote*: Return session cache for device-code and cache-only logins +- *remote*: Honor proxy client cdm_type for DRM system selection +- *drm*: Log missing Widevine/PlayReady PSSH at debug level +- *cli*: Make the click param types the one source of codec spellings +- *vaults*: Verify vault content keys per KID from the fragment map +- *vaults*: Harden the KID window check and clear a stale flag on licence +- *remote*: Forward nested service cache files to and from the server +- *remote*: Stop warning about missing keys for tracks that carry no DRM +- *remote*: Keep the server's own CDM when the tier licenses with server_cdm +- *post-scripts*: Expose {part} and all title-owned variables on failure +- *serve*: Apply staged service reloads when sessions end, with a max staging age +- *remote*: Let the server's CDM mapping decide the DRM system under server_cdm +- *remote*: Forward dl track selection and profile to remote sessions +- *dl*: Skip empty vault pushes and count cached keys once +- *serve*: Stop repeating server vault pushes and retry failed ones +- *export*: Import side-loaded subtitles and keep conflicting keys apart +- *export*: Strip session headers from exports and normalise merged keys +- *import*: Read export files through mediaexport +- *export*: Skip bad keys and failed writes without stopping the download +- *import*: Report refused titles and fail when none is usable +- *drm*: Give the zero-KID fallback only the track's own key +- *import*: Give each track only the keys it declares +- *import*: Stop clearly when no export or vault key exists +- *export*: Name the file from the first write +- *import*: Say an import uses the export's keys, not a server CDM +- *import*: Give no title keys to a track that is clear +- *import*: Read an HLS export that names no title language or master key +- *remote*: Report a missing title list and a refused track URI clearly +- *tracks*: Keep the Dolby Vision record when remuxing video with ffmpeg +- *proxies*: Match surfshark's current server api +- *proxies*: Skip a proxy provider that fails to load +- *proxies*: Return None for unservable queries and repair live providers +- *proxies*: Link to the expressvpn device login with the code prefilled +- *cdm*: Skip the server header probe for pywidevine and pyplayready remote CDMs +- *api*: Stop dashboard event and log reads racing worker threads +- *api*: Keep the worker's error on failed jobs, gate tracebacks behind --debug-api +- *sanitize*: Keep nonspacing marks on letters in unicode filenames +- *sanitize*: Normalise filenames to NFC and keep combining marks +- *console*: Write UTF-8 to redirected streams on Windows +- *dl*: Keep the --enrich original language after get_tracks +- *attachment*: Keep custom fonts after mux cleanup +- *dl*: Keep the --enrich title and year after get_tracks +- *docs*: Hide the release version in the header repo widget +- *dl*: Read the vaults first under --all-drm +- *hybrid*: Read the container file for a base that had the DV fixup +- *cdm*: Send a PlayReady licence without an XML declaration as XML +- *import*: Carry the HLS segment filter in an export +- *cdm*: Simplify cached keys retrieval in CustomRemoteCDM +- *hls*: Read the key id from the init segment when the PSSH has none +- *api*: Follow the cdm config key order for the server CDM + +### Documentation + +- *session*: Correct stale pool-size comment +- Strip non-essential comments, fold key facts into docstrings +- *services*: Add MUSIC_EXAMPLE reference service +- Apply simplified technical english across docs and docstrings. +- Phase 2 of the prose style across docs and docstrings +- Widen supported shaka-packager range to 2.6.1 or >= 3.10.0 +- *dev*: Correct get_chapters guidance on markers at timestamp 0 +- *example*: Show drm_preference pinning for dual-PSSH manifests +- *post-scripts*: Use post-script as the one term for hooks +- *api*: Describe the dashboard session payload in the OpenAPI yaml +- *cli*: Correct --merge-video scope in cli reference +- *export*: Describe the export file name and its messages + +### Performance Improvements + +- *downloader*: Slow-start ramp for the adaptive worker controller +- *downloader*: Use per-arrival reads only while a segment is hedge-raced +- *dash*: Collapse single-URL byte-range segments into one direct download +- *downloader*: Stride multiprocess chunk assignment across children +- *api*: Skip progress re-parse when the file is unchanged +- *api*: Append job history instead of rewriting the file +- *downloader*: Unblock hedge-loser reads at teardown +- *dash*: Speed up segment collection and URL templating +- *dl*: Parallelise mux, licensing, and vault lookups; size the shared pool +- *dl*: Overlap hybrid builds with muxing, tag in the mux thread, preload DRM in parallel +- *hybrid*: Reuse DV-side files across resolutions, trim the RPU chain, fix L6 fallback +- *dl*: Push vault key writes to a background thread +- *drm*: Decrypt fMP4 segments during download with mp4decrypt +- *kv*: Push whole services to SQL vaults in one call +- *kv*: Push keys to vaults concurrently, log one summary per title +- *sample*: Download only the subtitle segments around the window +- *manifests*: Decode manifests without charset detection + +### Changes + +- *monalisa*: Remove ML-Worker and improve MonaLisa DRM +- *downloader*: Extract shared byte-range split helper +- *console*: Route interactive prompts through a themed helper +- *core*: [**breaking**] Drop leading underscores from internal definitions +- *tests*: Drop leading underscores from test helper functions +- *music*: [**breaking**] Make Song an ordinary Title on the generic path +- *console*: Style env listings like the rich-click help screens +- *drm*: Drop the hardcoded service branch in the license flow +- *proxies*: Share proxy dispatch between dl, search and resolve_proxy + +### Maintenance + +- Restore memory/ to .gitignore from dev +- *scripts*: Expand bench suite for cross-machine runs +- *scripts*: Harden bench suite report capture +- *scripts*: Add attempt-1-only tail-slow fault to downloader bench +- Bump dev version to 5.5.0 +- Mark install.sh executable + +### Builds + +- *deps*: Pull mediaexport from github in the package metadata +- *deps*: Lock mediaexport at fa9357e + ## [5.4.0] - 2026-08-15 ### Features diff --git a/README.md b/README.md index 952d3a78..199362ff 100644 --- a/README.md +++ b/README.md @@ -26,13 +26,19 @@ A modular archival tool for movies, TV, and music. Fork of [Devine](https://gith ## Install +The recommended way is a git clone with the install script. The script installs `uv` and unshackle, then runs `unshackle setup` to download the external tools and write a first config. + ```shell -uv tool install git+https://github.com/unshackle-dl/unshackle.git -unshackle --help +git clone https://github.com/unshackle-dl/unshackle.git +cd unshackle +sh install.sh # Windows: .\install.bat +uv run unshackle env check ``` -> [!TIP] -> Prefer `uv run unshackle ...` inside a clone to keep the virtual environment active. +In a clone, run every command as `uv run unshackle ...`. + +> [!NOTE] +> Advanced: `uv tool install git+https://github.com/unshackle-dl/unshackle.git` installs unshackle into the tool folder of `uv`, not a folder that you choose. `unshackle setup` then puts the tools, config, and data in your user data and config directories. See [Installation](https://docs.unshackle.dev/getting-started/installation/) for details. ### Requirements @@ -42,7 +48,7 @@ External tools. (recommended versions): - [uv](https://docs.astral.sh/uv/) - ≥ 0.5 - [FFmpeg](https://ffmpeg.org/) - ≥ 6.0 - [MKVToolNix](https://mkvtoolnix.download/) - ≥ 80 -- [shaka-packager](https://github.com/shaka-project/shaka-packager/releases/tag/v2.6.1) - 2.6.1 +- [shaka-packager](https://github.com/shaka-project/shaka-packager/releases) - 2.6.1, or ≥ 3.10.0 Optional: @@ -52,4 +58,4 @@ Optional: ## License -[GPL-3.0](LICENSE). Do not use unshackle for content you lack the rights to. Keep the core free and open; keep service code private. Be kind. +[GPL-3.0](LICENSE). Do not use unshackle for content you do not have the rights to. Keep the core free and open. Keep service code private. Be kind. diff --git a/docs/assets/extra.css b/docs/assets/extra.css new file mode 100644 index 00000000..548a8002 --- /dev/null +++ b/docs/assets/extra.css @@ -0,0 +1 @@ +.md-source__fact--version { display: none; } diff --git a/docs/dev/creating-a-service.md b/docs/dev/creating-a-service.md index 04fa6163..c4583673 100644 --- a/docs/dev/creating-a-service.md +++ b/docs/dev/creating-a-service.md @@ -1,29 +1,30 @@ # Creating a Service A **service** is a plugin that teaches unshackle how to talk to one streaming -provider: how to log in, how to look up a title, what video/audio/subtitle -tracks exist, and how to license any DRM. Everything else (track selection, -downloading, decryption, muxing, naming) is handled by the unshackle core. +platform: how to log in, how to look up a title, what video/audio/subtitle +tracks exist, and how to license any DRM. The unshackle core does everything +else (track selection, downloading, decryption, muxing, naming). !!! info "Who this page is for" This is a **developer guide**. If you only want to *use* services, see [downloading](../guide/downloading.md) and - [configuration](../reference/configuration/index.md). Nothing here is required to run - the CLI. Service code is deliberately kept separate from the core so it can - live in its own private repository. + [configuration](../reference/configuration/index.md). You do not need anything here to + operate the CLI. The code of a service is deliberately separate from the + core, so it can live in its own private repository. -Unshackle ships one reference service, **EXAMPLE**, at -`unshackle/services/EXAMPLE/`. It is a deliberately exhaustive, non-runnable -showcase of every framework feature in a single file. Read it alongside this -page; most snippets below are drawn from it. +unshackle ships two reference services. **EXAMPLE**, at +`unshackle/services/EXAMPLE/`, is a non-runnable showcase of every framework +feature in a single file. Read it alongside this page. Most snippets below come +from it. **MUSIC_EXAMPLE**, at `unshackle/services/MUSIC_EXAMPLE/`, is the same +kind of showcase for a music service. If your platform has songs, read that one too. --- -## How a service is discovered +## How unshackle finds a service At startup unshackle scans every path in the `directories.services` config key (a **list**). Each entry is either a local directory of services or a remote -repo spec (a git URL or `owner/repo` shorthand, which is cloned automatically). +repo spec (a git URL or `owner/repo` shorthand, which unshackle clones for you). The default is the bundled `unshackle/services` directory. Within a services directory, **every subfolder that contains an `__init__.py` @@ -38,13 +39,13 @@ services/ Two rules the loader enforces: -1. **The class name must exactly match the folder/tag name.** Folder `EXAMPLE` must +1. **The class name must match the folder/tag name exactly.** Folder `EXAMPLE` must define `class EXAMPLE`. A mismatch raises a `RuntimeError`. 2. **List order is priority.** The first services path to define a given tag - wins; later duplicates are shadowed. Put your own local overrides *last* to + wins, and unshackle ignores the later duplicates. Put your own local overrides *last* to use them as fallbacks, or *first* to override a repo. -Once installed, a service is invoked as a subcommand of `dl`: +After installation, you call a service as a subcommand of `dl`: ```bash unshackle dl EXAMPLE 20914 @@ -55,11 +56,11 @@ unshackle dl EX 20914 # via an ALIAS A service's own settings go in `config.yaml` **inside the service folder** (`directories.services//config.yaml`). This is separate from the global `unshackle.yaml`. Access it in code as `self.config[...]`. Never hardcode - URLs, user agents, or certificates; put them here. + URLs, user agents, or certificates. Put them here. !!! warning "`config.yaml` is shared: keep secrets out of it" Treat `config.yaml` as a checked-in file of **defaults**: it belongs in the - service repo and is shared by everyone who runs the service. Per-user secrets + service repo, and everyone who runs the service shares it. Per-user secrets (API keys, device IDs, account tokens) must **not** live here. Those go in the user's own `unshackle.yaml` under `services.`, which is **merged into `self.config` at runtime**. That checked-in-defaults / per-user-overrides @@ -77,7 +78,7 @@ unshackle dl EX 20914 # via an ALIAS ``` A service loaded from a remote repo lives outside the `unshackle` package, - so the absolute `unshackle.services..*` path does not resolve and the + so Python cannot find the absolute `unshackle.services..*` path and the import fails with `no known parent package`. Relative imports work both locally and from a cloned repo. @@ -94,29 +95,39 @@ Declared at class level to configure framework behaviour: | Variable | Type | Purpose | |---|---|---| -| `ALIASES` | `tuple[str, ...]` | Extra tags that resolve to this service (e.g. `("EX", "DOMAIN")`). Default `()`. | -| `GEOFENCE` | `tuple[str, ...]` | IP region codes the service requires. Empty = no geofence. The **first** entry is treated as the main region for auto-proxy. | +| `ALIASES` | `tuple[str, ...]` | Extra tags that resolve to this service (e.g. `("EX", "DOMAIN")`). Case does not matter. Default `()`. | +| `GEOFENCE` | `tuple[str, ...]` | IP region codes the service requires. Empty = no geofence. unshackle treats the **first** entry as the main region for auto-proxy. | +| `GEOBLOCK` | `tuple[str, ...]` | IP region codes where the service refuses to work. Every other region is allowed. Default `()`. | | `VAULT_TAG` | `Optional[str]` | Overrides the key-vault namespace so sibling services can share one vault. Default `None` (use the service's own tag). | | `AUTH_METHODS` | `Optional[tuple[str, ...]]` | Auth methods accepted (`"cookies"` / `"credentials"`). When `None`, the REST `/services` endpoint infers them from `authenticate()`. | +| `ANONYMOUS_SEARCH` | `bool` | Set `True` when `search()` needs no login and no state from `authenticate()`. A search then skips the cookie load, `authenticate()` and the cookie save. Default `False`. | | `NO_SUBTITLES` | `bool` | Set `True` on a service with no subtitle tracks to skip subtitle handling entirely. | -| `ANIME` | `bool` | Set `True` when the catalog is anime, so metadata lookups prefer AniList. A title's own `anime` flag overrides it. | -| `DAILY` | `bool` | Set `True` when the catalog is daily/date-based (talk shows, news, sports), so episodes are named by air date. A title's own `daily` flag overrides it. | +| `ANIME` | `bool` | Set `True` when the catalogue is anime, so metadata lookups prefer AniList. A title's own `anime` flag overrides it. | +| `DAILY` | `bool` | Set `True` when the catalogue is daily/date-based (talk shows, news, sports), so unshackle names episodes by air date. A title's own `daily` flag overrides it. | !!! note "`NO_SUBTITLES` is a convention, not a base-class attribute" - `NO_SUBTITLES` is checked by `dl.py` via `hasattr` and is deliberately **not** - declared on the `Service` base class, so it only exists if your service + `dl.py` uses `hasattr` to find `NO_SUBTITLES`, and the `Service` base class + deliberately does **not** declare it, so it only exists if your service defines it. Setting `NO_SUBTITLES = True` is what makes the pipeline skip - subtitle work for services that never carry subtitles; leave it off otherwise. + subtitle work for services that never carry subtitles. Leave it off otherwise. `GEOFENCE` drives an automatic proxy: on startup, if you did not pass an explicit `--proxy`, the base class does a live IP check and, if your region is blocked, fetches a proxy to `GEOFENCE[0]` from your configured proxy providers. +`GEOBLOCK` is the negative form: the service works everywhere except the listed +regions. With no `GEOFENCE` to name a main region, a `GEOBLOCK` hit stops the run +with a "not available in your region" error; pass `--proxy` yourself. + ```python class EXAMPLE(Service): ALIASES = ("EX", "DOMAIN") GEOFENCE = ("US", "UK") VAULT_TAG = "DIFFERENT_NAME" + + +class WORLDWIDE(Service): + GEOBLOCK = ("GB",) ``` ### What `Service.__init__` wires up @@ -129,7 +140,7 @@ will use throughout the service: | `self.config` | This service's `config.yaml` contents (a dict), or `None` if absent. | | `self.log` | A `logging.Logger` named after your class. | | `self.session` | A prepared `requests.Session` with config headers and a retry adapter (5 retries, backoff 0.2, retries on 429/500/502/503/504). | -| `self.cache` | A `Cacher` for arbitrary key/value data (tokens, etc.). | +| `self.cache` | A `Cacher` for arbitrary key/value data, for example authentication tokens. | | `self.title_cache` | A region/account-aware `TitleCacher` used by `get_titles_cached`. | | `self.cache_dir` | `config.directories.cache / `. | | `self.track_request` | A `TrackRequest` built from the CLI `--vcodec` / `--range` / `--best-available` flags. | @@ -149,14 +160,14 @@ class TrackRequest: !!! note "Read the request, don't second-guess the user" Services may narrow `track_request` for hard technical constraints (e.g. - *"HDR on this service is only delivered as HEVC"*), but must **not** filter + *"this service delivers HDR only as HEVC"*), but must **not** filter the tracks they return by resolution, bitrate, or language. All selection is done by the core after `get_tracks` returns. !!! tip "Override `get_session()` to defeat TLS-fingerprint bot detection" The base `get_session()` returns a plain `requests.Session` (config headers + retry adapter) and **deliberately does not** do TLS impersonation. When a - provider blocks you on TLS fingerprint alone, override it to return + streaming platform blocks you on TLS fingerprint alone, override it to return `session("Chrome131")` (any `rnet.Impersonate` preset). `RnetSession` is a drop-in `requests.Session` replacement (same `.get`/`.post`/cookie-jar interface), so nothing else in the service changes. If instead you need @@ -165,9 +176,9 @@ class TrackRequest: --- -## The methods you implement +## The methods you write -Methods run in the order shown. Only the three abstract ones are mandatory. +unshackle calls the methods in the order shown. Only the three abstract ones are mandatory. ```mermaid graph LR @@ -181,11 +192,11 @@ returns an **instance** of your service. Keep the command `name=` matching the tag. !!! note "`name=` is cosmetic: the directory name is what resolves the command" - `unshackle dl EXAMPLE` is dispatched by the **folder/class name**, not by the - `name=` in `@click.command`. A mismatched `name=` still loads and runs; it - just produces confusing `--help`/usage output that names the wrong command. - That confusing output is the reason to keep it in sync, not any dispatch - requirement. + unshackle chooses the command from the **folder/class name**, not from the + `name=` in `@click.command`. A mismatched `name=` still loads and runs. It + only produces confusing `--help`/usage output that names the wrong command. + That confusing output is the reason to keep it in sync, not any requirement + of the command lookup. ```python @staticmethod @@ -211,7 +222,7 @@ accepted URL/ID formats and options there. !!! tip "CDM-aware behaviour" The resolved CDM is on `ctx.obj.cdm` (may be `None` for DRM-free runs). Use `is_widevine_cdm()` / `is_playready_cdm()` from `unshackle.core.cdm.detect` - to classify it. These correctly handle local *and* remote CDMs, so never + to classify it. These work correctly for local *and* remote CDMs, so never hand-roll an `isinstance` check. Services often pick a device profile or manifest endpoint based on which DRM the CDM speaks. @@ -219,7 +230,7 @@ accepted URL/ID formats and options there. Override to log in with cookies and/or credentials. **Call `super().authenticate()` first**: the base implementation loads the cookie jar into `self.session.cookies` -and stores `self.credential`. Do all token fetching here; it runs before +and stores `self.credential`. Do all token fetching here. It runs before `get_titles`. ```python @@ -236,30 +247,53 @@ def authenticate(self, cookies=None, credential=None) -> None: self.token = cache.data["token"] ``` -Cookies come from files under `directories.cookies`; credentials from the +Cookies come from files under `directories.cookies`. Credentials come from the `credentials` map in `unshackle.yaml`. For interactive prompts (OTP, captcha) use `self.request_input(prompt)`, never a bare `input()`. Under `serve` mode there is no local terminal, so a bare `input()` would hang the server waiting on -stdin that never arrives; `request_input` instead relays the prompt to the -remote client through the attached `InputBridge`. Locally it routes through the -shared Rich console (`console.input`) so the prompt renders correctly alongside +stdin that never arrives. `request_input` instead relays the prompt to the +client: a remote-dl session gets it through the attached `InputBridge`, and a +REST download job shows it as `input_prompt`. Locally it routes through the +shared Rich console (`prompt_user`) so the prompt renders correctly alongside progress and log output. -!!! warning "Key token caches by whatever varies per session" - The cache key above is `tokens_{device}_{profile}` on purpose. A token cache +For a login that the user approves on another device (a pair code, a QR code), +use `self.wait_for_approval(message, check, timeout)`, never a hand-written +loop. It shows the message, then calls `check` at each interval until `check` +returns a value. `check` returns `None` while the approval is pending. + +```python +token = self.wait_for_approval( + f"Open {self.config['endpoints']['pair']} and enter code {code}", + check=lambda: self.poll_pair_token(code), + timeout=expires_in, +) +``` + +It raises `TimeoutError` after `timeout` seconds. Under `serve` mode it also stops +when the client deletes the remote session, so the loop does not continue on the +server with no client. The message goes out as a log line, so a remote +session shows it. A REST download job shows it in its `notice` field until the wait ends. + +The wait sees a cancel only between two `check` calls, so `check` must return within a few +seconds. A `check` that reads a socket keeps the socket open across calls and returns `None` +after each short idle wait. + +!!! warning "Make each token cache entry unique" + The cache above uses `tokens_{device}_{profile}` on purpose. A token cache must include every dimension that changes the token (device, profile, or `credential.sha1`), or two profiles/devices will share one cache entry and - stomp each other's tokens. This isn't obvious from the caching API, which - happily lets you use a single flat key. + stomp each other's tokens. This is not obvious from the caching API, which + happily lets you use a single flat name. -!!! warning "Handle the credential carefully" - Use the `Credential` only inside `authenticate()` to obtain tokens; don't +!!! warning "Use the credential carefully" + Use the `Credential` only inside `authenticate()` to get tokens. Do not stash it or the raw cookie jar elsewhere. The base class already caches identity for you. ### `get_titles`: required -Return a titles collection for the given ID. The return type depends on content: +Return a titles collection for the given ID. The return type depends on the kind of title: | Return | Contains | Use for | |---|---|---| @@ -268,8 +302,8 @@ Return a titles collection for the given ID. The return type depends on content: | `Album` | `Song` objects | Music | Every title carries a `language` (its **original recorded language**) and an -arbitrary `data` dict you can use to stash metadata for later methods. At least -one title must be returned, or the ID is treated as invalid. +arbitrary `data` dict you can use to stash metadata for later methods. You must +return at least one title. If you return none, unshackle treats the ID as invalid. ```python def get_titles(self) -> Titles_T: @@ -310,7 +344,7 @@ Common constructor fields: part=None) ``` - Pass `air_date` for daily/sports content to name by date instead of + Pass `air_date` for daily and sports titles to name by date instead of `SxxExx`. Return a `Series([...])` of episodes. Pass `part` only when the service splits one episode into several videos, see [Split episodes](#split-episodes). @@ -318,11 +352,20 @@ Common constructor fields: === "Song" ```python - Song(id_, service, name, artist, album, track, disc, year, - language=None, data=None) + Song(id_, service, name, artist, album, track, disc=1, year=None, + language=None, data=None, ...) ``` - Return an `Album([...])` of songs. + Return an `Album([...])` of songs. `disc` defaults to 1 and `year` is optional. + Optional metadata keywords such as `album_artist`, `genre`, `isrc`, `label`, + `lyrics` and `artwork_url` feed the tagger and the naming templates. Read the + class for the current list. + + From `get_tracks()`, give one `Audio` track for each codec and bitrate you offer + for the song. The framework then selects one with its usual audio options. + A `Song` skips the muxer, so restore the real container suffix on the track path + in `on_track_downloaded`. The **MUSIC_EXAMPLE** service shows the full music + surface. !!! note "The ID must be unique and stable" `id_` must be truthy and, if it has a length, at least 4 characters, to @@ -344,8 +387,8 @@ Episode(..., season=1, number=1, part=1, name="The Reckoning") Episode(..., season=1, number=1, part=2, name="The Reckoning") ``` -1. `part` counts from 1, contiguous. `part=0` is rejected, and `-w` can only address - parts up to 99. +1. `part` counts from 1, contiguous. unshackle rejects `part=0`, and `-w` can only + address parts up to 99. 2. Every part of one episode shares the same `season` and `number`. 3. Each part is a separate `Episode` with its own unique `id_`. 4. Unsplit episode: leave `part` unset. Never pass `part=1` for a whole episode. @@ -365,13 +408,13 @@ Episode(..., season=1, number=1, part=2, name="The Reckoning") !!! tip "Clean the part out of the name" `Episode` discards any `name` that starts with `Episode `, so a raw - `"Episode 1 (Part 2): The Reckoning"` leaves you with no episode name at all. Strip + `"Episode 1 (Part 2): The Reckoning"` leaves you with no episode name at all. Remove the prefix before you pass it, or pass `None`. Once `part` is set, the filename gains a part token (`S01E01.Part.2`, see [Output & naming](../guide/output-and-naming.md#split-episodes)), `-w S01E01.2` selects a single part while a bare `-w S01E01` selects them all, and the `--list-titles` tree labels -the episode `01.2`. The REST API reports it as an extra `part` key on the serialized +the episode `01.2`. The REST API reports it as an extra `part` field on the serialized title, described in [Endpoints](rest-api/endpoints.md#post-apilist-titles). !!! note "Opt-in and additive" @@ -382,7 +425,7 @@ title, described in [Endpoints](rest-api/endpoints.md#post-apilist-titles). ### `get_tracks`: required Given one title, return a `Tracks` object holding `Video`, `Audio`, and -`Subtitle` tracks. In almost all cases you build these by parsing a manifest, +`Subtitle` tracks. In almost all cases you assemble these by parsing a manifest, not by hand. The manifest parsers live in `unshackle.core.manifests`: @@ -422,92 +465,80 @@ Each exposes `from_url(url, session=...)` (or `from_text(text, url)`) and then !!! warning "Always pass `language=`" Pass the title's original language to `to_tracks(language=...)`. For DASH and - HLS this is **required as a fallback**. If a track's language can't be - derived and no valid fallback was given, `to_tracks` raises `ValueError`. - It's also what lets the parser flag `is_original_lang` on each track (via - `is_close_match`), driving `-l best/all` selection and the filename language - token. + HLS this is **required as a fallback**. If `to_tracks` cannot derive a track's + language and you gave no valid fallback, it raises `ValueError`. + It is also what lets the parser flag `is_original_lang` on each track (through + `is_close_match`), which drives `-l best/all` selection and the filename + language token. Some services deliver a **separate manifest per codec/range**. The base class -provides `_get_tracks_for_variants(title, fetch_fn)` to fan out over every +provides `get_tracks_for_variants(title, fetch_fn)` to fan out over every codec×range in the `TrackRequest`, including `HYBRID` (fetch HDR10 + DV and merge) and `--best-available` skip-on-error handling: ```python def get_tracks(self, title: Title_T) -> Tracks: - def _fetch_variant(title, codec, range_) -> Tracks: + def fetch_variant(title, codec, range_) -> Tracks: vcodec = "H265" if codec == Video.Codec.HEVC else "H264" - return self._fetch_dash_manifest(title, vcodec=vcodec, range_=range_) - return self._get_tracks_for_variants(title, _fetch_variant) + return self.fetch_dash_manifest(title, vcodec=vcodec, range_=range_) + return self.get_tracks_for_variants(title, fetch_variant) ``` After parsing, you may **correct** track metadata the manifest gets wrong: stamp the real `video.range`, fix odd audio channel counts, mark descriptive audio, add hand-built subtitles or an `Attachment` (e.g. cover art). Do *not* -filter for resolution/bitrate. See `_fetch_dash_manifest` in the EXAMPLE service +filter for resolution/bitrate. See `fetch_dash_manifest` in the EXAMPLE service for a thorough demonstration. !!! note "Flip HDR10 → HDR10+ by hand when you know the platform embeds it" HDR10+ is a **bitstream (SEI)** feature. The HLS parser intentionally does - not sniff it from the stream, so a manifest that embeds HDR10+ SEI but labels + not sniff it from the bitstream, so a manifest that embeds HDR10+ SEI but labels the variant plain HDR10 will parse as HDR10. The label is the only signal - the parser has, and it's wrong. Only the service author knows the platform - embeds HDR10+, so it's on you to correct `video.range` to HDR10+ here for + the parser has, and it is wrong. Only the service author knows the platform + embeds HDR10+, so it is on you to correct `video.range` to HDR10+ here for those services. !!! warning "`get_tracks` is your only chance to capture license inputs" - The license callbacks (`get_widevine_license`, etc.) fire **much later**, in + The license callbacks (`get_widevine_license` and the others) fire **much later**, in the download/decrypt step, long after `get_tracks` has returned, and they receive **only** `challenge`, `title`, and `track`. Nothing else from the - manifest response reaches them. So anything a license call needs (the license - URL, `dt-custom-data`, a session token) has to be stashed **now**, during + manifest response reaches them. So you must stash anything a license call needs + (the license URL, `dt-custom-data`, a session token) **now**, during `get_tracks`, onto `self.license_data` or `title.data`. This is a - lifecycle-timing consequence you can't infer from the callback signatures. + lifecycle-timing consequence you cannot infer from the callback signatures. -!!! tip "Provide the KID if you cheaply can" - If you can obtain a track's Key ID (32-char hex) without downloading stream - data, set `track.kid`; it speeds up the decryption/key-lookup path. And be +!!! tip "Give the KID if you cheaply can" + If you can get a track's Key ID (32-char hex) without downloading the track + data, set `track.kid`. It speeds up the decryption and key-lookup path. And be sure encrypted tracks carry the correct `drm` so the core licenses them. ### `get_chapters`: required -Return a `Chapters` object (0 or more `Chapter`s). You don't need to number or -sort them; `Chapters` does that automatically and inserts a `00:00:00.000` -marker if missing. A `Chapter` timestamp accepts `"HH:MM:SS[.mmm]"`, an int in -milliseconds, or a float in seconds. +Return a `Chapters` object of 0 or more `Chapter`s. It sorts by timestamp, +numbers the chapters at mux time, and adds a `00:00:00.000` chapter if none +exists. Timestamps take `"HH:MM:SS[.mmm]"`, int milliseconds, or float seconds. ```python def get_chapters(self, title: Title_T) -> Chapters: - chapters = Chapters() - seen: set[int] = set() - for ch in title.data.get("chapters", []): - chapter = Chapter(timestamp=ch["start"], name=ch.get("name")) - if chapter.timestamp == 0 or chapter.timestamp in seen: - continue # see the warning below - seen.add(chapter.timestamp) - chapters.add(chapter) - return chapters + chapters = [Chapter(name=c.get("name"), timestamp=c["start"]) for c in title.data.get("chapters", [])] + return Chapters(sorted(chapters, key=lambda c: c.timestamp)) ``` -!!! warning "Skip markers at 0 and de-duplicate timestamps before `add()`" - `Chapters.add()` auto-injects a `Chapter(0)` at `00:00:00.000` the first time - you add *any* chapter, **and** it raises `ValueError` if a chapter already - exists at an exact timestamp. So an API marker reported at `0` (an intro or - recap that starts at the very beginning) collides with that auto-inserted - opening chapter, and two markers sharing a timestamp collide with each other. - Guard both cases: drop any marker at timestamp `0` and de-duplicate timestamps - before adding, as above. +!!! warning "Sort by timestamp before you build the `Chapters`" + `Chapters.add()` adds its own unnamed `Chapter(0)` once you add a chapter that is + not at `0`, and a duplicate timestamp raises `ValueError`. Sort first, so yours + lands before it. -!!! note "An unnamed chapter is the idiom for closing a named range" - A `Chapter` with no name is perfectly valid. Inserting an unnamed marker is - the standard way to *close out* a named range: e.g. add `Chapter(name="Intro")` - at the start and an unnamed `Chapter` where the intro ends, so the "Intro" - label applies only to that span. + You never need to add `Chapter(0)`. An API chapter at `0` keeps its name. Drop + duplicate timestamps. + +!!! note "Close a named range with an unnamed chapter" + An unnamed `Chapter` ends the range before it: `Chapter(name="Intro")` at the + start, an unnamed one where the intro ends. !!! warning "Don't invent chapter names" - Never name chapters `"Chapter 1"` yourself. Leave unnamed markers unnamed; - users who want generic names set `chapter_fallback_name` (e.g. - `"Chapter {i:02}"`) in their config. + Never write `"Chapter 1"`; leave unnamed chapters unnamed. Users set + `chapter_fallback_name` in their config (for example, `"Chapter {i:02}"`). --- @@ -516,7 +547,7 @@ def get_chapters(self, title: Title_T) -> Chapters: The core drives licensing. Your job is to answer the license challenges the CDM produces. Mark encrypted tracks with the right DRM in `get_tracks` (the manifest parsers do this automatically for PSSH/`EXT-X-KEY` found in the manifest), then -implement the license callbacks you need. Each receives the challenge plus the +write the license callbacks you need. Each receives the challenge plus the current `title` and `track`: | Method | For | Returns | @@ -548,20 +579,21 @@ def get_widevine_license(self, *, challenge: bytes, title, track): !!! tip "`ClearKeyCENC` (`org.w3.clearkey`) has three escalating integration levels" Pick the lowest level that works for the platform: - 1. **The manifest carries a ``**: implement nothing. The framework + 1. **The manifest carries a ``**: write nothing. The framework POSTs the challenge to that URL itself. - 2. **A custom endpoint or extra headers are needed**: override + 2. **Your service needs a custom endpoint or extra headers**: override `get_clearkey_license` to do the POST yourself. 3. **Keys arrive obfuscated or through a bespoke channel**: fetch and unwrap - the key in `get_tracks` and pre-populate + the content key in `get_tracks` and pre-populate `drm.content_keys[kid] = key_hex` on the track's `ClearKeyCENC`. The non-obvious payoff: when every KID is already keyed, the framework skips the license round-trip entirely. -Things you don't handle: +Things the service does not do: -- **HLS AES-128 (`ClearKey`)** and **DRM-free** content have no license - callback. The key comes from the manifest and is applied directly. +- **HLS AES-128 (`ClearKey`)** tracks and **DRM-free** tracks have no license + callback. The content key comes from the manifest, and unshackle applies it + directly. - **Key vaults** cache `KID:KEY` pairs across runs, so repeat downloads skip the license round-trip entirely. - **Decryption tooling** (shaka-packager or mp4decrypt) and the choice of local @@ -578,6 +610,12 @@ Override any of these to react to pipeline stages (all no-ops by default): `on_track_repacked`, `on_track_multiplex`. Also override `search()` to yield `SearchResult` objects for `unshackle search`. +!!! warning "Set `ANONYMOUS_SEARCH` only for a search that needs no account" + With `ANONYMOUS_SEARCH = True`, `search()` operates on an HTTP session with no cookies, and + `authenticate()` does not run. Set it only when the search results do not depend on the + account, and when `search()` does its own setup. A `search()` that reads a token, a header + or a region from `authenticate()` fails or gives results for the wrong region. + ```python def search(self) -> Generator[SearchResult, None, None]: results = self.session.get(self.config["endpoints"]["search"], @@ -678,7 +716,7 @@ endpoints: license: https://api.myservice.com/v1/license/widevine ``` -Test it with: +Try it with: ```bash unshackle dl MYSVC https://myservice.com/watch/abc123 @@ -689,12 +727,13 @@ unshackle dl MYSVC https://myservice.com/watch/abc123 ## Checklist - [ ] Folder name, class name, and Click `name=` all match the tag exactly. -- [ ] `cli` is a `@staticmethod` returning an instance; `__init__` calls `super().__init__(ctx)`. -- [ ] `get_titles`, `get_tracks`, `get_chapters` implemented; titles carry the original `language`. -- [ ] Tracks come from a manifest parser with `to_tracks(language=title.language)`; no filtering by quality/language. -- [ ] Encrypted tracks are marked with DRM; the license callbacks you need return responses **unmodified**. -- [ ] URLs, user agents, and certificates live in `config.yaml`, read via `self.config[...]`. +- [ ] `cli` is a `@staticmethod` that returns an instance. `__init__` calls `super().__init__(ctx)`. +- [ ] `get_titles`, `get_tracks` and `get_chapters` written. Titles carry the original `language`. +- [ ] Tracks come from a manifest parser with `to_tracks(language=title.language)`. No filtering by quality or language. +- [ ] Encrypted tracks carry their DRM. The license callbacks you need return responses **unmodified**. +- [ ] URLs, user agents, and certificates live in `config.yaml`, read through `self.config[...]`. - [ ] Multi-file services import their own modules relatively (`from .helpers import x`), so they work when loaded from a repo. -Read `unshackle/services/EXAMPLE/` end to end; it annotates every feature -touched above in one place. +Read `unshackle/services/EXAMPLE/` end to end. It annotates every feature +touched above in one place. For a music service, read +`unshackle/services/MUSIC_EXAMPLE/` too. diff --git a/docs/dev/rest-api/authentication.md b/docs/dev/rest-api/authentication.md index 0f707182..be06ac43 100644 --- a/docs/dev/rest-api/authentication.md +++ b/docs/dev/rest-api/authentication.md @@ -1,16 +1,16 @@ # REST API Authentication -The unshackle REST API protects every endpoint (with one exception) behind a single API key. Clients present that key in a request header, and the server checks it against the keys defined in your configuration. This page explains how that check works, how to configure keys, how clients send them, and the extra controls that build on top of the key: per-key service allowlists, per-key CDM device access, and session IP binding. +The unshackle REST API protects every endpoint (with one exception) behind a single API key. Clients present that API key in a request header, and the server examines it against the API keys in your configuration. This page explains how that check works, how to configure API keys, and how clients send them. It also explains the extra controls on top of the API key: per-key service allowlists, per-key CDM device access, and remote session IP binding. -The API is started with the [`unshackle serve`](../../guide/cli-reference.md) command. Authentication is on by default: if you start the server without an API key configured, it refuses to launch. +You start the API with the [`unshackle serve`](../../guide/cli-reference.md) command. Authentication is on by default: if you start the server without an API key configured, it refuses to launch. !!! note "Which server am I running?" - `unshackle serve` can run in two shapes, and each uses a slightly different piece of code to check your key: + `unshackle serve` can operate in two shapes, and each uses a slightly different piece of code to examine your API key: - The **integrated server** (the default) exposes the REST API *and* the pywidevine / pyplayready CDM HTTP endpoints. - The **API-only server** (`--api-only`, also implied by `--remote-only`) exposes only the REST API. - The header, the config, and the behaviour you see as a client are the same in both. The differences are internal and are called out in the developer notes below. + The header, the config, and the behaviour you see as a client are the same in both. The differences are internal, and the developer notes below give them. ## The short version @@ -36,7 +36,7 @@ serve: api_secret: "a-long-random-secret-string" ``` -This value becomes the one and only key that the server accepts. Requests that present it in the `X-Secret-Key` header are allowed; everything else is rejected. +This value becomes the one and only API key that the server accepts. The server allows requests that present it in the `X-Secret-Key` header. The server rejects everything else. !!! warning "The server will not start without a key" If you start `unshackle serve` with no `api_secret` configured, and you have *not* passed `--no-key`, the command fails immediately with: @@ -45,11 +45,11 @@ This value becomes the one and only key that the server accepts. Requests that p API secret key is not configured. Please add 'api_secret' to the 'serve' section in your config. ``` - Choose a long, unpredictable value. The key is the only thing standing between the internet and your CDM and download endpoints. + Choose a long, unpredictable value. The API key is the only thing standing between the internet and your CDM and download endpoints. ### Multiple keys with `users` -For finer control you can define named users, each with their own key. A user entry can also grant CDM device access and restrict which services that key may touch: +For finer control you can define named users, each with their own API key. A user entry can also grant CDM device access and restrict which services that API key may touch: ```yaml title="unshackle.yaml" serve: @@ -65,16 +65,16 @@ serve: devices: ["my_widevine_device"] ``` -The key of each entry under `users` (for example `a-secret-key-for-alice`) *is* the secret that client sends in `X-Secret-Key`. The `username` is a human-readable label used in logs and in job/history metadata. +The config key of each entry under `users` (for example `a-secret-key-for-alice`) *is* the secret that client sends in `X-Secret-Key`. The `username` is a human-readable label used in logs and in job/history metadata. !!! info "How `api_secret` and `users` combine (integrated server)" - On the integrated server, the configured `api_secret` is automatically added as an extra accepted key alongside everyone in `users`. It is granted access to all loaded Widevine and PlayReady devices and is labelled `api_user`. So `api_secret` behaves as an admin-level key in addition to any named users you define. + On the integrated server, the server automatically adds the configured `api_secret` as an extra accepted API key alongside everyone in `users`. It gives that API key access to all loaded Widevine and PlayReady devices, and labels it `api_user`. So `api_secret` behaves as an admin-level API key in addition to any named users you define. - On the API-only server, only `api_secret` is accepted: the single-key model. (See the developer notes for the exact difference.) + On the API-only server, the server accepts only `api_secret`: the single-key model. (See the developer notes for the exact difference.) -### CDM device access per key +### CDM device access per API key -Under the integrated server, a key can only run DRM licensing through a CDM device that its user entry lists: +Under the integrated server, an API key can do DRM licensing only through a CDM device that its user entry lists: | Config key | Grants access to | |---|---| @@ -82,21 +82,21 @@ Under the integrated server, a key can only run DRM licensing through a CDM devi | `playready_devices` | PlayReady `.prd` devices, by name | !!! warning "PlayReady access is opt-in per user" - If a user entry omits `playready_devices`, that key is given **no** PlayReady access, and the server logs a warning at startup. You must list PlayReady devices explicitly for any key that needs them. Widevine and PlayReady device files themselves are auto-loaded from your WVDs and PRDs directories. + If a user entry omits `playready_devices`, the server gives that API key **no** PlayReady access, and logs a warning at startup. You must name the PlayReady devices explicitly for any API key that needs them. Widevine and PlayReady device files themselves are auto-loaded from your WVDs and PRDs directories. -!!! note "Device lists *are* the server-side-decryption switch" - There is no separate tier, capability flag, or permission toggle for whether the server will hand back keys (`KID:KEY`) for a session download. The presence of devices on the calling key decides it. With **empty** `devices` and `playready_devices`, the server can only proxy CDM challenges, so the client must run its own CDM. Once those lists are **populated**, the client may request `mode:server_cdm` and receive keys back. Don't go looking for a tier setting; configuring devices is what enables server-side decryption. +!!! note "Grants decide whether the server returns content keys" + The devices on an API key decide which CDM the server can use. Two grants in the same user entry decide whether the server returns content keys (`KID:KEY`) for a remote session. `server_cdm` lets the server license with those devices. `server_vault` lets a remote session that the client's own device licenses read the server vault, and the server then makes no live licence. Without either grant, the server can only proxy CDM challenges, so the client must operate its own CDM. See [`serve`](../../reference/configuration/services.md) for both grants. ### Disabling authentication -The `--no-key` flag turns authentication off entirely. Every request is allowed, `X-Secret-Key` is ignored, and no key needs to be configured. +The `--no-key` flag turns authentication off entirely. The server allows every request, ignores `X-Secret-Key`, and needs no API key in your configuration. ```bash unshackle serve --no-key ``` !!! danger "Only use `--no-key` on a trusted, isolated network" - With `--no-key` there is nothing stopping any client that can reach the port from listing your services, starting downloads, or using your CDM devices. Never expose a `--no-key` server to an untrusted network. + With `--no-key`, any client that can reach the port can show your services, start downloads, and use your CDM devices. Never put a `--no-key` server on an untrusted network. ## How clients present credentials @@ -106,18 +106,18 @@ Clients authenticate by sending the secret in a single HTTP request header on ev X-Secret-Key: ``` -The value must exactly match one of the configured keys (`api_secret`, or one of the keys under `users`). There is no login step, no session cookie, and no token exchange for API access. The same static key is sent on each request. +The value must match one of the configured API keys exactly (`api_secret`, or one of the keys under `users`). There is no login step, no HTTP session cookie, and no token exchange for API access. The client sends the same static API key on each request. !!! info "One route also accepts the key as a query parameter" - The job event stream, `GET /api/download/jobs/{job_id}/events`, also accepts the key in a `secret_key` query parameter. This is for browsers: the `EventSource` API cannot set request headers. The exception applies to that one route only, and it works in both server modes. + The job event stream, `GET /api/download/jobs/{job_id}/events`, also accepts the API key in a `secret_key` query parameter. This is for browsers: the `EventSource` API cannot set request headers. The exception applies to that one route only, and it works in both server modes. ```javascript new EventSource(`http://127.0.0.1:8786/api/download/jobs/${jobId}/events?secret_key=${key}`); ``` - The header always wins. If the request has an `X-Secret-Key` header, the server checks that header and ignores the query parameter, so a wrong header is rejected even when the query parameter holds a valid key. + The header always wins. If the request has an `X-Secret-Key` header, the server examines that header and ignores the query parameter. The server rejects a wrong header even when the query parameter holds a valid API key. - A key in a URL is easier to leak than a key in a header, because proxies and browser history can record it. Use the header wherever your client can set one. + An API key in a URL is easier to leak than an API key in a header, because proxies and browser history can record it. Use the header wherever your client can set one. === "curl" @@ -150,11 +150,11 @@ The value must exactly match one of the configured keys (`api_secret`, or one of ``` !!! tip "The reference client sets it for you" - unshackle's own [remote download](../../guide/downloading.md) client (`RemoteService`) sends `X-Secret-Key` automatically, reading the key from your `remote_services` config. It also sends a `User-Agent` of `unshackle/`. You only deal with the header directly when writing your own client. + unshackle's own [remote download](../../guide/downloading.md) client (`RemoteService`) sends `X-Secret-Key` automatically, reading the API key from your `remote_services` config. It also sends a `User-Agent` of `unshackle/`. You only deal with the header directly when writing your own client. ### The health check is always open -One endpoint is exempt from authentication: `GET /api/health`. It never requires a key, so you can use it for liveness and version probes without embedding a secret in your monitoring: +One endpoint is exempt from authentication: `GET /api/health`. It never requires an API key, so you can use it for liveness and version probes without embedding a secret in your monitoring: ```bash title="No key needed" curl http://127.0.0.1:8786/api/health @@ -172,11 +172,11 @@ curl http://127.0.0.1:8786/api/health } ``` -Every other endpoint (including the Swagger UI at `/api/docs/` on the API-only server) requires a valid key. +Every other endpoint (including the Swagger UI at `/api/docs/` on the API-only server) requires a valid API key. ## Authentication failures -When a request is rejected for authentication reasons, the response has an HTTP `401 Unauthorized` status and a small JSON body. +When the server rejects a request for authentication reasons, the response has an HTTP `401 Unauthorized` status and a small JSON body. === "Missing header" @@ -191,7 +191,7 @@ When a request is rejected for authentication reasons, the response has an HTTP === "Wrong key" - Sending a key that is not in your config: + Sending an API key that is not in your config: ```json { @@ -203,17 +203,42 @@ When a request is rejected for authentication reasons, the response has an HTTP !!! warning "Auth errors use a different JSON shape than other errors (developer note)" The rest of the API reports errors with a structured body containing `error_code`, `message`, `timestamp`, and other fields (see [Errors](errors.md)). The authentication middleware is different: it returns `{"status": 401, "message": "..."}`, where `status` is an **integer**, and there is no `error_code` or `timestamp`. - A robust client should treat any `401` as an authentication problem and be prepared to parse *both* shapes rather than assuming the standard error body is always present. + In your client, treat any `401` as an authentication problem and parse *both* shapes, because the standard error body is not always present. -## Building on the key: access controls +## Rate limit rejections -Once a request is authenticated, several additional controls decide what that specific key is allowed to do. +An API key that carries a rate limit gets `429 Too Many Requests` once it goes over, from the +same middleware and in the same shape as the `401` bodies above, with a `Retry-After` header in +seconds: + +```json +{ + "status": 429, + "message": "Rate limit exceeded." +} +``` + +A limit comes from `serve.tiers..rate_limit` or from the API key's own +`serve.users..rate_limit`, in requests per hour. An API key with neither has no limit, and +`GET /api/health` is never limited. See +[dashboard rate limits](dashboard.md#rate-limits) for the config and the counters, and +[services configuration](../../reference/configuration/services.md) for the keys themselves. + +!!! warning "`429` is not the `RATE_LIMITED` error body" + `RATE_LIMITED` in [Errors](errors.md) is a *service* rate limit that a handler raises, and it + arrives in the standard envelope with an `error_code`. The `429` here comes from the + middleware before any handler runs, and has the integer-`status` shape shown above. A client + that reads `error_code` to classify a `429` must cope with it being absent. + +## Access controls on top of the API key + +After the server authenticates a request, several additional controls decide what that specific API key can do. ### Per-key service allowlists -You can restrict which services a key may use. Two layers combine: +You can restrict which services an API key may use. Two layers combine: -- **Global allowlist**: `serve.services`, applied to every key. +- **Global allowlist**: `serve.services`, applied to every API key. - **Per-key allowlist**: `services` inside that key's `users` entry. The effective allowlist for a request is: @@ -235,11 +260,11 @@ serve: services: ["EXAMPLE1"] # this key ends up allowed only EXAMPLE1 ``` -Endpoints that name a service (listing services, searching, listing titles/tracks, downloading, profiles, history, and remote sessions) all filter against this allowlist. A request for a service outside the key's allowlist is rejected as an invalid service. Service tags are matched after normalization, so casing and aliases resolve consistently. +Endpoints that name a service (listing services, searching, listing titles/tracks, downloading, profiles, history, and remote sessions) all filter against this allowlist. The server rejects a request for a service outside the API key's allowlist as an invalid service. The server matches service tags after normalisation, so casing and aliases give the same result. ### CDM overrides and per-job credentials -Two download-time capabilities are gated behind server config and, unless enabled, are refused with `403 Forbidden` even for an authenticated key: +The server config gates two download-time capabilities. Unless you enable them, the server refuses them with `403 Forbidden`, even for an authenticated API key: | Config key | Default | Controls | |---|---|---| @@ -254,26 +279,26 @@ serve: ``` !!! tip "When to enable these gates" - The two gates are fully independent and can be combined. The intended posture is that a locked-down or public-facing deployment leaves **both** unset (they default off and reject with `403`) so client requests can never steer the server's CDM or feed it their own logins. Enabling them only makes sense for a trusted single-client deployment, where the caller and the operator are effectively the same party. + The two gates are fully independent, and you can combine them. For a locked-down or public-facing deployment, leave **both** unset. They then default off and reject with `403`, so client requests can never steer the server's CDM or feed it their own logins. Enable them only for a trusted single-client deployment, where the caller and the operator are effectively the same party. !!! note "Client-supplied credentials get isolated token caches" - When `allow_job_credentials` is enabled and a download job supplies its own `credential` / `credentials`, each distinct credential is given its **own** isolated token cache on the server. Client-supplied logins are never shared or merged with the server's configured-credential caches, so they cannot cross-contaminate or read the server's own token state, and they don't clobber each other. + When you enable `allow_job_credentials` and a download job supplies its own `credential` / `credentials`, the server gives each distinct credential its **own** isolated token cache. The server never shares or merges client-supplied logins with its configured-credential caches. They cannot cross-contaminate or read the server's own token state, and they do not clobber each other. -See [Downloads](endpoints.md) for how these fields are used on the download endpoint. +See [Downloads](endpoints.md) for how the download endpoint uses these fields. ### Session IP binding (remote sessions) -The remote-download session endpoints (`/api/session/*`) add an extra check on top of the key. When a session is created, the server records the client's IP address. Any later request for that session must come from the **same** IP, or it is rejected with `403 Forbidden`. This means a session is bound both to the key that created it and to the address it was created from. +The remote-download session endpoints (`/api/session/*`) add an extra check on top of the API key. When the server creates a remote session, it records the client's IP address. Any later request for that remote session must come from the **same** IP, or the server rejects it with `403 Forbidden`. Thus the server binds a remote session both to the API key that created it and to the address it came from. ## Transport security (HTTPS) -The API server speaks plain HTTP. Because your key is sent on every request, you should not expose it over an unencrypted connection on an untrusted network. To serve over HTTPS, run a reverse proxy in front of unshackle. The `serve` command can launch Caddy for you: +The API server speaks plain HTTP. Because the client sends your API key on every request, do not use it over an unencrypted connection on an untrusted network. To serve over HTTPS, operate a reverse proxy in front of unshackle. The `serve` command can launch Caddy for you: ```bash unshackle serve --caddy ``` -With `--caddy`, unshackle also starts `caddy run` using the `Caddyfile` located next to your unshackle config, letting you terminate TLS and reverse-proxy to the API. Configuring Caddy itself (certificates, domains, upstream) is done in that `Caddyfile`. +With `--caddy`, unshackle also starts `caddy run` using the `Caddyfile` located next to your unshackle config, letting Caddy end the TLS connection and reverse-proxy to the API. Configuring Caddy itself (certificates, domains, upstream) is done in that `Caddyfile`. ## Quick reference @@ -283,15 +308,17 @@ With `--caddy`, unshackle also starts `caddy run` using the `Caddyfile` located | Query-parameter alternative | `?secret_key=` on `GET /api/download/jobs/{job_id}/events` only | | Default bind address | `127.0.0.1:8786` | | Exempt endpoint | `GET /api/health` | -| Failure status | `401 Unauthorized` | +| Failure status | `401 Unauthorized`, or `429 Too Many Requests` for a key over its rate limit | | Missing-header body | `{"status": 401, "message": "Secret Key is Empty."}` | | Invalid-key body | `{"status": 401, "message": "Secret Key is Invalid."}` | +| Over-limit body | `{"status": 429, "message": "Rate limit exceeded."}`, plus a `Retry-After` header | +| Rate limit config | `serve.tiers..rate_limit`, overridden by `serve.users..rate_limit` | | Disable auth | `--no-key` (all requests allowed) | | Config location | `serve.api_secret` and `serve.users` in `unshackle.yaml` | --- -## Developer notes: how the check is implemented +## Developer notes: how the server does the check !!! note "This section is for people writing or debugging the server, not for API consumers." @@ -299,13 +326,13 @@ With `--caddy`, unshackle also starts `caddy run` using the `Caddyfile` located The header and config are identical between modes, but the code that enforces them differs: -- **API-only server** (`--api-only`, or `--remote-only` which forces API-only). An `api_key_authentication` middleware runs on every request. It lets `GET /api/health` through unconditionally, then reads `X-Secret-Key`. An empty header returns the *"Secret Key is Empty."* body; a header that is not a configured user returns *"Secret Key is Invalid."*. In this mode the accepted-keys map holds your `api_secret` (labelled `api_user`, with no devices) plus every key under `serve.users`, so a per-user key authenticates here exactly as it does on the integrated server, and that user's `services` allowlist applies as usual. With `--no-key`, this middleware is simply not installed and the users map is empty. +- **API-only server** (`--api-only`, or `--remote-only` which forces API-only). An `api_key_authentication` middleware runs on every request. It lets `GET /api/health` through unconditionally, then reads `X-Secret-Key`. An empty header returns the *"Secret Key is Empty."* body. A header that is not a configured user returns *"Secret Key is Invalid."*. In this mode the accepted-keys map holds your `api_secret` (labelled `api_user`, with no devices) plus every key under `serve.users`. A per-user key therefore authenticates here exactly as it does on the integrated server, and that user's `services` allowlist applies as usual. With `--no-key`, this middleware is not installed and the users map is empty. - **Integrated server** (default). A `serve_authentication` middleware wraps pywidevine's authentication (and pyplayready's for `/playready*` paths), and the REST routes live in the same application, guarded by the same check. Here the accepted-keys map is your full `serve` config: `api_secret` (auto-added with access to all loaded devices) plus every entry under `users`, each with its declared `devices` / `playready_devices`. Because the API-only middleware guards *all* non-health paths, the Swagger UI at `/api/docs/` is also behind `X-Secret-Key` there. In `--remote-only` mode the Swagger UI is not mounted at all. -Both middlewares read the caller's key through the shared `request_secret_key()` helper in `unshackle/core/api/handlers.py`, which returns the `X-Secret-Key` header and falls back to the `secret_key` query parameter only when the matched route is the job event stream. The integrated server needs one extra branch for this: pywidevine's `authentication` is header-only, so `serve_authentication` compares the query-parameter key itself when the header is absent, and delegates to pywidevine in every other case. That is why a present-but-wrong header is rejected in both modes. +Both middlewares read the caller's API key through the shared `request_secret_key()` helper in `unshackle/core/api/handlers.py`. That helper returns the `X-Secret-Key` header, and falls back to the `secret_key` query parameter only when the matched route is the job event stream. The integrated server needs one extra branch for this. pywidevine's `authentication` is header-only. So `serve_authentication` compares the API key from the query parameter itself when the header is absent, and delegates to pywidevine in every other case. That is why both modes reject a present-but-wrong header. ### CORS and the `Authorization` header @@ -318,8 +345,8 @@ Access-Control-Allow-Headers: Content-Type, X-Secret-Key, Authorization Access-Control-Max-Age: 3600 ``` -The REST API authenticates with `X-Secret-Key`; `Authorization` is advertised because the co-hosted pywidevine / pyplayready CDM endpoints use it. `PUT` appears in the allowed methods list but no REST route uses it; only `GET`, `POST`, and `DELETE` are wired up. +The REST API authenticates with `X-Secret-Key`. The middleware advertises `Authorization` because the co-hosted pywidevine / pyplayready CDM endpoints use it. `PUT` appears in the allowed-methods list, but no REST route uses it. Only `GET`, `POST`, and `DELETE` have routes. ### Where device access is read -The map of accepted keys lives at `request.app["config"]["users"]`. For DRM operations, a key's permitted Widevine devices come from its `devices` list and PlayReady devices from `playready_devices`; the first configured device is used when a request does not (or may not) override it. A server-wide `config.cdm[]` mapping, if present, takes precedence over the key's device list when resolving which device to use. +The map of accepted API keys lives at `request.app["config"]["users"]`. For DRM operations, an API key's permitted Widevine devices come from its `devices` list, and PlayReady devices from `playready_devices`. The server uses the first configured device when a request does not (or may not) override it. A server-wide `config.cdm[]` mapping, if present, takes precedence over the API key's device list when the server chooses which device to use. diff --git a/docs/dev/rest-api/dashboard.md b/docs/dev/rest-api/dashboard.md new file mode 100644 index 00000000..85dd7742 --- /dev/null +++ b/docs/dev/rest-api/dashboard.md @@ -0,0 +1,312 @@ +# Developer Dashboard + +The dashboard endpoints show the operator of a `serve` instance what the server is doing: +version and uptime, request counts, live remote sessions, download jobs, and the recent +log lines. They exist so you can watch a headless server (`serve --quiet`) from a web page +instead of a terminal. + +The dashboard endpoints are for the person who runs the server, not for API users. They +have their own key: a user key or a tier key never opens them. + +## Enable + +Set a dashboard key under `serve.dashboard` in `unshackle.yaml`: + +```yaml +serve: + api_secret: ... + dashboard: + key: a-long-random-string +``` + +Without `dashboard.key` the server does not register the routes, and they answer `404`. +`serve --no-key` turns off user authentication only; the dashboard key stays required. +Once the dashboard key is set, every `/api/dashboard/` request must carry it in +`X-Secret-Key`. +Every other endpoint refuses the dashboard key, and the dashboard refuses user keys. The +routes are available in `--remote-only` mode too. + +Run the server headless with `--quiet`: no banner, no Rich output, one plain log line per +event on stderr, and `api.*` loggers stay at `INFO` so remote session activity reaches the +log ring. Add `--debug` to raise the level to `DEBUG` and also write the full log to +`directories.logs` as `unshackle_serve_