From d1b23953138bb8d1abd09be9e982c1c1c1e21e64 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Fri, 4 Dec 2026 18:25:14 -0700 Subject: [PATCH] docs(rest-api): give the remote session protocol one page and move dl --remote setup to a user guide --- docs/dev/creating-a-service.md | 2 +- docs/dev/rest-api/authentication.md | 4 +- docs/dev/rest-api/endpoints.md | 427 +----- docs/dev/rest-api/errors.md | 6 +- docs/dev/rest-api/index.md | 36 +- docs/dev/rest-api/job-lifecycle.md | 4 +- docs/dev/rest-api/remote-sessions.md | 1596 ++++++++++----------- docs/guide/remote-sessions.md | 371 +++++ docs/reference/configuration/services.md | 14 +- mkdocs.yml | 3 +- tests/remote/unit/test_remote_protocol.py | 18 + 11 files changed, 1235 insertions(+), 1246 deletions(-) create mode 100644 docs/guide/remote-sessions.md diff --git a/docs/dev/creating-a-service.md b/docs/dev/creating-a-service.md index 6a3cd3cd..90c2f117 100644 --- a/docs/dev/creating-a-service.md +++ b/docs/dev/creating-a-service.md @@ -73,7 +73,7 @@ unshackle dl EX 20914 # via an ALIAS `preferences` in `config.yaml`, and read it from `self.config["preferences"]`. Over `--remote`, the client's own `services..preferences` values reach that block on the server with no extra code. See - [Your preferences](rest-api/remote-sessions.md#your-preferences). + [Your preferences](../guide/remote-sessions.md#your-preferences). !!! warning "Split across files? Use relative imports" If your service grows beyond a single `__init__.py`, import your own diff --git a/docs/dev/rest-api/authentication.md b/docs/dev/rest-api/authentication.md index 13c3b181..9fb805ea 100644 --- a/docs/dev/rest-api/authentication.md +++ b/docs/dev/rest-api/authentication.md @@ -1,6 +1,6 @@ # REST API Authentication -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 unshackle REST API protects every endpoint, `GET /api/health` included, behind an API key. The [dashboard](dashboard.md) routes take the dashboard key instead. 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. 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. @@ -345,7 +345,7 @@ The header and config are identical between modes, but the code that enforces th - **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. +Because the API-only middleware guards every path outside the dashboard prefix, 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 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. diff --git a/docs/dev/rest-api/endpoints.md b/docs/dev/rest-api/endpoints.md index 04283a9d..7c56ed0a 100644 --- a/docs/dev/rest-api/endpoints.md +++ b/docs/dev/rest-api/endpoints.md @@ -1,6 +1,6 @@ # REST API Endpoints -This is the full endpoint reference for the unshackle REST API. It covers every route: its method and path, the request body it accepts, the response shape it returns, and the status codes it can give. This page groups the routes into general, download jobs, server management, and remote-dl sessions. +This is the full endpoint reference for the unshackle REST API. It covers every route: its method and path, the request body it accepts, the response shape it returns, and the status codes it can give. This page groups the routes into general, download jobs, server management, remote sessions, and the remote services relay. Start the server with [`unshackle serve`](../../guide/cli-reference.md). By default it binds to `127.0.0.1:8786`, and every route lives under the `/api/` prefix. The [Authentication](authentication.md) page gives authentication, server modes, and the `X-Secret-Key` header in detail. Read that first if you have not already. For an end-to-end walkthrough, see the [Quickstart](quickstart.md). @@ -15,9 +15,9 @@ Start the server with [`unshackle serve`](../../guide/cli-reference.md). By defa - **Authentication.** Every request, `GET /api/health` included, requires the `X-Secret-Key` header when you configure an API key. `--no-key` disables the check entirely. See [Authentication](authentication.md). - **Content type.** Request bodies are JSON (`Content-Type: application/json`). All success responses are JSON unless this page documents a `204 No Content`. - **CORS.** Every response carries permissive CORS headers, and the server answers `OPTIONS` preflight requests automatically. -- **Compression.** JSON responses of 256 bytes or more are gzip-compressed when the client sends `Accept-Encoding: gzip`. A [slow response](#slow-responses) is not compressed. +- **Compression.** JSON responses of 256 bytes or more are gzip-compressed when the client sends `Accept-Encoding: gzip`. A [slow response](remote-sessions.md#slow-responses) is not compressed. - **Service allowlist.** The effective allowlist for your API key filters the service-facing endpoints (the intersection of the global `serve.services` list and your per-key list). The server treats services you cannot use as unknown. -- **Remote services.** A full-mode server can run a service through one of its own `remote_services` servers (see [Remote sessions](remote-sessions.md)). `GET /api/config` lists their names in `remote_services`, and `GET /api/services?remote=` lists that server's services, each with `remote` set to the name. Add `"remote": ""` to `POST /api/search`, `/api/list-titles`, `/api/list-tracks` or `/api/download`, and the server opens a remote session with its own key for that server: the remote logs in and resolves titles, tracks and licences, and a download still runs, decrypts and muxes here. The tag may be any case or an alias, and your allowlist applies to it. An unknown name is `400 INVALID_PARAMETERS`, a server that does not answer is `SERVICE_UNAVAILABLE`, a server that rejects this server's API key is `AUTH_FAILED` (424), and a tag it does not offer is `INVALID_SERVICE`. List calls from the same API key for the same title, profile, proxy, client region and service options share one remote session, which closes after 120 seconds unused. When the server stops, a list call that waits on the login of a new remote session, or starts one, gets `SERVER_DRAINING` (409). A call that opens a lost remote session again can be cut too: `list-titles` then gets `SERVER_DRAINING`, and `list-tracks` that or `SERVICE_ERROR` (422). An optional `client_name` names your client on the remote server's dashboard as `serve ()`. A relayed search opens no remote session. The server sends its own credentials, cookies and cache for the `profile` with the search. A service that searches with no login gets none of them. A `--remote-only` server does not relay. A remote login that waits on you (a pair code or URL to approve on another device) cannot answer through a list call, so poll `GET /api/remote/logins` alongside it: each entry carries the login's `notice`, its `qr` (the text of a QR code to scan, or null), and its `prompt` when it asks a question (an OTP), which you answer with `POST /api/remote/logins/{id}/input` and `{"response": "..."}`. A remote download job shows the same text as its own `notice`, and asks a question (an OTP) through `input_prompt` as a local job does. +- **Remote services.** A full-mode server can run a service through one of its own `remote_services` servers. See [Remote services relay](#remote-services-relay). !!! warning "Error responses have two shapes" Structured application errors (raised inside a handler) return `{"status": "error", "error_code": "...", "message": "...", "timestamp": "..."}`. The authentication middleware, however, returns a **different** shape: `{"status": 401, "message": "..."}` with an integer `status` and no `error_code`. The same middleware answers `429` in that shape when an API key goes over its rate limit. Clients must accept both shapes. The [Error responses](#error-responses) section at the bottom of this page gives the full error model. @@ -155,7 +155,7 @@ For a service with `anonymous_search`, the server does not log in and ignores `c | `proxy` | string | no | `null` | Full proxy URI on a public host, a Control D resolver as `controld://@dns.controld.com`, or a country code when the API key has `server_proxy`. | | `no_proxy` | boolean | no | `false` | Force-disable all proxy use. | | `credentials`, `cookies`, `cache` | - | no | `null` | Your own login material, on a `--remote-only` server only. See [Client cache on a remote-only server](#client-cache-on-a-remote-only-server). | -| `dl_params` | object | no | `null` | The `dl` track selection, as on [`POST /api/session/create`](#post-apisessioncreate). | +| `dl_params` | object | no | `null` | The `dl` track selection, as on [`POST /api/session/create`](remote-sessions.md#post-apisessioncreate). | === "Request" @@ -230,7 +230,7 @@ them in that mode. `credentials` (`{username, password, extra?}`) and `cookies` (base64 of a zlib-compressed Netscape cookie file) are the same as on -[`POST /api/session/create`](#post-apisessioncreate). `cache` is a map of cache +[`POST /api/session/create`](remote-sessions.md#post-apisessioncreate). `cache` is a map of cache files in the same form: each cache key is the file path relative to the service cache directory, with `/` separators and no `.json` suffix, and each value is base64 of the zlib-compressed file. The server writes these files into the request @@ -327,7 +327,7 @@ Show the video, audio, and subtitle tracks for a title. For series, you can scop | `part` | int/string | no | Part index of a split episode (combined with `season` and `episode`). | | `profile`, `proxy`, `no_proxy`, `cdm_type` | - | no | As on `list-titles`. | | `credentials`, `cookies`, `cache` | - | no | As on `list-titles`. | -| `dl_params` | object | no | The `dl` track selection that the service reads from `ctx.parent.params`: `lang`, `v_lang`, `a_lang`, `s_lang`, `acodec`, `forced_subs` and `exact_lang`, as on [`POST /api/session/create`](#post-apisessioncreate). Some services select the manifests they fetch from these values. | +| `dl_params` | object | no | The `dl` track selection that the service reads from `ctx.parent.params`: `lang`, `v_lang`, `a_lang`, `s_lang`, `acodec`, `forced_subs` and `exact_lang`, as on [`POST /api/session/create`](remote-sessions.md#post-apisessioncreate). Some services select the manifests they fetch from these values. | When you give both `season` and `episode`, the server combines them into a `"{season}x{episode}"` selector. `part` narrows that to `"{season}x{episode}.{part}"`, one part of a [split episode](../creating-a-service.md#split-episodes). Without `part` you get every part of the episode. The server reads `part` only when you give both `season` and `episode`, and `wanted` takes precedence over all three. To scope a part by range, put it in `wanted` instead (`"S01E01.2"`). @@ -437,7 +437,7 @@ Make a download job. It requires `service` and `title_id`. Every other field is } ``` -**Request body.** Every field except `service` and `title_id` is optional. The `dl` fields mirror the flags of the [`dl` command](../../guide/downloading.md). This table comes from the OpenAPI description that `/api/docs/` of a running server also shows. +**Request body.** Every field except `service` and `title_id` is optional. The `dl` fields mirror the flags of the [`dl` command](../../guide/cli-reference.md#dl). This table comes from the OpenAPI description that `/api/docs/` of a running server also shows. @@ -899,127 +899,74 @@ Report the install status of the external binaries unshackle depends on (the sam --- -## Remote-dl sessions +## Remote sessions -!!! note "Developer feature" - The `/api/session/*` endpoints power unshackle's **remote download** mode. A thin local client authenticates once against a remote server, then fetches titles, tracks, and segments, and proxies DRM licensing back through it. The server mounts these endpoints in `--remote-only` mode, and they are what the built-in `RemoteService` client drives. Most end users never call them directly. +The `/api/session/*` and `/api/tunnel` routes carry the remote sessions of `dl --remote`. The +[remote session protocol](remote-sessions.md) page is their reference: each route, its request and +response, the login states, the licensing modes and the error codes. -The server holds remote sessions in memory. They expire after `serve.session_ttl` (default 300s) without a request, except while the login runs, which can stay idle for the larger of `session_ttl` and 600s. A remote session whose client is gone ends sooner: see [Client presence](remote-sessions.md#client-presence). A remote session binds to the IP that made it, so the server rejects a request from a different IP with `403 FORBIDDEN`. +## Remote services relay -### Remote session lifecycle overview +A full-mode server can run a service through one of its own `remote_services` servers. +`GET /api/config` lists their names in `remote_services`, and `GET /api/services?remote=` +lists the services of that server, each with `remote` set to the name. Add `"remote": ""` to +`POST /api/search`, `/api/list-titles`, `/api/list-tracks` or `/api/download`, and the server opens +a remote session with its own API key for that server: the remote server logs in and resolves titles, +tracks and licences, and a download still runs, decrypts and muxes here. The tag may be any case or +an alias, and your allowlist applies to it. A `--remote-only` server does not relay. -```text -POST /api/session/create → returns session_id, status "authenticating" -GET /api/session/{id}/channel → WebSocket: prompts, CDM calls, logs, login state, drain -GET /api/session/{id}/prompt → without the channel: poll until authenticated (submit answers via POST) -GET /api/session/{id}/titles → list titles -POST /api/session/{id}/tracks → tracks + chapters (with URLs) for one title; a track that resolves its URL on use has resolve_url true and no URL -POST /api/session/{id}/segments → resolve segment URLs / DRM / headers per track -POST /api/session/{id}/segment_filter → HLS segments the service drops (ads, bumpers) -POST /api/session/{id}/samples → decrypt cbcs samples of a track on the server -POST /api/session/{id}/license → proxy or server-CDM DRM licensing -POST /api/session/{id}/keys → store the content keys the client proved on a track -POST /api/session/{id}/keys/bad → report a server-vault content key that did not decrypt -DELETE /api/session/{id} → tear down, harvest updated cache -``` +- An unknown name is `400 INVALID_PARAMETERS`, a server that does not answer is + `SERVICE_UNAVAILABLE`, a server that rejects the API key of this server is `AUTH_FAILED` (424), + and a tag that it does not offer is `INVALID_SERVICE`. +- List calls from the same API key for the same title, profile, proxy, client region and service + options share one remote session, which closes after 120 seconds unused. +- When the server stops, a list call that waits on the login of a new remote session, or starts one, + gets `SERVER_DRAINING` (409). A call that opens a lost remote session again can be cut too: + `list-titles` then gets `SERVER_DRAINING`, and `list-tracks` that or `SERVICE_ERROR` (422). +- An optional `client_name` names your client on the dashboard of the remote server as + `serve ()`. +- A relayed search opens no remote session. The server sends its own credentials, cookies and cache + for the `profile` with the search. A service that searches with no login gets none of them. -### Slow responses +A remote login that waits on you (a pair code or URL to approve on another device, or a question +such as an OTP) cannot answer through a list call. Poll `GET /api/remote/logins` beside it. A remote +download job shows the same text as its own `notice`, and asks a question through `input_prompt` as +a local job does. -The `titles`, `tracks`, `segments` and `license` routes can take minutes on a large catalogue. When the -answer is not ready after 30 seconds, the route sends status `200` and the headers. It then -sends a newline every 30 seconds until the JSON body is ready. JSON parsers ignore the leading -newlines. This keeps the connection open through a reverse proxy that closes an idle request. +### `GET /api/remote/logins` -!!! warning "A late failure has status `200`" - The server sent the status before the work ended. A failure after the first 30 seconds - arrives as the [standard error body](errors.md#the-standard-error-shape) with status `200`. - Check `status` in the body, not only the HTTP status. The body has no HTTP status field. - Use `error_code` and `retryable` to decide what to do. - -A slow response is not gzip-compressed. Gzip output cannot start before the body is ready, and -the newlines must go out at once. - -### `POST /api/session/create` - -Make a remote session for a service and title. Authentication runs asynchronously in the background. This call returns immediately with `status: "authenticating"`, and you then poll the prompt endpoint. The body accepts `service` and `title_id` (both required). It also accepts a broad set of optional keys, because the body allows `additionalProperties`. These are `session_id`, `credentials` (`{username, password, extra?}`), `cookies` (base64 of zlib-compressed Netscape cookie file), `proxy`, `no_proxy`, `profile`, `cache` (map of forwarded cache files, keyed by the file path relative to the service cache directory with `/` separators and no `.json` suffix, so a nested key such as `session_web/` lands in a subdirectory), `client_region`, `proxy_region`, `cdm_type`, `range_`, `vcodec`, `quality`, `best_available`, `dl_params`, `plugins`, `client`, and any service CLI options. `plugins` maps the id of each DRM plugin that the client loads to `{version, device?}`; `device` holds the plain values of the device attributes that the plugin names in `device_facts`. The server refuses a title with a track of a plugin that is not in `plugins` (or a body with no `plugins`) on `POST /api/session/{id}/tracks` with `DRM_ERROR`, and gives `device` to the service only in a remote session that the client's device licenses. A `plugins` value over 16384 bytes of JSON, or of another shape, gets `INVALID_INPUT`. `proxy_region` is the country code the client resolved `proxy` from; the server matches it against its own accounts. `client` is a freeform object the dashboard shows as sent (the CLI puts `version`, `code_hash`, `platform` and a redacted `argv` in it); the server ignores it above 4096 bytes of JSON. - -`session_id` is the ID that you give the remote session, so that you can delete it before this call answers. It must be the canonical text of a version 4 UUID. Without it, the server makes the ID. A remote session with your ID ends when you send no request for it and open no channel within 150s of the create. A second create with the same ID from the same API key and IP ends the first one if the first one has not answered, and replaces its remote session when the new one is stored. A second create that fails leaves that remote session open. - -`dl_params` is an object with the `dl` track selection: `lang`, `v_lang`, `a_lang` and `s_lang` (arrays of language strings), `acodec` (an array of audio codec names or `dl -a` aliases such as `ddp`), and `forced_subs` and `exact_lang` (booleans). The service reads these values from `ctx.parent.params`. The server uses the `dl` default for each absent value. It refuses a malformed value, an unknown codec, range or vcodec name, and a height of 0 or less with `INVALID_PARAMETERS`. The flat `range_`, `vcodec`, `quality`, `best_available` and `generate_dv` keys are `dl` values on this route. On the list and search routes they are `dl` values only when the body has `service_params`. - -Service CLI options also travel in a nested `service_params` object. When the body has `service_params`, the server reads service options only from it, and a flat key with the same name stays a `dl` value. `profile` at the top level always means the credentials profile, never a service's own `--profile` option. - -The `proxy` value must be a full proxy URI, unless the operator gives your API key `server_proxy` in the `serve.users` config. Without `server_proxy`, a proxy URI gets `INVALID_PROXY` when its host is not a public address, does not resolve, or is not a plain host name or IP address. Without `server_proxy`, the server does not resolve country codes with its own proxy providers. It rejects the request with `INVALID_PROXY` when no `proxy` is set and the reported `client_region` differs from the server's region. A request that reports no `client_region` is not blocked. Pass `proxy` with your own proxy, or `no_proxy` to accept the server's own connection. With `server_proxy`, the server resolves a country code and picks a proxy for your `client_region` itself. A Control D resolver, `controld://@dns.controld.com`, counts as a full proxy URI: the server runs a forwarder for it and needs no Control D configuration of its own. A proxy URI needs an `http`, `https` or `socks` scheme: the server answers `INVALID_PROXY` to a `host:port` value, also with `server_proxy`. +The logins of your list calls that wait on a remote server. An admin key sees the logins of every API +key. === "Response `200`" ```json { - "session_id": "d4e5f6a7-...", - "service": "EXAMPLE", - "status": "authenticating", - "server_account": false + "logins": [ + { + "id": "3f2a9c...", + "remote": "my_server", + "service": "EXAMPLE", + "title_id": "0ABCDEF", + "prompt": null, + "notice": "Open https://example.com/activate and enter ABCD-1234", + "qr": "https://example.com/activate?code=ABCD-1234" + } + ] } ``` -`server_account` is `true` when the server authenticated with one of its own accounts (`serve.server_accounts`). Otherwise the server uses only what the client sent, and never falls back to its own credentials. When the login succeeds and the remote session does not use a server account, the login belongs to the client, and the client gets cookies, auth headers, and the remote session cache back. A remote session on the server's device is the exception: the client gets its cookies back, but no auth headers and no cache. For a server-account remote session the tracks and segments responses carry no cookies and no auth headers. The server also drops secret-looking keys from track data, and the cache stays on the server. A server-account service also refuses a client proxy URI, because the server's login would pass through it. +| Field | Description | +| --- | --- | +| `id` | The ID to answer the prompt with. | +| `remote`, `service`, `title_id` | The remote server, the service and the title of the list call. | +| `prompt` | What the login asks you (an OTP, a PIN), or `null`. | +| `notice` | What the login shows you while it waits, such as a URL and a pair code, or `null`. | +| `qr` | The text of a QR code to scan with the prompt or notice, or `null`. | -| Status | Error code | Meaning | -| --- | --- | --- | -| `200` | - | Session created; authentication in progress. | -| `400` | `INVALID_INPUT` | Missing `service` or `title_id`, or a `session_id` that is not the canonical text of a version 4 UUID. | -| `400` | `INVALID_PARAMETERS` | Invalid `range_`, `vcodec`, `quality` or `dl_params` value. | -| `403` | `FORBIDDEN` | Another API key or another IP has the `session_id`. | -| `404` | `SESSION_NOT_FOUND` | A `DELETE` or a newer create with the same `session_id` ended this create. | -| `400` | `INVALID_SERVICE` | Unknown or disallowed service. | +### `POST /api/remote/logins/{login_id}/input` -### `GET /api/session/{session_id}/channel` - -Open the remote session channel: a WebSocket that carries the prompts, CDM calls, log records, login state and drain state of the remote session, and the client's answers. Pass `since=` to get only the log records newer than that sequence number. The server closes the WebSocket with code `4404` when the remote session ends. See [The remote session channel](remote-sessions.md#the-remote-session-channel) for the messages. - -| Status | Error code | Meaning | -| --- | --- | --- | -| `101` | - | WebSocket open. | -| `403` | `FORBIDDEN` | Request IP differs from the remote session creator. | -| `404` | `SESSION_NOT_FOUND` | No such session. | - -### `GET /api/session/{session_id}/prompt` - -The polling fallback of the remote session channel. Poll for the authentication status and any pending interactive prompt (OTP, PIN, device code). Response variants: - -=== "Authenticating" - - ```json - { "status": "authenticating" } - ``` - -=== "Pending input" - - ```json - { "status": "pending_input", "prompt": "Enter the code sent to your email:" } - ``` - -=== "Authenticated" - - ```json - { "status": "authenticated" } - ``` - -=== "Failed" - - ```json - { "status": "failed", "error": "Invalid credentials" } - ``` - -| Status | Error code | Meaning | -| --- | --- | --- | -| `200` | - | Status returned. | -| `403` | `FORBIDDEN` | Request IP differs from the remote session creator. | -| `404` | `SESSION_NOT_FOUND` | No such session. | - -### `POST /api/session/{session_id}/prompt` - -Submit a response to a pending prompt. Body: `{ "response": "..." }` (required). +Answer the prompt of a remote login. Body: `{ "response": "..." }` (required). === "Response `200`" @@ -1029,258 +976,10 @@ Submit a response to a pending prompt. Body: `{ "response": "..." }` (required). | Status | Error code | Meaning | | --- | --- | --- | -| `200` | - | Response accepted. | -| `400` | `INVALID_INPUT` | Missing `response`, or no prompt is pending. | -| `404` | `SESSION_NOT_FOUND` | No such session. | - -### `GET /api/session/{session_id}/logs` - -The polling fallback of the remote session channel. Drain the service's server-side log output for this remote session. The server mirrors every log call the service makes (`self.log.info`, warnings, errors) into a bounded per-session buffer, so a remote client can see why an auth, title, or license step failed. Pass `since=` to get only records newer than the last drained sequence number. Works in every auth state, including `failed`. - -=== "Response `200`" - - ```json - { - "session_id": "a1b2c3", - "logs": [ - { "seq": 1, "level": "INFO", "message": "Signed in as profile 'Main'", "ts": 1724990000.1 }, - { "seq": 2, "level": "WARNING", "message": " - ThePlatform returned no streams", "ts": 1724990002.7 } - ], - "last_seq": 2 - } - ``` - -| Status | Error code | Meaning | -| --- | --- | --- | -| `200` | - | Records returned (empty list when nothing new). | -| `404` | `SESSION_NOT_FOUND` | No such session. | - -The buffer keeps the newest 500 records. Only the service instance's own logger is mirrored; core pipeline loggers stay on the server. A server-account session gets no log relay at all - auth-time service output can carry the operator account's identity, so it stays server-side. - -### `GET /api/session/{session_id}/titles` - -Fetch the titles for an authenticated remote session. -A slow answer arrives as a [slow response](#slow-responses). - -=== "Response `200`" - - ```json - { - "session_id": "d4e5f6a7-...", - "titles": [ { "type": "episode", "name": "Pilot", "id": "ep-1" } ] - } - ``` - -`collection` is present only when the service returned a music collection. It holds the facts of the collection itself: `kind`, `title`, `artist`, `year`, `total_tracks`, `total_discs`, `artwork_url`, `total_duration`, `owner` and `description`, for example `"collection": { "kind": "playlist", "title": "Example Playlist", "total_tracks": 93 }`. A fact that the collection does not have is absent. - -Requires an authenticated remote session. Otherwise it returns `404 SESSION_NOT_FOUND`. - -### `POST /api/session/{session_id}/tracks` - -Get tracks and chapters for a specific title within the remote session. Body: `{ "title_id": "..." }` (required). Unlike `list-tracks`, track objects here **include** download URLs, along with session headers/cookies and manifest data the client needs to download directly. A slow answer arrives as a [slow response](#slow-responses). - -`manifests` holds each served DASH/ISM manifest once. One URL can have more than one entry, such as when a service merges a second manifest under the same URL. `track_ids` names the tracks that each entry restores, and the client matches such a track only in that entry's manifest. For DASH, `filtered_period_ids` names the periods that the download skips, such as ad periods. A service can build an AdaptationSet of its own that the served manifest does not contain. `track_manifests` holds a one-track MPD for each such track, and the client re-parses that in place of the whole manifest. That MPD starts at the period of the track and keeps the content periods after it. - -`hls_playlists` holds the media playlist text of each HLS track that the service holds as text, with the track URL. A `file:` URL is never sent: such an entry has `url` set to `null`. The client keeps an entry only when it parses as a media playlist whose segment URIs are absolute `http` or `https` URLs, and is for the same URL as its track. Otherwise it logs `Refusing track : its HLS playlist ...` and drops the track. - -=== "Response `200`" - - ```json - { - "title": { "type": "episode", "name": "Pilot", "id": "ep-1" }, - "video": [ { "id": "v-1", "url": "https://...", "drm": [ ... ] } ], - "audio": [ { "id": "a-1", "url": "https://..." } ], - "subtitles": [ { "id": "s-1", "url": "https://..." } ], - "chapters": [ { "timestamp": "00:00:00.000", "name": "Intro" } ], - "attachments": [ { "url": "https://...", "name": "font.ttf", "mime_type": "font/ttf", "description": "" } ], - "manifests": [ { "type": "dash", "url": "https://...", "data": "", "track_ids": [ "v-1", "a-1" ], "filtered_period_ids": [ "ad-1" ] } ], - "track_manifests": [ { "track_id": "s-1", "type": "dash", "url": "https://...", "data": "" } ], - "hls_playlists": [ { "track_id": "v-1", "url": "https://...", "data": "" } ], - "session_headers": { "User-Agent": "..." }, - "session_cookies": { "sid": "..." }, - "session_cookie_jar": [ { "name": "sid", "value": "...", "domain": ".example.com", "path": "/", "secure": true } ], - "server_cdm_type": "widevine" - } - ``` - -| Status | Error code | Meaning | -| --- | --- | --- | -| `200` | - | Tracks returned. | -| `400` | `INVALID_INPUT` | Missing or unknown `title_id`. | -| `404` | `SESSION_NOT_FOUND` | No such session. | - -### `POST /api/session/{session_id}/segments` - -Get the download URL, DRM info, headers, cookies, and track data for the selected tracks. Body: `{ "track_ids": ["v-1", "a-1"] }` (required). A track that the tracks response sent with `resolve_url` gets its URL from the service here. The server makes one service call at a time per remote session, so parallel requests wait for each other. A slow answer arrives as described in [Slow responses](#slow-responses). - -=== "Response `200`" - - ```json - { - "tracks": { - "v-1": { "descriptor": "DASH", "url": "https://...", "drm": [ ... ], "headers": { ... }, "cookies": { ... }, "cookie_jar": [ ... ], "data": { ... } } - } - } - ``` - -`data` has the form of the track `data` in `list-tracks`: the JSON-safe part of the service-set `track.data`, without the `hls`, `dash`, and `ism` parser keys. `cookies` gives names and values only. `cookie_jar` gives the same cookies with their domain, path and `secure` flag, in the `session_cookie_jar` form of the tracks response. - -| Status | Error code | Meaning | -| --- | --- | --- | -| `200` | - | Segment info returned. | -| `400` | `INVALID_INPUT` | Missing `track_ids`. | -| `404` | `TRACK_NOT_FOUND` | An unknown track ID was requested. | - -### `POST /api/session/{session_id}/segment_filter` - -Get the HLS segments a service drops (ads, bumpers, dub cards). The server runs the service's own segment filter over the track's media playlist and returns only the URIs, so the client drops the same segments the service does. Body: `{ "track_id": "v-1" }` (required). `unwanted` is `null` when the track has no filter. The client keeps every segment when the server does not have this route. When the server answers with an error, the client stops the track download. - -=== "Response `200`" - - ```json - { "unwanted": ["https://cdn.example/hls/ad1.ts"] } - ``` - -| Status | Error code | Meaning | -| --- | --- | --- | -| `200` | - | Unwanted segment URIs, or `null`. | -| `400` | `INVALID_INPUT` | Missing `track_id`. | -| `404` | `TRACK_NOT_FOUND` | An unknown track ID was requested. | -| `422` | `SERVICE_ERROR` | The playlist request or the filter failed. | - -### `POST /api/session/{session_id}/samples` - -Decrypt the samples of a track that the service decrypts itself after the download. The tracks response lists those track IDs in `sample_decrypt_tracks`. The client downloads the file, then sends each `stsd` sample entry's samples here, and writes the plaintexts back in place. The query string names the track and the 1-based entry: `?track_id=a-1&entry=2`. - -- An empty body asks how the entry decrypts. The JSON response is `{ "key": "" }`, which the client then uses itself, or `{ "decrypter": true }`. -- An `application/octet-stream` body is a sample frame: a big-endian `uint32` count, one `uint32` length per sample, then the samples. Each sample is a ciphertext cut to whole AES blocks. The response is a frame of the same shape with the plaintexts in the same order. - -The client sends at most 8 MiB of samples per request, and the route accepts a body of up to 16 MiB. Binary frames keep the upload the size of the samples, and the server does not compress them. The route needs the `server_cdm` grant for the service, because the decrypter can use a process or an account of the server. - -| Status | Error code | Meaning | -| --- | --- | --- | -| `200` | - | The content key, `decrypter`, or the plaintext frame. | -| `400` | `INVALID_INPUT` | Missing `track_id`, a bad `entry`, a malformed frame, or a track the service does not decrypt. | -| `413` | - | The body is larger than 16 MiB. | -| `403` | `FORBIDDEN` | The API key has no `server_cdm` grant for the service. | -| `404` | `TRACK_NOT_FOUND` | An unknown track ID was requested. | -| `422` | `SERVICE_ERROR` | The service's decrypter failed. | - -### `POST /api/session/{session_id}/license` - -Get the content keys for the DRM. The `mode` field selects one of two modes. -A slow answer arrives as a [slow response](#slow-responses). - -**Proxy mode** (`mode: "proxy"`, the default) forwards the client's CDM `challenge` to the service's license endpoint and returns the raw license bytes: - -=== "Request" - - ```json - { "track_id": "v-1", "challenge": "", "drm_type": "widevine" } - ``` - -=== "Response `200`" - - ```json - { "license": "" } - ``` - -**Server-CDM mode** (`mode: "server_cdm"`) runs the full CDM flow on the server using the device configured for your API key, returning content keys directly. Use `track_id` for a single track or `track_ids` for a batch: - -=== "Single: Response `200`" - - ```json - { "keys": { "": "" }, "vault_keys": [""], "drm_type": "widevine" } - ``` - -=== "Batch: Response `200`" - - ```json - { "keys": { "v-1": { "": "" } }, "vault_keys": [""], "drm_type": "widevine" } - ``` - -| Field | Description | -| --- | --- | -| `track_id` / `track_ids` | Single track, or a batch of tracks. | -| `challenge` | Base64 CDM challenge (proxy mode). | -| `pssh` | Base64 PSSH. Server-CDM mode licenses this PSSH. Proxy mode gives it to the service licence callback as `pssh` (Widevine) or `pssh_b64` (PlayReady), the PSSH of the header the challenge is for. A proxy-mode PSSH that names a KID the track does not carry goes to no callback. | -| `drm_type` | `widevine` (default), `playready`, or the id of a DRM plugin that both peers load. In server-CDM mode the server's `cdm` mapping for the service decides the DRM system and the response `drm_type` names the system that licensed. A mapping with a device for each system takes the system of the device the remote session loaded. With no mapping, the client's value decides when the track carries that system; else a system the track carries decides, PlayReady first. The tracks response `server_cdm_type` names the system the same order gives for the title's tracks. A track whose DRM is a whole-file cipher takes `clearkeyctr` with no `pssh`: the service on the server licenses it. A track of a DRM plugin that licenses locally takes the plugin id with no `pssh` and `mode` `server_cdm`: the server answers in `keys` with the content key from a server vault or from a licence of its own plugin device, only in a session that uses the server CDM, and only under the licence cap (`SERVER_CDM_CAPPED` above it). | -| `mode` | `proxy` (default) or `server_cdm`. | -| `clear_tracks` (response) | Requested track ids that carry no DRM, so they have no keys. Absent when every requested track is encrypted. | -| `file_keys` (response) | Content keys of whole-file ciphers, by track id, for a single track and for a batch. Absent when no requested track holds such a cipher. | -| `vault_keys` (response) | KIDs whose content key came from a server vault, not the CDM. The client proves such a content key with a decode before it trusts it; the field is absent when every content key came from the CDM. | -| `bridge_kids` (response) | For a batch: the KIDs of the init segments of each FairPlay-only track that the server licensed through the FairPlay bridge, by track id. The client needs the content key of each of these KIDs, or the download of that track stops. Absent when the batch has no such track. | - -| Status | Error code | Meaning | -| --- | --- | --- | -| `200` | - | License/keys returned. | -| `400` | `INVALID_INPUT` | Missing challenge/PSSH, or no CDM device configured for the API key. | -| `400` | `INVALID_PARAMETERS` | Unsupported `drm_type`. | -| `404` | `TRACK_NOT_FOUND` | Unknown track ID. | -| `404` | `NO_CONTENT` | Server CDM produced no keys. | -| `422` | `SERVICE_ERROR` | The service aborted during licensing. | - -### `POST /api/session/{session_id}/keys` - -Store the content keys that the client proved on a track and that the server did not serve to this remote session. The server stores a content key only for a KID that a track of the remote session names and that no local server vault holds a content key for. It never stores a pair flagged bad, and it never removes a flag. The server answers when its local vaults hold the pairs, and sends them to its other vaults after the answer. The client sends each key of a licence when the licence returns, and each vault key after its decode check passes. A licence key of a FairPlay-only track that the client licensed through the bridge goes only after its decode check passes, so a client without FFmpeg does not send it. - -```json -{ "track_id": "", "keys": { "": "" } } -``` - -| Status | Error code | Meaning | -| --- | --- | --- | -| `200` | - | `{}`, whatever the server stored. | -| `404` | `SESSION_NOT_FOUND` | Unknown remote session. | - -### `POST /api/session/{session_id}/keys/bad` - -Report a content key from `vault_keys` that did not decrypt the track. The server flags the pair in its local vaults and reports it to the vault that served it, and the next licence for that KID reaches the CDM. When the CDM returns the same pair, the server removes the flag. The client never learns the server vault names. - -```json -{ "kid": "", "key": "" } -``` - -| Status | Error code | Meaning | -| --- | --- | --- | -| `200` | - | `{"flagged": true}`: the pair is flagged. `{"flagged": false}`: the CDM licensed the pair, so it is not flagged. | -| `400` | `INVALID_INPUT` | This remote session was not served that pair. | -| `404` | `SESSION_NOT_FOUND` | Unknown remote session. | - -### `GET /api/session/{session_id}` - -Return remote session metadata and validity. - -=== "Response `200`" - - ```json - { - "session_id": "d4e5f6a7-...", - "service": "EXAMPLE", - "valid": true, - "expires_in": 300, - "draining": false, - "track_count": 4, - "title_count": 10 - } - ``` - -`404 SESSION_NOT_FOUND` if the remote session does not exist or has expired. - -### `DELETE /api/session/{session_id}` - -Tear down a remote session. The server cancels its input bridge, harvests any updated cache files, and deletes the remote session and its cache directory. A create of the same API key and IP that still runs under this ID ends too: it makes no remote session and answers `404 SESSION_NOT_FOUND`. If no remote session exists yet, the `DELETE` answers `200` with no `cache`. - -=== "Response `200`" - - ```json - { - "status": "ok", - "cache": { "tokens": "", "session_web/": "" } - } - ``` - -The `cache` field is present only if the remote session produced cache files and the login belongs to the client. Each cache key is the file path relative to the session cache directory, with `/` separators and no `.json` suffix, so a file in a subdirectory keeps its place on the client. The server rejects a cache key with a drive letter, a root, a `..` segment, or an empty segment, and so does the client. `404 SESSION_NOT_FOUND` if the remote session does not exist. +| `200` | - | Answer accepted. | +| `400` | `INVALID_INPUT` | No `response`. | +| `404` | `NOT_FOUND` | No such remote login for this API key. | +| `409` | `CONFLICT` | The login asks nothing now. | --- @@ -1320,4 +1019,4 @@ When a generic (uncategorized) exception reaches a handler, unshackle inspects i - [REST API overview](index.md). What the server is and when to use it. - [Authentication](authentication.md). Keys, server modes, and the `X-Secret-Key` header. - [Quickstart](quickstart.md). A first end-to-end request walkthrough. -- [Downloading](../../guide/downloading.md). The `dl` flags mirrored by `POST /api/download`. +- [CLI reference: `dl`](../../guide/cli-reference.md#dl). The `dl` flags mirrored by `POST /api/download`. diff --git a/docs/dev/rest-api/errors.md b/docs/dev/rest-api/errors.md index b6ef2265..1ebfa457 100644 --- a/docs/dev/rest-api/errors.md +++ b/docs/dev/rest-api/errors.md @@ -124,7 +124,7 @@ while the server restarts. | `NOT_FOUND` | 404 | A requested resource (title, history entry, and so on) does not exist. | | `NO_CONTENT` | 404 | The request was valid but produced nothing: no matching titles, tracks, episodes, or keys. | | `JOB_NOT_FOUND` | 404 | The referenced download job does not exist. | -| `SESSION_NOT_FOUND` | 404 | The remote-dl session does not exist or has expired. | +| `SESSION_NOT_FOUND` | 404 | The remote session does not exist or has expired. | | `TRACK_NOT_FOUND` | 404 | A referenced track ID is not present in the remote session. | | `CONFLICT` | 409 | The target resource is in a state that disallows the action (retrying a running job, prioritising a non-queued job, clearing cache during an active download). | | `SERVER_DRAINING` | 409 | The server is about to restart or stops, and starts no new remote session, remote login or download job. Open work continues. Retryable after the restart. A `dl --remote` client waits for the restart and opens a new remote session. | @@ -232,9 +232,9 @@ body that uses an integer `status` and no `error_code` or `timestamp`. ## Late failures with status `200` -The remote session `titles`, `tracks` and `license` routes send status `200` and the headers +The remote session `titles`, `tracks`, `segments` and `license` routes send status `200` and the headers when the work takes longer than 30 seconds. They then send a newline every 30 seconds to keep -the connection open. See [Slow responses](endpoints.md#slow-responses). A failure after that +the connection open. See [Slow responses](remote-sessions.md#slow-responses). A failure after that time arrives as the standard error body, but with status `200`. The body has no field for the HTTP status that the error would otherwise have. `error_code` and `retryable` stay in the body. diff --git a/docs/dev/rest-api/index.md b/docs/dev/rest-api/index.md index 6849f4cc..30cf7bdd 100644 --- a/docs/dev/rest-api/index.md +++ b/docs/dev/rest-api/index.md @@ -28,10 +28,10 @@ calls you can script against: - **History and housekeeping**: read the log of finished jobs, inspect the server's effective (redacted) configuration, examine external tool versions, and clear caches or temp files. -- **Remote-download sessions**: a thin local client can authenticate against a - service *on the server*, then pull titles, tracks, and segment info back, and proxy +- **Remote sessions**: a thin local client can authenticate against a + service *on the server*, then pull titles, tracks, and segment info back, and relay DRM licensing. This is how one machine with the credentials and CDMs can serve - downloads to another. See [Remote Sessions](remote-sessions.md). + downloads to another. See the [remote session protocol](remote-sessions.md). Because every download runs as a queued job in a separate job worker process, the API is well suited to running unattended: submit work, come back later, and read the result. @@ -194,29 +194,19 @@ request and response in full. | `POST` | `/api/maintenance/clear-temp` | Clear the temp directory. | | `POST` | `/api/maintenance/refresh-services` | `git pull` each configured service repository and re-import the services that changed. | -### Remote-download sessions +### Remote sessions + +The `/api/session/*`, `/api/tunnel` and `/api/tunnel/check` routes carry the remote sessions of +`dl --remote`. The [remote session protocol](remote-sessions.md#routes) lists each route. | Method | Path | Purpose | |---|---|---| -| `POST` | `/api/session/create` | Start a server-side, authenticated service session. | -| `GET` | `/api/session/{session_id}` | Remote session info and time-to-live. | -| `DELETE` | `/api/session/{session_id}` | Tear down a session. | -| `GET` | `/api/session/{session_id}/titles` | Titles for the session's title ID. | -| `POST` | `/api/session/{session_id}/tracks` | Tracks (with URLs) for a chosen title. | -| `POST` | `/api/session/{session_id}/segments` | Per-track segment/download details. | -| `POST` | `/api/session/{session_id}/segment_filter` | Server-side HLS segment filter results for one track. | -| `POST` | `/api/session/{session_id}/samples` | Server-side cbcs sample decryption for one track. | -| `POST` | `/api/session/{session_id}/license` | Proxy or server-side DRM licensing. | -| `POST` | `/api/session/{session_id}/keys` | Store the content keys the client proved on a track. | -| `POST` | `/api/session/{session_id}/keys/bad` | Report a server-vault content key that did not decrypt. | -| `GET` | `/api/session/{session_id}/channel` | WebSocket of the remote session channel: prompts, CDM calls, logs, login state. | -| `GET` | `/api/session/{session_id}/logs` | Drain the service's server-side log output. | -| `GET` | `/api/session/{session_id}/prompt` | Poll for interactive auth status/prompt. | -| `POST` | `/api/session/{session_id}/prompt` | Submit an answer to an auth prompt. | +| `GET` | `/api/remote/logins` | The logins of a [relayed](endpoints.md#remote-services-relay) list call that wait on you. | +| `POST` | `/api/remote/logins/{login_id}/input` | Answer the prompt of such a login. | !!! note "Remote-only routes" - The health, services, search, and `/api/session/*` routes are the ones exposed - when the server runs with `--remote-only`. Everything else (downloads, jobs, + A server that runs with `--remote-only` exposes only the + [remote session routes](remote-sessions.md#routes) and the dashboard routes. Everything else (downloads, jobs, history, config, maintenance) is only available in the full or `--api-only` modes. ## Authentication in one line @@ -246,8 +236,8 @@ the full model, including per-key service allowlists. shape, endpoint by endpoint. - **[Job Lifecycle](job-lifecycle.md)**: how a download moves from `queued` to a terminal state, live progress, cancellation, and retries. -- **[Remote Sessions](remote-sessions.md)**: the `/api/session/*` flow for driving a - service from a thin remote client. +- **[Remote Session Protocol](remote-sessions.md)**: the routes, login states, + licensing modes and message shapes of a remote session. - **[Error Responses](errors.md)**: the standard error envelope, error codes, and their HTTP statuses. diff --git a/docs/dev/rest-api/job-lifecycle.md b/docs/dev/rest-api/job-lifecycle.md index c740858e..905577a1 100644 --- a/docs/dev/rest-api/job-lifecycle.md +++ b/docs/dev/rest-api/job-lifecycle.md @@ -418,7 +418,7 @@ Each job carries a cancellation event. When you `DELETE` a live job: subprocess (escalating to `kill()` if it does not exit within 5 seconds), and raises a cancellation so the task unwinds. The subprocess model is what makes this a clean, immediate stop rather than a cooperative one. A job with the `remote` parameter first ends its - [remote session](remote-sessions.md#when-the-client-ends-a-remote-session), in at most 4 + [remote session](../../guide/remote-sessions.md#when-the-client-ends-a-remote-session), in at most 4 seconds, and runs no post-script after the cancel. ### Secret handling in serialized jobs @@ -437,4 +437,4 @@ or logs them. - [Endpoints](endpoints.md): the full request/response reference for every job endpoint. - [Error Responses](errors.md): the error envelope, codes, and HTTP statuses a failed job reports. - [Authentication](authentication.md): the `X-Secret-Key` header and per-key service allowlists that gate job creation and retry. -- [Downloading](../../guide/downloading.md): the equivalent options on the `dl` command line. +- [CLI reference: `dl`](../../guide/cli-reference.md#dl): the equivalent options on the `dl` command line. diff --git a/docs/dev/rest-api/remote-sessions.md b/docs/dev/rest-api/remote-sessions.md index bdeff7ad..da5466ba 100644 --- a/docs/dev/rest-api/remote-sessions.md +++ b/docs/dev/rest-api/remote-sessions.md @@ -1,921 +1,831 @@ -# Remote Service Sessions +# Remote session protocol -A **remote session** lets one machine do the hard, service-specific work -(authenticating to a streaming service, listing titles, resolving tracks and -manifests, and, optionally, DRM licensing) while another machine runs the actual -download, decryption, and muxing locally. +The remote session protocol is the one record of the routes, login states, error codes and message +shapes that a `--remote` client and the server share. A remote session keeps an authenticated +service on the server between requests. The client logs in one time, then asks for titles, tracks, +segments and licences in the same remote session. The client downloads, decrypts and muxes. -This is the mechanism behind unshackle's client/server "remote download" workflow. -A thin local client (`RemoteService`) talks to an unshackle `serve` instance over -HTTP. The server keeps an authenticated service instance alive between requests so -the client can authenticate once and then make many follow-up calls against the -same remote session. +The record is `unshackle/core/remote_protocol.py`: both the client (`unshackle/core/remote_service.py`, +the reference client) and the server (`unshackle/core/api/`) read it. Titles, tracks and DRM cross +in the wire form of `unshackle/core/wire.py`. To set up `dl --remote`, read +[Remote sessions](../../guide/remote-sessions.md) in the user guide. -!!! note "Why you'd use this" - - The server has service accounts, cookies, or a CDM you do not want to copy to - every machine. - - You want to do downloads on a fast/local machine but keep credentials and - licensing centralised. - - A service is region-locked to where the server lives, and the client is not. +## Routes ---- - -## The big picture - -``` -┌──────────────────────────┐ HTTP (X-Secret-Key) ┌──────────────────────────┐ -│ Local machine (client) │ ───────────────────────────────▶ │ unshackle serve │ -│ │ │ │ -│ unshackle dl --server │ POST /api/session/create │ authenticated Service │ -│ │ GET /api/session/{id}/titles │ instance, kept alive in │ -│ • track selection │ POST /api/session/{id}/tracks │ an in-memory session │ -│ • download / decrypt │ POST /api/session/{id}/segments │ store (TTL-based) │ -│ • mux │ POST /api/session/{id}/license │ │ -│ │ DELETE /api/session/{id} │ │ -└──────────────────────────┘ └──────────────────────────┘ -``` - -The client implements the same interface `dl` expects from a normal service, but -every service-facing method proxies to the server. Everything after track -selection (downloading segments, decrypting, and muxing) runs locally. - -!!! note "Migration: `remote_dl` is gone" - The `RemoteService` adapter lives inside the ordinary `dl` command and replaces - the old standalone `remote_dl` command. If you have prior scripts or docs that - invoke `remote_dl`, use `dl` with a configured remote server instead. The - functionality now rides on `dl` through `RemoteService`. - -For the auth-facing endpoints, header format, and error shapes referenced below, -see [Authentication](authentication.md) and the endpoint reference in -[the REST API index](index.md). - ---- - -## Configuring a remote server (client side) - -On the **client**, add a `remote_services` block to your `unshackle.yaml`. Each -entry names a server and provides its URL and API key. - -```yaml title="unshackle.yaml (client)" -remote_services: - my_server: - url: "https://my-box.example:8786" - api_key: "your-api-key" - # Optional: let the server's CDM do the licensing instead of a local CDM - server_cdm: true - # Optional: per-service config overrides applied locally (title_map, cdm, server_cdm, etc.) - services: - EXAMPLE: - server_cdm: false # this service licenses with your local CDM - title_map: - "0ABCDEF": "The Show (Renamed Locally)" -``` - -| Key | Required | Meaning | -|---|---|---| -| `url` | yes | Base URL of the `unshackle serve` instance (no trailing slash needed) | -| `api_key` | no | Sent as the `X-Secret-Key` header on every request | -| `server_cdm` | no | `true` asks for the server's CDM, `false` uses your local device; unset follows the API key's server CDM grant | -| `services` | no | Per-service local config overrides, keyed by service tag in any case; a `server_cdm` here replaces the server entry's value for that service | - -!!! warning "Port default" - The `unshackle serve` default port is **`8786`** (not `8080`). Use the port - your server binds. Some older example snippets show `8080`, which is - not the default. - -### Selecting a server - -If you configure exactly one server, unshackle uses it implicitly: - -```bash -unshackle dl --remote EXAMPLE 0ABCDEF -``` - -If you configure **more than one** server, you must pick one with `--server`: - -```bash -unshackle dl --remote --server my_server EXAMPLE 0ABCDEF -``` - -With no `remote_services` configured at all, unshackle raises a clear error telling -you to add the block shown above. - -### Making a service remote by default - -To run a service on the server without `--remote`, set `remote` in the -[`services`](../../reference/configuration/services.md#services) block, not in the -`services` sub-dict of `remote_services`. Add `server` to select one of several servers: - -```yaml title="unshackle.yaml (client)" -services: - EXAMPLE: - dl: - remote: true - server: my_server -``` - -`unshackle dl EXAMPLE 0ABCDEF` and `unshackle search EXAMPLE "query"` then run on -`my_server`. A `--server` on the command line overrides the configured server, and `--local` -runs the local service code for that run. The global -`dl: remote: true` makes every `dl` run remote, but it has no effect on `search`. -The REST API ignores both settings: a job runs remote only when its request asks for it. - ---- - -## What happens during a download - -From your point of view the command looks like an ordinary download. Under the -hood the client walks a remote session through its lifecycle. - -=== "1. Create + authenticate" - - The client calls `POST /api/session/create`, forwarding whatever it can so the - server does not have to prompt: - - - Local **credentials** for the service/profile (`{username, password, extra?}`) - - Local **cookies**, compressed and base64-encoded - - A resolved **proxy**, or, if you did not set one, your detected - **client region**. A client that reports no region is not blocked. The - proxy must be a full proxy URI on a public host unless the operator gives your API key - `server_proxy`. Without `server_proxy` the server does not resolve country - codes with its own proxy providers, and it rejects the remote session when - it sits in a different region from the reported one, asking the client to - pass `--proxy` with its own proxy, or `--no-proxy` to accept the server's - own connection. With `server_proxy` the server picks a proxy that matches - the client region itself. For `--proxy controld:ca` the client points its - Control D profile at the region and sends only the resolver, as - `controld://@dns.controld.com`. The server counts it as a full proxy - URI and runs its own forwarder for it. A bare region skips Control D, because its - proxy is a forwarder on the client. See - [Control D](../../guide/proxies-and-vpn.md#control-d). - The client also downloads playlists and segments through the same proxy, - as a local run does. `--no-proxy-download` and `--proxy-download` change - that for downloads only. - - A `--local-proxy` goes as `tunnel:`. The client opens - `GET /api/tunnel` first, and the server replaces the ID with a loopback SOCKS5 - proxy that relays to the client's own connection. See - [Send the server's requests through your machine](../../guide/proxies-and-vpn.md#send-the-servers-requests-through-your-machine). - - Track-selection hints (`range_`, `vcodec`, `quality`, `best_available`, - `generate_dv`) so the server fetches the right manifests - - Your language and audio codec selection (`-l`, `-vl`, `-al`, `-a`, `-fs`) - in a `dl_params` object. Some services fetch one manifest - for each audio language, and pick the languages from these values - - Your local per-service **cache files** (e.g. refreshed tokens), including - files in subdirectories of the service cache directory, but only the files - for the active profile. The client withholds a file whose path, in any - directory or file name, embeds a hash of another credential or the name of - another profile. One profile's tokens - therefore never reach the server while you use a different profile. At - worst, a withheld file makes the server authenticate again - - The server uses its own accounts only when the operator lists the service in - `serve.server_accounts` and gives your API key `server_accounts` in `serve.users`. - For any other service, a client that sends no credentials or cookies authenticates - with nothing. For a listed service the client sends no credentials, cookies, or - cache at all: the server picks one of its own accounts that works in your region and - rotates through them. `--proxy ca` picks a `ca` account. - - `GET /api/services` advertises the regions those accounts cover. When your own - region is not one of them and you set no `--proxy`, the client resolves a proxy for - the first advertised region itself, so both sides sit in a region the account - works in. This is a bare region query, so it skips Control D. A server-account - service does not accept a `controld://` resolver from the client. - - The server responds immediately with a session ID and a status. Authentication - runs in the background on the server. - -=== "2. Interactive prompts (if needed)" - - Some services need a one-time code, PIN, or device confirmation. When the - server's auth flow asks for input, the remote session enters `pending_input`. The - server sends the prompt to the client, the client shows it to you locally, collects - your answer, and sends it back. The server's auth thread resumes with your response. - - ```text - Enter the 6-digit code sent to your email: 483920 - ``` - - A client older than the `service_params` change sends service options as - flat body keys only. A flat key that shares a name with a transport field - (such as `profile`, which at the top level always means the credentials - profile) no longer reaches the service; the server logs a warning naming - the dropped key. Update the client to send service options under - `service_params`. - - The server also mirrors the service's own log output (`self.log`) into a - per-session buffer and sends each record to the client, which prints the records - locally, so you see the server-side reason when a step fails. - -=== "3. Titles + tracks" - - Once authenticated, the client fetches the title list, then the tracks for the - chosen title. The tracks come back with playback URLs, and the server ships - DASH/ISM manifests as compressed XML so the client can re-parse them locally for - downloading. A service can build an AdaptationSet of its own that the served - manifest does not contain. Each such track gets a one-track MPD in - `track_manifests`, with the content periods after its own, and the client - re-parses that instead. An HLS track whose service holds its media playlist as text - gets that text in `hls_playlists`. The client drops the track when the text is not a - media playlist with absolute `http` or `https` segment URIs. The client skips the same DASH periods as the server. Any - `session_headers` and cookies the server used are merged into the - client's local HTTP session. Each cookie in `session_cookie_jar` keeps its - domain, path and `secure` flag, so it goes only to its own hosts. `session_cookies` carries - the same cookies as names and values only, for older clients. - - For a music collection (an album, a playlist, an artist listing), the title list reply also - has `collection`, with the facts of the collection itself, such as its kind, title, artist - and totals. The client builds its collection with them. It ignores the keys of - `collection` that it does not know, and stops with an error on a value of the wrong type. - Without `collection`, for example from an older server, the client has the songs only. - - The tracks response repeats the title. A service can rewrite title fields inside - `get_tracks`, so the client takes this copy in place of the one from the title - list. Each track carries the full local field set. After the manifest re-parse the - client overlays the JSON-safe part of the service-set `track.data`, so a service - value wins over the parser's. An attachment that the service wrote to a file on the - server travels as base64, and the client writes it to its own temp directory. - -=== "4. Licensing" - - For a DRM-protected title the client either **proxies** its CDM challenge through - the server, or, if `server_cdm: true`, asks the server to do the full CDM flow - and return the content keys directly. See - [Server-side vs. proxied CDM](#server-side-vs-proxied-cdm) below. - -=== "5. Download + close" - - The client downloads, decrypts, and muxes locally. While it works, the open - [remote session channel](#the-remote-session-channel) keeps the remote session alive, - so a long download does not let the remote session expire. On - completion, and also when `dl` exits early (`--list`, Ctrl+C, an error), it - deletes the remote session (see [When the client ends a remote session](#when-the-client-ends-a-remote-session)). - If the login belongs to the client, the `DELETE` - request returns the updated cache files (for example a refreshed token) and the - client saves them locally, so the **next** remote session can skip interactive - authentication. The login belongs to the client when it succeeds and the - remote session does not use a server account. This includes a pair code that - the user approves on another device. A server-account login never does, - and neither does a remote session on the server's device (see below). - The client saves only the returned files that pass the same profile check it - applies before it sends them, so a file for another profile cannot overwrite - that profile's local file. - -!!! tip "Renaming remote titles locally" - You can rename titles for a remote service you do not have installed locally by - adding a `title_map` under that service in your client `remote_services..services` - config. The server sends raw titles. Your local map wins. - - This is deliberate: the server does **no** `title_map` remapping of its own and - sends titles exactly as the service returns them. All remapping happens on the - client, applied to the titles the server sends back. It keeps the final output - name fully under the client's control and lets you rename titles even for - services you have no local install of. - ---- - -## Server-side vs. proxied CDM - -There are two ways DRM keys get resolved, chosen by the client's `server_cdm` flag. - -=== "Proxied CDM (server_cdm: false)" - - Your **local CDM** builds the license challenge. The client sends that challenge - to `POST /api/session/{id}/license`, the server forwards it to the service, and - the raw license bytes come back for your local CDM to parse. - - - Keeps your CDM local. The server only relays the license request. - - Used when `server_cdm` is `false`, or when it is unset and the API key has no server - CDM for the service. - - Also used for a run with `dl --cdm `, and, when `server_cdm` is unset, for a - service whose own entry in your `cdm` config named the loaded device. In each case the client sends - `server_cdm: false` when it creates the remote session, and the server builds the - service on your device even when the API key has the server CDM. - - A service option that the service lists in `SERVER_DEVICE_OPTIONS` keeps the server - CDM, and the service gets the server's device whatever device you have. From a server - `cdm` entry with a device for both DRM systems, it gets the device that the entry - lists first. The server reads the option from `service_params`, or from the top level of - a request that has no `service_params`. The create response gives the result in - `server_cdm`, and the client shows a warning when the server did not apply its choice. - - The service on the server sees your device, not the server's: its DRM system, - security level, system ID and device type. A CDM call that the service makes - (for example a session-key exchange at login) goes to your client as a `cdm_call`, - and your local CDM answers it. See [Your own device identity](#your-own-device-identity). - -=== "Server-side CDM (server_cdm: true)" - - The **server's CDM** does everything. The client sends track IDs (or a PSSH), - the server checks its key vaults, loads the device configured for your API key, - runs the CDM flow, and returns `KID:KEY` pairs directly. The client needs no - CDM. When the server's `cdm` entry for the service names a `widevine` and a - `playready` device, the server loads the device of your local CDM's DRM system. - See [`cdm`](../../reference/configuration/drm.md). - - - Enable with `server_cdm: true` in the server entry. - - The server tells the client which DRM type it used - (`widevine` or `playready`). - - A content key the server took from its own vault is unproven. The response - lists its KID in `vault_keys`, the client decrypts and checks that the output - decodes, and a wrong pair goes back to `POST /api/session/{id}/keys/bad`. The - server flags the pair in every local vault it holds, reports it to the vault - that served it, and the next licence for that KID skips the pair and reaches - the CDM. When the CDM returns the same pair, the server removes the flag, - because then the client's check was wrong. A server with no local SQLite - vault cannot store the flag. The server accepts a report only for a pair it - served to that remote session, and does not flag a pair its CDM licensed. - The client never learns the server vault names. - - A content key in the client's own vaults goes first, even when the server - already answered. The client proves it, and a server key waits as the next - candidate. - - When the server licence fails, or the server gives a track no content key, your - own device licenses the track only when the `cdm` entry for the service names the - loaded device (see [`remote_services`](../../reference/configuration/services.md#remote_services)). - Otherwise, or when that device also fails, the run stops at the licence step of - that track with one `DRM_ERROR` line. - -!!! note "A DRM type that the client does not know" - The client rebuilds the DRM of each track from the track list of the server. When the server - sends a DRM `type` that the client does not know, the client stops the title with one - `DRM_ERROR` line that names the type. Update the client to the version of the server. - -!!! note "A height limit on the server CDM" - An API key with `server_cdm_max_height` gets the server CDM only up to that height. The - session create response tells the client who licenses the session in `server_cdm` and gives - the limit in `server_cdm_max_height`. In a server CDM session, the batch licence response - lists each track the server refused to license live under `capped_tracks`. A single-track - server CDM licence answers `403 SERVER_CDM_CAPPED` for such a track. In both cases the client - reads its own key vaults first, then licenses those tracks in proxy mode with its own local - CDM. When the track has no DRM of that CDM's system, the client uses the device that its own - `cdm` entry names for the track's DRM system. With no such device, the download of that track - stops. See - [`server_cdm_max_height`](../../reference/configuration/services.md). - -### Your own device identity - -A service can need more than a licence challenge from your device: an ESN, model keys, or a -session-key exchange that runs on the CDM. The device never leaves your machine. Only these cross -the wire: - -- **Device facts.** When it creates the remote session, the client sends its DRM system, security level, - system ID and device type. The service sees a stand-in with these facts. -- **CDM calls.** When the service calls the CDM, the server sends a `cdm_call` to the client - and waits. The client makes the challenge, or parses the licence, on its own CDM. When - the service closes a CDM session, the server sends a `close` call, because a CDM holds - only a few sessions. The server sends each call on the remote session channel. Without - the channel, the client polls for calls during login and while one of its own requests - runs service code, so an idle remote session sends nothing extra. -- **Session keys only.** A `keys` call returns Widevine `OPERATOR_SESSION` and `SIGNING` - keys. It never returns a content key, and the client refuses a PlayReady `keys` call. - So a server cannot use your device to license titles for itself. -- **Identity config.** A service names the config keys a client may send (for example - `esn`, `Kpe`, `Kph`, `esn_map`). The server lists them in the service listing as - `client_config`. The client sends only those keys, from its own `services: :` - block in `unshackle.yaml`. When the client sends an identity, the server drops its own - value for each of those keys, so the two identities never mix. A mapping (such as - `esn_map`) merges the client's entries over the server's. A client entry replaces a - server entry with the same key, also when the server's key is a number. The server keeps - these values in the remote session's memory only. - -A service can also offer an option that builds the remote session on the server's own -device and identity, for the quality that device reaches. The session then makes no live -licence at all: each content key comes from the server vault or the client's own vaults, -and a content key that no vault holds stops the download with an error that names its KID, -when the client knows it. The create response sets `server_device` to `true` for such a -remote session. The service then uses the server's own config: the client's identity -values do not apply, but its preferences do (see [Your preferences](#your-preferences)). The client reads the -server vault only when the API key has the `server_vault` grant (or `server_cdm`); without -it, the client reads only its own vaults. The login tokens of such a remote session hold the -server's device identity, so the server keeps them: `DELETE` returns no cache files, and the -HTTP session headers and `track.data` lose their secret-looking keys, as for a server login. - -!!! note "The server vault in a session your device licenses" - With the `server_vault` grant (or `server_cdm`) on the API key, a remote session that your own - device licenses still takes content keys from the server vault. The server tries the - vault first. A track that no server vault holds goes back to your device. See - [`server_vault`](../../reference/configuration/services.md). - -### Your preferences - -The `preferences` block of a service is the place for user choices, such as a metadata -language or a subtitle format. It is not an identity, so it crosses `--remote` in every -licensing mode, whatever CDM the client has, and no service declares anything for it: - -- The client sends each entry of its own `services: : preferences:` block in - `unshackle.yaml` that is a string, a number or a boolean. It leaves out other entries and - logs one debug line for each. -- The server merges the entries key by key over its own `preferences` block for that - service. An entry that the client sends replaces the server's value, and a config key that - the client does not send keeps the server's value. The entries never count as an identity, - and they stay when the service builds the remote session on the server's device. -- The server refuses a `preferences` value that is not an object of strings, numbers and - booleans with `INVALID_INPUT`. - -A service reads its preferences from `self.config["preferences"]`, locally and over -`--remote` alike. Keep a value that changes the server's account (a profile, an account -type) out of `preferences` unless every client of the server may choose it: a server -account is shared, and the service can store the choice in its cache. - ---- - -## Remote session lifecycle and expiry - -Remote sessions live in an **in-memory store on the server**. They expire on a timer, or when their client is gone. You -generally never touch this directly, but it explains behaviour you might observe. - -| Behavior | Value | Notes | -|---|---|---| -| Idle session TTL | **300s** (5 min) default | Refreshed on every request to the session and when a `titles` or `tracks` request ends. A remote session does not reach this limit while a request works on it or while its remote session channel is open | -| Client presence | **180s**, **150s** or **90s** | The time that a client can be silent after it lost its channel, after `create`, or after it closed its channel. See [Client presence](#client-presence) | -| Max concurrent sessions | **100** default | When full, the least recently used remote session of the API key that holds the most is evicted. A remote session that a request works on goes last | -| Auth/input timeout | **600s** (10 min) | A remote session that still logs in, a prompt included, can stay idle for the larger of the TTL and this value, unless its client is gone | -| Cleanup sweep | every 5s | Expired sessions are removed and their input prompts cancelled | - -!!! note "Auth is never rushed" - A remote session that is still `authenticating` or waiting on `pending_input` can stay - idle for the larger of `session_ttl` and 600s. This gives you time to enter an interactive - code without the remote session vanishing mid-prompt. The client must stay: it keeps its - channel open, or it polls. - -The TTL and max-session limits are read from server config: - -```yaml title="unshackle.yaml (server)" -serve: - session_ttl: 300 # seconds a session may sit idle - max_sessions: 100 # cap on concurrent sessions -``` - ---- - -## Security properties worth knowing - -- **API key required.** Every remote session request carries `X-Secret-Key`. The - server rejects requests without a valid API key (health check aside). See - [Authentication](authentication.md). -- **IP binding.** A remote session records the creator's IP when the server makes it. - If a later request for the same remote session comes from a different IP, the server - returns `403 FORBIDDEN`. Remote sessions are not portable between hosts. -- **Namespaced, isolated cache.** Each remote session gets its own cache directory, - namespaced by a hash of the API key and the remote session ID, so remote sessions - cannot read each other's cached tokens. The server deletes the directory when the - remote session ends. A remote session that uses a server account (`serve.server_accounts`) - gets a persistent per-account cache instead, so the account's tokens outlive the - remote session. A service can name cache files that hold its device identity in - `Service.IDENTITY_CACHE`. A remote session on the server's device, or of an API key with its - own device config, writes those files to a directory of the API key, outside the remote - session's directory, so the server never sends them to the client and never takes them from - the client, and the next remote session of that - API key reads them again. The server and the client both refuse a forwarded cache file that is not - JSON or that names a type other than a date or time, and the service then authenticates again. -- **A tunnel belongs to its API key.** The server accepts `tunnel:` only from the API key - that opened the tunnel. Its SOCKS5 proxy listens on loopback only, and it needs a username and - password for that tunnel, so a raw `socks5h://127.0.0.1:` proxy from a client fails. -- **Only the client dials.** The server ignores a request from the client to open a - connection, so a tunnel never gives a client access to the server's network. -- **The server redacts secrets in logs.** It redacts remote session IDs, service tags, - and other user values before it writes them to the log. - ---- - -## Developer reference - -!!! info "This section is for developers" - The material below documents the server-side implementation and the HTTP - contract. End users configuring a client can stop at the sections above. - -### Remote session endpoints - -The server mounts all these routes, even in `--remote-only` mode. Paths use the -`session_id` that `create` returns. - -!!! note "Why `--remote-only` exists" - `--remote-only` narrows the server to only the health, services, search, and - remote session subset (and emits CORS headers), precisely so it is safe to sit behind - Cloudflare or serve cross-origin browser clients. That trimmed surface, rather - than the full `--api-only` mode, is what makes a CORS/Cloudflare-fronted - deployment practical: reach for it when the server is public-facing or accessed - from a browser origin, not when you want only the local HTTP API. +`unshackle serve` mounts these routes in every mode except `--cdm-only`, which keeps only +`/api/health`. `--remote-only` keeps only these routes (and the dashboard routes). Paths use the `session_id` of the create request. | Method | Path | Purpose | |---|---|---| -| `POST` | `/api/session/create` | Build + authenticate a service instance; returns a session ID immediately | -| `GET` | `/api/tunnel` | WebSocket that relays the connections of a `tunnel:` proxy to the client; `?id=` reconnects, close code 1000 frees the tunnel at once | -| `GET` | `/api/tunnel/check?id=` | Exit IP address and lookup time through the caller's tunnel, for `unshackle tunnel-test` | -| `GET` | `/api/session/{id}/titles` | Fetch and cache the title list | -| `POST` | `/api/session/{id}/tracks` | Resolve tracks, manifests, chapters, headers/cookies for a title | -| `POST` | `/api/session/{id}/segments` | Resolve per-segment/track download descriptors | -| `POST` | `/api/session/{id}/segment_filter` | Unwanted HLS segment URIs for one track (ads, bumpers) | -| `POST` | `/api/session/{id}/samples` | Decrypt the cbcs samples of a track the service decrypts itself | -| `POST` | `/api/session/{id}/license` | DRM licensing (proxy or server CDM) | -| `POST` | `/api/session/{id}/keys` | Store the content keys the client proved on a track | -| `POST` | `/api/session/{id}/keys/bad` | Report a server-vault content key that did not decrypt | -| `GET` | `/api/session/{id}/channel` | WebSocket of the [remote session channel](#the-remote-session-channel): the messages the server starts, and the client's answers; `?since=` is the last log `seq` the client has | -| `GET` | `/api/session/{id}/logs` | Drain the service's server-side log output (polling fallback) | -| `GET` | `/api/session/{id}/prompt` | Poll interactive auth status / pending prompt (polling fallback) | -| `POST` | `/api/session/{id}/prompt` | Submit an answer to a pending prompt (polling fallback) | -| `GET` | `/api/session/{id}` | Session info (validity, TTL, counts) | -| `DELETE` | `/api/session/{id}` | Close the remote session, return updated cache, clean up | +| `GET` | `/api/health` | Version, and the liveness check of a client that waits for a restarted server. See [endpoints](endpoints.md#get-apihealth). | +| `GET` | `/api/services` | The services, their options and `client_config` keys, and the regions of the server accounts. See [endpoints](endpoints.md#get-apiservices). | +| `POST` | `/api/search` | Search a service. See [endpoints](endpoints.md#post-apisearch). | +| `POST` | `/api/session/create` | [Create a remote session](#post-apisessioncreate) and start its login. | +| `GET` | `/api/tunnel` | [The WebSocket of a `--local-proxy` tunnel](#get-apitunnel). | +| `GET` | `/api/tunnel/check` | [The exit IP address through a tunnel](#get-apitunnelcheck). | +| `GET` | `/api/session/{session_id}/channel` | [The remote session channel](#get-apisessionsession_idchannel): the messages the server starts, and the client's answers. | +| `GET` | `/api/session/{session_id}/prompt` | [The login state and a waiting prompt](#get-apisessionsession_idprompt), the polling fallback of the remote session channel. | +| `POST` | `/api/session/{session_id}/prompt` | [Answer a prompt](#post-apisessionsession_idprompt), the polling fallback. | +| `GET` | `/api/session/{session_id}/logs` | [Service log records](#get-apisessionsession_idlogs), the polling fallback. | +| `GET` | `/api/session/{session_id}/titles` | [The titles](#get-apisessionsession_idtitles). | +| `POST` | `/api/session/{session_id}/tracks` | [The tracks, chapters and manifests of a title](#post-apisessionsession_idtracks). | +| `POST` | `/api/session/{session_id}/segments` | [The URL, DRM, headers and cookies of the selected tracks](#post-apisessionsession_idsegments). | +| `POST` | `/api/session/{session_id}/segment_filter` | [The HLS segments the service drops](#post-apisessionsession_idsegment_filter). | +| `POST` | `/api/session/{session_id}/samples` | [Decrypt the samples of a track the service decrypts itself](#post-apisessionsession_idsamples). | +| `POST` | `/api/session/{session_id}/license` | [A licence relay, a certificate, or the content keys of the server CDM](#post-apisessionsession_idlicense). | +| `POST` | `/api/session/{session_id}/keys` | [Store the content keys the client proved](#post-apisessionsession_idkeys). | +| `POST` | `/api/session/{session_id}/keys/bad` | [Report a server-vault content key that did not decrypt](#post-apisessionsession_idkeysbad). | +| `GET` | `/api/session/{session_id}` | [Remote session info](#get-apisessionsession_id). | +| `DELETE` | `/api/session/{session_id}` | [End the remote session](#delete-apisessionsession_id) and return the changed cache files. | -### Create: request and response +A client walks a remote session in this order: -`POST /api/session/create` requires `service` and `title_id`. It also accepts `session_id` (the ID of the remote session, -as the canonical text of a version 4 UUID; a create of the same API key and IP with the same ID replaces that remote -session when the new one is stored, and the server answers the ID of another API key or IP with `403 FORBIDDEN`), -`credentials`, `cookies` (base64 of zlib-compressed Netscape cookie file), `proxy`, -`no_proxy`, `profile`, `cache` (a map of `filename → base64(zlib(bytes))`), -`client_region`, `server_cdm` (`false` when the user picked the local CDM), `cdm_type`, `cdm_security_level`, `cdm_relay` (`true` when the client -answers CDM calls; a plugin `cdm_type` gets no relay), `cdm_system_id` and `cdm_device_type` (Widevine only), `service_config` -(the identity config keys the service lists in `client_config`, and the client's -[preferences](#your-preferences)), `plugins` (the version of each DRM plugin of the -client and the values of the plugin device attributes that the plugin names in `device_facts`; see -[endpoints](endpoints.md#post-apisessioncreate)), `client` (a freeform identity -object the dashboard shows as sent), and the track-selection hints `range_`, `vcodec`, -`quality`, `best_available`, `generate_dv`, plus arbitrary service CLI options -(`additionalProperties: true`). - -`dl_params` holds the `dl` track selection: `lang`, `v_lang`, `a_lang` and `s_lang` -(arrays of language strings), `acodec` (an array of audio codec names, such as -`EC3`), and `forced_subs` and `exact_lang` (booleans). The server gives these values to the -service in `ctx.parent.params`, never as service options, so a service option -with the same name, such as an own `--lang`, does not get them. The server uses -the `dl` default for each absent value: `lang` is `["orig"]`, -`v_lang`, `a_lang` and `acodec` are `[]`, and `forced_subs` and `exact_lang` are `false`. The -server refuses a malformed value and an unknown codec or range name with -`INVALID_PARAMETERS`. An empty array is a valid value and stays empty. - -The server does not forward the `dl` mode flags: `video_only`, `audio_only`, -`subs_only`, `chapters_only`, `list_`, `skip_dl`, `sub_format`, -`no_attachments`, `audio_description`, `audio_description_only` and -`forced_subs_only`. A service that reads one of them to skip work fetches more on -the server, but the result is the same. - -In a client-login session (not a server account), the server gives the service -the client's `profile` in `ctx.parent.params`, the same as a local run with that -profile. The profile name keys the service's token cache, so the cache files -the client sends and gets back belong to that profile. A service can also use -the name to select per-profile entries in the server's service config, such as -a per-profile ESN. - -The response returns **before** authentication finishes: - -```json -{ "session_id": "...uuid4...", "service": "EXAMPLE", "status": "authenticating", - "server_cdm": false, "server_cdm_max_height": null, "server_vault": true, "server_device": false } +```text +GET /api/tunnel → only with --local-proxy, before the create +POST /api/session/create → session_id, login state "authenticating", licensing mode +GET /api/session/{id}/channel → WebSocket: prompts, CDM calls, log records, login state, drain +GET /api/session/{id}/titles → after the login state is "authenticated" +POST /api/session/{id}/tracks → for the title that the user selects +POST /api/session/{id}/segments → for the selected tracks +POST /api/session/{id}/license → for each DRM track +POST /api/session/{id}/keys → the content keys that the client proved +DELETE /api/session/{id} → the end, with the changed cache files ``` -`server_vault` tells the client that the server vault serves a remote session its own device -licenses. `server_device` tells it that the service runs on the server's device, so every -content key comes from a vault. +## Conventions -Authentication runs on a background thread (`asyncio.to_thread(authenticate, ...)`). -The remote session starts in `AUTHENTICATING`. The client opens the remote session -channel and waits on it until the login state is `authenticated` (or `failed`). A client -without the channel polls the prompt endpoint for that state. +- **API key and owner.** Each request carries the API key in `X-Secret-Key` (see + [Authentication](authentication.md)). A request without a valid API key gets `401` from the + authentication middleware, in its own error shape. A remote session belongs to the API key and the IP address + that created it. A request from another API key or another IP address gets `403 FORBIDDEN`. A + remote session that does not exist, or that ended, gets `404 SESSION_NOT_FOUND`. +- **Errors.** A failure is the [standard error body](errors.md#the-standard-error-shape) with an + `error_code` from `APIErrorCode`. The server never answers with a `5xx` status. +- **Body size.** The create request and `POST /api/search` take a body of up to 8 MiB, the + `samples` route up to 16 MiB, and every other route up to 1 MiB. +- **A route that the server lacks.** A client counts an optional call (the segment filter, a bad + content key report, the log poll) as empty only when the server answers `404` with no + `error_code`. Any other error stops the call. -### Interactive auth: the `InputBridge` +### Slow responses -When the service calls its input function during `authenticate()` on the server -thread, an `InputBridge` pauses that thread and exposes the prompt to the HTTP -layer. +The `titles`, `tracks`, `segments` and `license` routes can take minutes on a large catalogue. +When the answer is not ready after 30 seconds, the route sends status `200` and the headers. It +then sends a newline every 30 seconds until the JSON body is ready. JSON parsers ignore the leading +newlines. This keeps the connection open through a reverse proxy that closes an idle request, and +the read timeout of the client starts again at each byte. -- `AuthStatus` values: `authenticating`, `pending_input`, `authenticated`, `failed`. -- `InputBridge.request_input(prompt, timeout=600, qr=None)` blocks the sync auth thread on a - `threading.Event` until `submit_response()` or `cancel()` fires. -- A timeout raises `TimeoutError`. The remote session becomes `FAILED` when that error ends the login. -- A prompt after authentication (in `get_titles()`, `get_tracks()` or licensing) goes to - the client on an open remote session channel. Without the channel it raises `RuntimeError` - at once: the client polls for prompts only during authentication, so no answer can come. -- A CDM call (`InputBridge.request_cdm`) works during and after authentication, because the - channel carries it, or the client polls while its own requests run. A call that no client fetches within 10 seconds - fails then, because no client is listening. A fetched call waits 60 seconds for its answer. - The call leaves the auth status as it was. An answer never marks the remote session as client-authenticated. -- `AUTH_INPUT_TIMEOUT = 600.0` seconds. An `AUTHENTICATING` remote session expires in the store after - the larger of `session_ttl` and this value, or when its client is gone. A remote session that waits on a prompt stays `AUTHENTICATING`. +A failure after the first 30 seconds arrives with status `200`: see +[Late failures with status `200`](errors.md#late-failures-with-status-200). -`GET /api/session/{id}/prompt` returns one of: +A slow response is not gzip-compressed. Gzip output cannot start before the body is ready, and +the newlines must go out at once. + +## Login states + +The login state (`AuthStatus`) tells where the login of a remote session stands: + +| Login state | Meaning | +|---|---| +| `authenticating` | The login runs on the server. The create request answers with this state. | +| `authenticated` | The login succeeded. The service routes answer. | +| `failed` | The login failed. `error` gives the reason, and each service route answers `AUTH_FAILED`. | + +`pending_input` is not a login state: the prompt route reports it while a prompt or a CDM call +waits for the client. The login state stays `authenticating` during that time. Each service route +(`titles`, `tracks`, `segments`, `segment_filter`, `samples`, `license`, `keys`, `keys/bad`) answers +`400 INVALID_INPUT` while the login state is `authenticating`, and `401 AUTH_FAILED` after a failed +login. + +A prompt waits up to 600 seconds for its answer. When the time ends, the login fails. A prompt after +the login (in the titles, tracks or licence step) goes to the client on an open remote session channel. +Without the channel it fails at once, because the client polls for prompts only during the login. + +A CDM call goes to the client in any login state. A call that no client takes within 10 seconds fails, +because no client listens. A call that a client took waits 60 seconds for its answer. An answer to a +CDM call does not change the login state. + +## Licensing modes + +The licensing mode (`LicensingMode`) says who licenses a remote session. The server fixes it at the +create request, for the whole remote session: + +| Licensing mode | `Licensor` | Who licenses | +|---|---|---| +| Server CDM | `server_cdm` | The server's device, live, up to the licence cap of the API key. The server vault answers first. | +| Client device | `client_device` | The client's own device, through the licence relay. The service sees a stand-in for that device. With `server_vault`, the server vault answers first. | +| Lent device | `lent_device` | Nobody licenses live: the service runs on the server's device, and the content keys come only from a vault. | +| No device | `no_device` | No server CDM, and no client device that the service can see: the create had no `cdm_type`, or no `cdm_relay: true`. A client with a CDM licenses through the licence relay. | + +The create response gives the mode in four fields, and the client reads them back: + +| Field | Server CDM | Client device | Lent device | No device | +|---|---|---|---|---| +| `server_cdm` | `true` | `false` | `false` | `false` | +| `server_device` | `false` | `false` | `true` | `false` | +| `server_vault` | `false` | the grant | the grant | `false` | +| `server_cdm_max_height` | the licence cap, or `null` | the licence cap, or `null` | the licence cap, or `null` | the licence cap, or `null` | + +The client reads the no-device mode, and a create response without `server_cdm` and +`server_device`, as the client-device mode. + +The server picks the server CDM when the API key has the `server_cdm` grant for the service, unless +the client sends `server_cdm: false` with a `cdm_type`, or `quality` asks for more than the licence +cap with a `cdm_type`. Above the licence cap without a `cdm_type`, the server refuses the create +with `403 SERVER_CDM_CAPPED`. A request that sets one of the service's `SERVER_DEVICE_OPTIONS` keeps the +server CDM. Without the server CDM, a create with `cdm_type` and `cdm_relay: true` (or with a +licence cap) gets the client-device mode, and any other create gets the no-device mode. A service +that calls `lend_server_device()` turns a client-device mode into the lent-device mode. + +The user's view of each mode is in [Who licenses the tracks](../../guide/remote-sessions.md#who-licenses-the-tracks). + +## Client presence + +Source: `unshackle/core/api/client_presence.py`. The server knows a client by its remote session channel, +its requests and its create request. Each state has a limit for the silence of the client. At the +limit, the server ends the remote session. + +| State | When | Limit | +|---|---|---| +| awaited | The client gave the remote session its ID in the create request, and has sent no request and opened no remote session channel since | 150s | +| polling | The client has had no remote session channel | The TTL rule only | +| present | The remote session channel is open | None | +| away | The remote session channel closed with any code except 1000, the connection broke, or the server closed the channel | 180s, or half of `session_ttl` when that is more | +| left | The client closed the remote session channel with code 1000 | 90s | + +- **Sign of life.** A request of the client for the remote session, or a new remote session channel, starts + the time again. The end of a request does not. A request after the state left makes the state away. +- **Work in progress.** A request that still works for the client does not keep the remote session + past the limit. +- **Login.** A client that is away or left does not get the 600s of a login. Its login ends with the + remote session. +- **TTL.** The limit never makes a remote session stay for longer than the TTL rule lets it. +- **The end request.** The client closes its remote session channel and then sends the `DELETE`, whose + answer has the login cache. Thus the close does not end the remote session at once. +- **A silent loss.** A client that the network cuts off sends no close. The server sends a ping after + 20s without data, and counts the client as away when no answer comes in 10s. + +## Remote session lifetime + +The server keeps remote sessions in memory. A restart loses them all. + +| Limit | Value | +|---|---| +| Idle time | `serve.session_ttl`. Each request and each new remote session channel starts it again. A remote session does not reach it while a request works on it or while its remote session channel is open. | +| Idle time during the login | The larger of `session_ttl` and 600 seconds, unless the client is gone. | +| Client presence | See [Client presence](#client-presence). | +| Remote sessions at the same time | `serve.max_sessions`. A create at the limit ends the least recently used remote session of the API key that holds the most. A remote session that a request works on goes last. | +| Sweep | Every 5 seconds the server ends each expired remote session. | + +[`serve`](../../reference/configuration/services.md#serve) in the configuration reference gives +the defaults of `session_ttl` and `max_sessions`. + +A delete, an expiry, an eviction and a server shutdown end a remote session the same way: the server +cancels each waiting prompt and CDM call, closes the remote session channel with code `4404` and deletes +the cache directory of the remote session. A request that waits for the remote session then answers +`SESSION_NOT_FOUND` and starts no service code. + +Before a restart the operator can start a drain. A create request then gets `409 SERVER_DRAINING`, +and the requests of open remote sessions continue. The server tells each client with the `drain` +message of the remote session channel and the `draining` field of the info route. + +--- + +## Route reference + +### `POST /api/session/create` + +Create a remote session for a service and title. The server builds the service, starts the login in +the background, and answers at once with the login state `authenticating`. The body is a +`SessionCreate` object: + +| Field | Description | +|---|---| +| `service` | Required. The service tag, in any case, or an alias. | +| `title_id` | Required. The title ID or URL, as for `dl`. | +| `session_id` | The ID that the client gives the remote session: the canonical text of a version 4 UUID. Without it, the server makes the ID. | +| `credentials` | `{username, password, extra?}` for the profile. | +| `cookies` | The Netscape cookie file of the profile, zlib-compressed and base64-encoded. | +| `cache` | The cache files of the service: a map of cache key to the zlib-compressed, base64-encoded file. See [Cache files](#cache-files). | +| `profile` | The credentials profile. At the top level it never means a service's own `--profile` option. | +| `proxy` | A full proxy URI, `tunnel:` for a `--local-proxy` tunnel, or, with `server_proxy`, a country code or `provider:country`. | +| `no_proxy` | `true` to accept the server's own connection. | +| `client_region` | The two-letter country code of the client. | +| `proxy_region` | The country code that the client resolved `proxy` from. For a server-account service, the server matches it against its own accounts. | +| `server_cdm` | `false` when the client declines the server CDM. | +| `cdm_type` | The DRM system of the client's CDM (`widevine`, `playready`), or the id of a DRM plugin. | +| `cdm_relay` | `true` when the client answers CDM calls. A plugin `cdm_type` gets no relay. | +| `cdm_security_level`, `cdm_system_id`, `cdm_device_type` | The device facts of the client's CDM. `cdm_system_id` and `cdm_device_type` are for Widevine only. | +| `service_config` | The identity config keys that the service lists in `client_config`, and the client's `preferences` block. At most 16384 bytes of JSON. | +| `plugins` | The DRM plugins of the client: id to `{version, device?}`. `device` holds the plain values of the device attributes that the plugin names in `device_facts`. At most 16384 bytes of JSON. | +| `range_`, `vcodec`, `quality`, `best_available`, `generate_dv` | The `dl` track selection, so that the service fetches the right manifests. | +| `dl_params` | The other `dl` values that a service reads (see below). | +| `service_params` | The service's own CLI options, by option name or flag spelling. | +| `client` | A free object that the dashboard shows as it is. The CLI sends `version`, `code_hash`, `platform` and a redacted `argv`. The server drops it above 4096 bytes of JSON. | + +`session_id` lets the client delete the remote session before the create answers. A second create +with the same ID from the same API key and IP address ends the first one if the first one has not +answered, and replaces its remote session when the new one is stored. A second create that fails +leaves that remote session open. A remote session with an ID from the client ends when the client +sends no request for it and opens no remote session channel within 150 seconds of the create. + +`dl_params` holds `lang`, `v_lang`, `a_lang` and `s_lang` (arrays of language strings), `acodec` (an +array of audio codec names or `dl -a` aliases such as `ddp`), and `forced_subs` and `exact_lang` +(booleans). The service reads them from `ctx.parent.params`, never as service options, so a service +option with the same name does not get them. The server uses the `dl` default for each absent value: +`lang` is `["orig"]`, `s_lang` is `["all"]`, `v_lang`, `a_lang` and `acodec` are `[]`, and `forced_subs` and `exact_lang` are +`false`. An empty array is a valid value and stays empty. The server does not get the `dl` mode flags +(`video_only`, `audio_only`, `subs_only`, `chapters_only`, `list_`, `skip_dl`, `sub_format`, +`no_attachments`, `audio_description`, `audio_description_only`, `forced_subs_only`). A service that +reads one of them to skip work fetches more on the server, but the result is the same. + +When the body has `service_params`, the server reads service options only from it, and a flat key +with the same name stays a `dl` value. Without `service_params`, the server reads service options +from the flat keys that are not fields of `SessionCreate`: the table above, plus `season`, +`episode`, `part` and `wanted`, which the create ignores. + +In a remote session that does not use a server account, the service gets the client's `profile` in +`ctx.parent.params`, as in a local run with that profile. The profile name keys the token cache of +the service, so the cache files that the client sends and gets back belong to that profile. + +**The proxy.** Without the `server_proxy` grant, `proxy` must be a full proxy URI with an `http`, +`https` or `socks` scheme on a public host that resolves. A Control D resolver, +`controld://@dns.controld.com`, counts as a full proxy URI: the server runs a forwarder for +it. Without `server_proxy`, the server does not resolve country codes with its own proxy providers, +and it refuses the create with `INVALID_PROXY` when no `proxy` is set and `client_region` differs from +the server's region. A request with no `client_region` is not blocked. With `server_proxy`, the +server resolves a country code and picks a proxy for `client_region` itself. The server accepts +`tunnel:` only from the API key that opened the tunnel. A server-account service refuses a client +proxy URI, because the server's login would go through it. + +=== "Response `200`" + + ```json + { + "session_id": "d4e5f6a7-...", + "service": "EXAMPLE", + "status": "authenticating", + "server_account": false, + "server_cdm": false, + "server_cdm_max_height": null, + "server_vault": true, + "server_device": false + } + ``` + +`server_account` is `true` when the server logs in with one of its own accounts +(`serve.server_accounts`). Otherwise the server uses only what the client sent, and never its own +credentials. The other four fields give the [licensing mode](#licensing-modes). + +When the login succeeds and the remote session uses no server account, the login belongs to the +client: the client gets cookies, auth headers and the cache files back. A remote session on the +server's device (lent-device mode) gives the client its cookies, but no auth headers and no cache +files. A server-account remote session sends no cookies and no auth headers, drops secret-looking +keys from track data, and keeps the cache on the server. + +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | Remote session created; the login runs. | +| `400` | `INVALID_INPUT` | No `service` or `title_id`, a `session_id` that is not the canonical text of a version 4 UUID, a bad `cache`, `plugins` or `preferences` value, or a `proxy_region` that is not a country code. | +| `400` | `INVALID_PARAMETERS` | A bad `range_`, `vcodec`, `quality`, `dl_params` or service option value. | +| `400` | `INVALID_PROXY` | A proxy that the API key may not use, or a region that differs from the server's. | +| `403` | `SERVER_CDM_CAPPED` | `quality` asks for more than the licence cap, and the create has no `cdm_type`. | +| `400` | `INVALID_SERVICE` | An unknown service, or one that the API key may not use. | +| `403` | `FORBIDDEN` | Another API key or another IP address has the `session_id`. | +| `404` | `SESSION_NOT_FOUND` | A `DELETE` or a newer create with the same `session_id` ended this create. | +| `409` | `SERVER_DRAINING` | The server drains before a restart. | + +### `GET /api/tunnel` + +A WebSocket that a `--local-proxy` client holds open before its create request. The server gives the +service a SOCKS5 proxy on loopback and sends each connection of that proxy to the client, which makes +it from its own connection and relays the bytes. Only the client dials: the server ignores a request +of the client to open a connection. TLS stays end to end between the server and the service. + +- The first message is `{"id": ""}`. The client then sends `proxy: "tunnel:"` in its + create request. +- Each later message is a binary frame: a 4-byte stream ID and a 1-byte kind (open, ok, data, close) + in network byte order, then the data. Source: `unshackle/core/tunnel.py`. +- `?id=` attaches the client to its tunnel again after a drop. After any close except + code 1000, the tunnel waits 60 seconds for a reconnect. Code 1000 means that the client has + finished, and frees the tunnel at once. +- An API key can have 4 tunnels open at once. On an API key with `shared: true`, the server counts + them for each `X-Client-Id` value, which the gateway sets. + +| Status | Error code | Meaning | +| --- | --- | --- | +| `101` | - | WebSocket open. | +| `404` | `NOT_FOUND` | No open tunnel with this `id` for this API key. | +| `429` | `RATE_LIMITED` | The API key has the maximum number of tunnels open. | + +### `GET /api/tunnel/check` + +Look up the exit IP address through the caller's tunnel `?id=`, so that the client can +check the route before a real run. `unshackle tunnel-test` calls it. + +=== "Response `200`" + + ```json + { "ip": "203.0.113.7", "country": "ca", "ms": 412 } + ``` + +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | The exit IP address, its country and the lookup time in ms. | +| `404` | `NOT_FOUND` | No open tunnel with this `id` for this API key. | +| `424` | `INVALID_PROXY` | No IP lookup got through the tunnel. | + +### `GET /api/session/{session_id}/channel` + +The remote session channel: a WebSocket that carries only the messages the server starts, and the client's +answers. Titles, tracks, licences, samples, the segment filter, content key reports, the create and +the delete stay HTTP requests. Pass `since=` to get only the log records after that sequence +number. + +Each message is a JSON text frame with a `type` field (`ChannelMessage`): + +| `type` | From | Fields | Meaning | +|---|---|---|---| +| `prompt` | server | `id`, `prompt`, `qr` | The service asks the user for input. `qr`, when present, is the text of a QR code to draw with it. | +| `cdm_call` | server | `id`, `call` | The service calls the client's CDM. `call` has the shape of [`cdm_call`](#cdm-calls). | +| `log` | server | `seq`, `level`, `message`, `ts`, `qr` | One record of the service log, as the logs route gives it. `qr`, when present, is the text of a QR code to draw under the message. | +| `status` | server | `status`, `error` | The login state, on attach and at each change. | +| `drain` | server | `draining` | The operator started or stopped a drain before a restart. | +| `answer` | client | `id`, `response`, `error` | The answer to the `prompt` or `cdm_call` with this `id`. The answer to a CDM call is its JSON object as a string. `error` says why the client cannot answer a prompt, and the service stops at once. | + +When the client attaches, the server first sends the log records after `since`, the drain state, the +prompts and CDM calls that the client did not answer, and the login state. A log record can arrive +twice after a reconnect: the client skips a `seq` it already has. Each prompt and CDM call goes to one +path only: the remote session channel, or the prompt route. + +The server closes the remote session channel with code `4404` when the remote session ends. The client then +stops reconnecting, and its next request finds the remote session gone. The server sends a ping after +20 seconds without data. + +The client uses the polling fallback (the prompt and logs routes, and a keep-alive request to the info +route at a third of `expires_in`) in these cases: + +- A gateway in front of the server refuses the WebSocket upgrade, or the connection fails, at the + create. The client then polls for the life of the process. +- The remote session channel drops. The client polls until it reconnects, with a backoff from 1 to 30 + seconds. + +| Status | Error code | Meaning | +| --- | --- | --- | +| `101` | - | WebSocket open. | +| `403` | `FORBIDDEN` | The remote session belongs to another API key or IP address. | +| `404` | `SESSION_NOT_FOUND` | No such remote session. | + +### `GET /api/session/{session_id}/prompt` + +The polling fallback of the remote session channel: the login state, and the prompt or CDM call that waits +for the client (`PromptReply`). A client without the remote session channel polls it every 2 seconds during +the login, and every 0.5 seconds while one of its requests runs service code, so that it takes each +CDM call within the 10 seconds of the pickup. ```json -{ "status": "authenticated" } { "status": "authenticating" } { "status": "pending_input", "prompt": "Enter code: " } { "status": "pending_input", "prompt": "Scan the code, then press Enter", "qr": "https://login.example/scan" } { "status": "pending_input", "prompt": "...", "cdm_call": { "op": "challenge", "drm": "widevine", "init_data": "...", "license_type": "OFFLINE", "privacy_mode": true, "service_certificate": "..." } } -{ "status": "failed", "error": "...message..." } +{ "status": "authenticated" } +{ "status": "failed", "error": "Invalid credentials" } ``` -A `cdm_call` comes first, in any auth state. The client answers it with a JSON object in -`response`: `{"session": "...", "challenge": ""}` for `challenge`, -`{"keys": [{"kid", "type", "key", "permissions"}]}` for `keys`, `{}` for `close`, or -`{"error": "..."}` when its CDM refuses. An older client refuses `close`, and the server -ignores that refusal. An answered call stops being pending at once, so a client that polls again -straight away does not see it twice. +#### CDM calls -A missing remote session returns `404 SESSION_NOT_FOUND`. An IP mismatch returns -`403 FORBIDDEN`. `POST /api/session/{id}/prompt` takes `{ "response": "..." }` and -returns `{ "status": "accepted" }`. A post with no pending prompt is an -`INVALID_INPUT` error. +A `cdm_call` comes first, in any login state. Its `op` is `challenge`, `keys` (parse a licence and return its keys) or `close`. The +client answers it with a JSON object in `response`: `{"session": "...", "challenge": ""}` for +`challenge`, `{"keys": [{"kid", "type", "key", "permissions"}]}` for `keys`, `{}` for `close`, or +`{"error": "..."}` when its CDM refuses. A `keys` answer holds only the Widevine `OPERATOR_SESSION` and +`SIGNING` keys, never a content key, and the client refuses a PlayReady `keys` call. An answered call +stops waiting at once, so a client that polls again at once does not get it two times. -### The remote session channel +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | The login state, and the waiting prompt or CDM call. | +| `403` | `FORBIDDEN` | The remote session belongs to another API key or IP address. | +| `404` | `SESSION_NOT_FOUND` | No such remote session. | -`GET /api/session/{id}/channel` is a WebSocket that carries only the messages the server -starts. Titles, tracks, licences, samples, the segment filter, bad content key reports, create -and delete stay HTTP requests. The route takes the same API key and ownership checks as the -other remote session routes. +### `POST /api/session/{session_id}/prompt` -Each message is a JSON text frame with a `type` field: +Answer the waiting prompt or CDM call. Body: `{ "response": "..." }` (`PromptAnswer`). -| `type` | From | Fields | Meaning | -|---|---|---|---| -| `prompt` | server | `id`, `prompt`, `qr` | The service asks the user for input; `qr`, when present, is the text of a QR code to draw with it | -| `cdm_call` | server | `id`, `call` | The service calls the client's CDM; `call` has the shape of the prompt route's `cdm_call` | -| `log` | server | `seq`, `level`, `message`, `ts`, `qr` | One record of the service log, with the same redaction as `GET /logs`; `qr`, when present, is the text of a QR code to draw under the message | -| `status` | server | `status`, `error` | The login state, as the `status` of `GET /prompt` | -| `drain` | server | `draining` | The operator started or stopped a drain before a restart | -| `answer` | client | `id`, `response`, `error` | The answer to the `prompt` or `cdm_call` with this `id`; `error` says why the client cannot answer a prompt, and the service stops at once | +=== "Response `200`" -When the client connects, the server first sends the log records after `since`, the drain -state, the prompts and CDM calls that the client did not answer, and the login state. A log -record can arrive twice, after a reconnect; the client skips a `seq` it already has. Each -prompt and CDM call goes to one path only: the channel, or the prompt routes. + ```json + { "status": "accepted" } + ``` -The server closes the channel with code `4404` when the remote session ends: a delete, an -expiry, an eviction, or a server shutdown. The client then stops reconnecting, and its next -request finds the remote session gone. +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | Answer accepted. | +| `400` | `INVALID_INPUT` | No `response`, or no prompt waits. | +| `404` | `SESSION_NOT_FOUND` | No such remote session. | -The client polls the prompt and logs routes, and sends keep-alive requests, in these cases: +### `GET /api/session/{session_id}/logs` -- A gateway in front of the server refuses the WebSocket upgrade, or the connection fails, when - the client creates the remote session. The client polls for the life of the process and logs - the refusal at debug level only. -- The channel drops. The client polls until it reconnects, with a backoff from 1 to 30 seconds. +The polling fallback of the remote session channel: the records of the service's own log (`LogsReply`). +Pass `since=` to get only the records after the last sequence number. The route answers in each +login state, `failed` too. -### `SessionStore` internals +=== "Response `200`" -Source: `unshackle/core/api/session_store.py`. A singleton you get from -`get_session_store()`. + ```json + { + "session_id": "d4e5f6a7-...", + "logs": [ + { "seq": 1, "level": "INFO", "message": "Signed in as profile 'Main'", "ts": 1724990000.1 }, + { "seq": 2, "level": "WARNING", "message": " - The service returned no streams", "ts": 1724990002.7 } + ], + "last_seq": 2 + } + ``` -- **Config-driven limits.** `serve.session_ttl` (default `300`) and - `serve.max_sessions` (default `100`) are read as properties, so config changes - take effect without recreating the store. -- **`creating()`** holds the ID of a remote session while its `create` handler works, and refuses an ID that another API - key or IP has. **`end_pending()`** ends such a create for a `DELETE`, and then `create()` stores nothing. -- **`create()`** evicts the least-recently-accessed remote session of the API key that holds the most when at capacity, - then stores a complete `SessionEntry` from the fields of the `create` handler and publishes the `create` event. -- **Expiry.** `get()` and `cleanup_expired()` use one rule. A remote session expires when its client is gone - ([Client presence](#client-presence)), also while a request holds it. A remote session that no request holds - also expires when it is idle for longer than `ttl`. While its login runs (`AUTHENTICATING`), the limit is - the larger of `ttl` and `AUTH_INPUT_TIMEOUT`. -- **`get()`** refreshes `last_accessed` and `idle_since` through `touch()`. It returns `None` and - deletes the entry when the remote session has expired. -- **`cleanup_expired()`** runs every 5s and removes each expired remote session. -- **Removal.** Eviction, expiry and `delete()` end the remote session the same way: they cancel its - `InputBridge`, close its channel, send the `delete` dashboard event, schedule a staged service reload - and delete its cache directory (pruning empty parent dirs up to, but not including, the cache root). A request - that waits for the remote session then answers `SESSION_NOT_FOUND` and starts no service code. So does a request - whose service code waits on the client for a prompt or a CDM call, whatever that code does next. A service thread - that runs can still write to the cache directory, so a task deletes the directory again after the last request. -- **`track_login(task)`** keeps each login task of `session/create`, and each task that deletes a cache directory - again, until it ends. -- **Shutdown.** First, `close_channels()` cancels each `InputBridge` and closes each channel, so no request waits - for a client while the server waits for its requests. Then the server calls **`close()`**. It ends each open - remote session and deletes the cache directory of each one. It sends no dashboard event - and schedules no reload. It then waits up to 5 seconds for each tracked task that still runs, and stops the sweep. - Within that time, a login that ends deletes its cache directory again. -- **Relay.** A server that relays to a `remote_services` server runs **`end_remote_pool()`** after `close_channels()`. - It starts the end of each remote login that waits, and of all idle pooled remote sessions at the same time. A list - call whose login it ends, or whose login comes later, gets `SERVER_DRAINING`. A request in flight finishes first. Every - 5 seconds until it has stopped, the server ends each request that opens its lost remote session again. Then - **`close_remote_pool()`** ends the rest and waits up to 5 seconds for each `DELETE` request. The exit of the process - waits for an end that still runs. -- **Signals.** The first `SIGTERM` starts the shutdown, and the server ignores each later one. A second Ctrl+C forces - the end. On Windows only Ctrl+C starts the shutdown. +The buffer keeps the newest 500 records. Only the logger of the service is copied: the core loggers +stay on the server, and the HTTP requests that the server makes for the service never reach the +client. A server-account remote session sends no log records, because the output of its login can +carry the identity of the operator's account. -`SessionEntry` fields: +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | Records, oldest first (an empty list when nothing is new). | +| `404` | `SESSION_NOT_FOUND` | No such remote session. | + +### `GET /api/session/{session_id}/titles` + +The titles of an authenticated remote session (`TitlesReply`), each in the wire form. A slow answer +arrives as a [slow response](#slow-responses). + +=== "Response `200`" + + ```json + { + "session_id": "d4e5f6a7-...", + "titles": [ { "type": "episode", "name": "Pilot", "id": "ep-1" } ] + } + ``` + +`collection` is present only when the service returned a music collection. It holds the facts of the +collection itself: `kind`, `title`, `artist`, `year`, `total_tracks`, `total_discs`, `artwork_url`, +`total_duration`, `owner` and `description`, for example +`"collection": { "kind": "playlist", "title": "Example Playlist", "total_tracks": 93 }`. A fact that +the collection does not have is absent. The client ignores a field of `collection` that it does not +know, and stops with an error on a value of the wrong type. + +The server applies no `title_map`: the client renames the titles. + +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | Titles returned. | +| `400` | `INVALID_INPUT` | The login state is still `authenticating`. | +| `401` | `AUTH_FAILED` | The login failed. | +| `404` | `SESSION_NOT_FOUND` | No such remote session. | + +### `POST /api/session/{session_id}/tracks` + +The tracks and chapters of one title. Body: `{ "title_id": "..." }` (`TracksRequest`). Unlike +`list-tracks`, each track object here **includes** its download URL. A track that resolves its URL on +use has `resolve_url` set to `true` and no URL. A slow answer arrives as a +[slow response](#slow-responses). + +The response repeats the title. A service can rewrite title fields in `get_tracks`, so the client +takes this copy in place of the one from the title list. Each track carries the full local field set. + +`manifests` holds each served DASH or ISM manifest one time. One URL can have more than one entry, +for example when a service merges a second manifest under the same URL. `track_ids` names the tracks +that each entry restores, and the client matches such a track only in the manifest of that entry. For +DASH, `filtered_period_ids` names the filtered periods, which the download skips. +`track_manifests` holds a one-track fragment for each track that the manifest cannot identify, such +as an AdaptationSet that the service built itself. The client parses that fragment in place of the +whole manifest. The fragment starts at the period of the track and keeps the content periods after it. + +`hls_playlists` holds the media playlist text of each HLS track that the service holds as text, with +the URL of the track. A `file:` URL is never sent: such an entry has `url` set to `null`. The client +keeps an entry only when it parses as a media playlist whose segment URIs are absolute `http` or +`https` URLs, for the same URL as its track. Otherwise it logs `Refusing track : its HLS playlist ...` +and drops the track. + +After the manifest parse, the client lays the JSON-safe part of the `track.data` that the service set +over the parser's values, so a value of the service wins. An attachment that the service wrote to a +file on the server travels as base64, and the client writes it to its own temp directory. + +=== "Response `200`" + + ```json + { + "title": { "type": "episode", "name": "Pilot", "id": "ep-1" }, + "video": [ { "id": "v-1", "url": "https://...", "drm": [ ... ] } ], + "audio": [ { "id": "a-1", "url": "https://..." } ], + "subtitles": [ { "id": "s-1", "url": "https://..." } ], + "chapters": [ { "timestamp": "00:00:00.000", "name": "Intro" } ], + "attachments": [ { "url": "https://...", "name": "font.ttf", "mime_type": "font/ttf", "description": "" } ], + "manifests": [ { "type": "dash", "url": "https://...", "data": "", "track_ids": [ "v-1", "a-1" ], "filtered_period_ids": [ "ad-1" ] } ], + "track_manifests": [ { "track_id": "s-1", "type": "dash", "url": "https://...", "data": "" } ], + "hls_playlists": [ { "track_id": "v-1", "url": "https://...", "data": "" } ], + "session_headers": { "User-Agent": "..." }, + "session_cookies": { "sid": "..." }, + "session_cookie_jar": [ { "name": "sid", "value": "...", "domain": ".example.com", "path": "/", "secure": true } ], + "server_cdm": false, + "server_cdm_type": "widevine", + "sample_decrypt_tracks": [], + "fairplay_bridge": false + } + ``` + +The remote session fields (`TracksReply`): | Field | Description | |---|---| -| `session_id` | UUID4 string: the one of the create request, else one that the server makes | -| `service_tag` | Normalized service tag | -| `service_instance` | The authenticated service object kept alive between calls | -| `titles` / `title_map` | Result of `get_titles()` and a `title_id → Title` map | -| `tracks` / `tracks_by_title` / `chapters_by_title` | Cached resolved tracks and chapters | -| `creator_ip` | IP recorded at create time for IP-binding checks | -| `cache_tag` | Per-session cache directory tag | -| `input_bridge` | `InputBridge` for interactive auth, if any | -| `auth_status` / `auth_error` | Current `AuthStatus`, read from `input_bridge` (`AUTHENTICATED` without one), and last error message | -| `presence` | `ClientPresence`: the state of the client and its last sign of life | -| `created_at` / `last_accessed` | Timestamps; `last_accessed` drives LRU eviction | -| `idle_since` | Monotonic time of the last access; it drives the TTL, so a step of the system clock expires no remote session | +| `session_headers` | The HTTP headers of the service session, which the client merges into its own. A server login sends no secret-looking header. | +| `session_cookie_jar` | The cookies of the service session, each with its domain, path and `secure` flag, so that each cookie goes only to its own hosts. | +| `session_cookies` | The same cookies as names and values only. | +| `server_cdm` | `true` in a server-CDM remote session. | +| `server_cdm_type` | The DRM system that a server-CDM licence takes first for the tracks of this title. | +| `sample_decrypt_tracks` | The IDs of the tracks that the service decrypts itself, through the `samples` route. | +| `fairplay_bridge` | `true` when the service licenses FairPlay-only tracks through a bridge on the server. | -### Client presence +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | Tracks returned. | +| `400` | `INVALID_INPUT` | No `title_id`, a `title_id` that is not in the title list, or the login is not complete. | +| `404` | `SESSION_NOT_FOUND` | No such remote session. | +| `422` | `DRM_ERROR` | A track of the title needs a DRM plugin that the client did not list in `plugins`, or the client sent no `plugins`. | -Source: `unshackle/core/api/client_presence.py`. The server knows a client by its channel, its requests and its -`create`. Each state has a limit for the silence of the client. At the limit, the server ends the remote session. +### `POST /api/session/{session_id}/segments` -| State | When | Limit | -|---|---|---| -| awaited | The client gave the remote session its ID in `create`, and has sent no request and opened no channel since | 150s | -| polling | The client has had no channel | The TTL rule only | -| present | The channel is open | None | -| away | The channel closed with any code except 1000, the connection broke, or the server closed the channel | 180s, or half of `session_ttl` when that is more | -| left | The client closed the channel with code 1000 | 90s | +The download URL, DRM, headers, cookies and track data of the selected tracks. Body: +`{ "track_ids": ["v-1", "a-1"] }` (`SegmentsRequest`). A track that the tracks response sent with +`resolve_url` gets its URL from the service here. The server makes one service call at a time for each +remote session, so parallel requests wait for each other. A slow answer arrives as a +[slow response](#slow-responses). -- **Sign of life.** A request of the client for the remote session, or a new channel, starts the time again. The end - of a request does not. A request after the state left makes the state away. -- **Work in progress.** A request that still works for the client does not keep the remote session past the limit. -- **Login.** A client that is away or left does not get the 600s of a login. Its login ends with the remote session. -- **TTL.** The limit never makes a remote session stay for longer than the TTL rule lets it. -- **The `DELETE`.** The client closes its channel and then sends the `DELETE`, whose answer has the login cache. - Thus the close does not end the remote session at once. -- **A silent loss.** A client that the network cuts off sends no close. The server sends a ping after 20s without - data, and counts the client as away when no answer comes in 10s. +=== "Response `200`" -### Per-session cache namespacing + ```json + { + "tracks": { + "v-1": { "descriptor": "DASH", "url": "https://...", "drm": [ ... ], "headers": { ... }, "cookies": { ... }, "cookie_jar": [ ... ], "data": { ... } } + } + } + ``` -The `create` handler builds a `Cacher` namespaced as: +`data` has the form of the track `data` in `list-tracks`: the JSON-safe part of the `track.data` that +the service set, without the `hls`, `dash` and `ism` parser keys. `cookies` gives names and values +only. `cookie_jar` gives the same cookies with their domain, path and `secure` flag, in the form of +`session_cookie_jar`. -```text -_sessions/// -``` +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | Track details returned. | +| `400` | `INVALID_INPUT` | No `track_ids`, or a value that is not an array of strings. | +| `404` | `TRACK_NOT_FOUND` | An unknown track ID. | -The server makes a new UUID for each `create`, so a `create` that takes over a session ID never shares a directory -with the one before it. +### `POST /api/session/{session_id}/segment_filter` -The handler writes forwarded `cache` files into that directory before authentication. -On `DELETE`, when the login belongs to the client (`client_auth`) and the remote -session does not run on the server's device, the handler harvests updated cache files from the whole directory tree (compressing each -with zlib and base64-encoding, **excluding** `titles_*` files) and returns them -under a `cache` field, so the client can keep refreshed tokens. A remote session on the -server's device keeps the files of the service's `IDENTITY_CACHE` in -`_identity//` instead, so they are never in that tree. Each cache key -is the file path relative to that directory, with `/` separators and no `.json` -suffix, which is the `Cacher` cache key the service reads it with: +The HLS segments that a service drops (ads, bumpers, dub cards). The server runs the service's own +segment filter over the media playlist of the track and returns only the URIs, so the client drops +the same segments as the service. Body: `{ "track_id": "v-1" }` (`SegmentFilterRequest`). +`unwanted` is `null` when the track has no filter (`SegmentFilterReply`). When the server answers with +an error, the client stops the track download. Only a `404` with no `error_code`, from a server +that lacks the route, makes the client keep every segment. + +=== "Response `200`" + + ```json + { "unwanted": ["https://cdn.example/hls/ad1.ts"] } + ``` + +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | Unwanted segment URIs, or `null`. | +| `400` | `INVALID_INPUT` | No `track_id`. | +| `404` | `TRACK_NOT_FOUND` | An unknown track ID. | +| `422` | `SERVICE_ERROR` | The playlist request or the filter failed. | + +### `POST /api/session/{session_id}/samples` + +Decrypt the samples of a track that the service decrypts itself after the download. The tracks +response lists those track IDs in `sample_decrypt_tracks`. The client downloads the file, then sends +the samples of each `stsd` sample entry here, and writes the plaintexts back in place. This is the one +route that carries media bytes. The query string names the track and the 1-based entry: +`?track_id=a-1&entry=2`. + +- An empty body asks how the entry decrypts. The JSON response is `{ "key": "" }`, which the + client then uses itself, or `{ "decrypter": true }`. +- An `application/octet-stream` body is a sample frame: a big-endian `uint32` count, one `uint32` + length for each sample, then the samples. Each sample is a ciphertext cut to whole AES blocks. The + response is a frame of the same shape with the plaintexts in the same order. + +The client sends at most 8 MiB of samples in one request, and the route accepts a body of up to +16 MiB. The server does not compress the frames. The route needs the `server_cdm` grant for the +service, whatever the licensing mode, because the decrypter can use a process or an account of the +server. + +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | The content key, `decrypter`, or the plaintext frame. | +| `400` | `INVALID_INPUT` | No `track_id`, a bad `entry`, a malformed frame, or a track that the service does not decrypt. | +| `403` | `FORBIDDEN` | The API key has no `server_cdm` grant for the service. | +| `404` | `TRACK_NOT_FOUND` | An unknown track ID. | +| `413` | - | The body is larger than 16 MiB. | +| `422` | `SERVICE_ERROR` | The decrypter of the service failed. | + +### `POST /api/session/{session_id}/license` + +A licence relay, a service certificate, or the content keys of the server CDM (`LicenseRequest` and +`LicenseReply`). `mode` selects one of two modes. A slow answer arrives as a +[slow response](#slow-responses). + +**Relay mode** (`mode: "proxy"`, the default) sends the client's CDM `challenge` to the licence +endpoint of the service and returns the raw licence bytes. A Widevine licence or certificate that the +service returns as Base64 text arrives decoded, as raw bytes in Base64. `is_certificate: true` asks +for the service certificate in place of a licence. + +=== "Request" + + ```json + { "track_id": "v-1", "challenge": "", "drm_type": "widevine" } + ``` + +=== "Response `200`" + + ```json + { "license": "" } + ``` + +**Server-CDM mode** (`mode: "server_cdm"`) licenses on the server with the device of the API key and +returns the content keys. Use `track_id` for one track or `track_ids` for a batch. The server vault +answers first. In a client-device or lent-device remote session with `server_vault`, this mode +answers only from the server vault. + +=== "Single: Response `200`" + + ```json + { "keys": { "": "" }, "vault_keys": [""], "drm_type": "widevine" } + ``` + +=== "Batch: Response `200`" + + ```json + { "keys": { "v-1": { "": "" } }, "vault_keys": [""], "drm_type": "widevine" } + ``` + +| Field | Description | +| --- | --- | +| `track_id` / `track_ids` | One track, or a batch of tracks. | +| `challenge` | The base64 CDM challenge (relay mode). | +| `pssh` | A base64 PSSH. Server-CDM mode licenses this PSSH, but only when its KIDs are KIDs of the track. Relay mode gives it to the licence callback of the service as `pssh` (Widevine) or `pssh_b64` (PlayReady), the PSSH of the header that the challenge is for. A relay-mode PSSH that names a KID that the track does not carry goes to no callback. | +| `kid` | The KID that the client found for the track, for the server vault lookup of a single track. | +| `drm_type` | `widevine` (default), `playready`, or the id of a DRM plugin that both peers load. In server-CDM mode the server's `cdm` mapping for the service decides the DRM system, and the response `drm_type` names the system that licensed. A mapping with a device for each system takes the system of the device that the remote session loaded. With no mapping, the client's value decides when the track carries that system; else a system that the track carries decides, PlayReady first. A track whose DRM is a whole-file cipher takes `clearkeyctr` with no `pssh`: the service on the server licenses it. A track of a DRM plugin that licenses locally takes the plugin id with no `pssh` and `mode` `server_cdm`: the server answers in `keys` with the content key from a server vault or from a licence of its own plugin device, only in a server-CDM remote session, and only under the licence cap. | +| `mode` | `proxy` (default) or `server_cdm`. | +| `is_certificate` | `true` for a service certificate request (relay mode). | +| `keys` (response) | KID to content key for `track_id`, or track ID to that map for `track_ids`. | +| `vault_keys` (response) | The KIDs whose content key came from a server vault, not the CDM. The client proves such a content key with a decode before it trusts it. Absent when each content key came from the CDM. | +| `capped_tracks` (response) | For a batch: the tracks above the licence cap, each with `reason` and `max_height`. They get no content keys, and the client licenses them with its own device. | +| `clear_tracks` (response) | The requested track IDs that carry no DRM, so they have no keys. Absent when each requested track is encrypted. | +| `file_keys` (response) | The content keys of whole-file ciphers, by track ID. Absent when no requested track holds such a cipher. | +| `bridge_kids` (response) | For a batch: the KIDs of the init segments of each FairPlay-only track that the server licensed through the FairPlay bridge, by track ID. The client needs the content key of each of these KIDs, or the download of that track stops. | +| `drm_type` / `drm_types` (response) | The DRM system that licensed, for the request or for each track. The client takes it for its next call. | + +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | Licence or content keys returned. | +| `400` | `INVALID_INPUT` | No `track_id`, no challenge or PSSH, a PSSH that is not a valid PSSH box, or no CDM device for the API key. | +| `400` | `INVALID_PARAMETERS` | An unsupported `drm_type`. | +| `403` | `FORBIDDEN` | Server-CDM mode in a remote session that the server CDM does not license and that cannot read the server vault, or a PSSH with a KID that the track does not carry. | +| `403` | `SERVER_CDM_CAPPED` | A single track that the server does not license live. `details.reason` is `server_cdm_max_height` (above the licence cap, with `max_height`), `client_device` (a client-device remote session), or `server_device` (a lent-device remote session, for a track that no vault holds). | +| `404` | `TRACK_NOT_FOUND` | An unknown track ID. | +| `404` | `NO_CONTENT` | The server CDM returned no content keys. | +| `422` | `SERVICE_ERROR` | The service failed during licensing. | +| `422` | `DRM_ERROR` | The server could not license the track. | + +### `POST /api/session/{session_id}/keys` + +Store the content keys that the client proved on a track and that the server did not serve to this +remote session (`TrackKeys`). The server stores a content key only for a KID that a track of the +remote session names and that no local server vault holds a content key for. It never stores a pair +flagged bad, and it never removes a flag. The server answers when its local vaults hold the pairs, +and sends them to its other vaults after the answer. The client sends each content key of a licence when the +licence returns, and each vault key after its decode check passes. A licence key of a FairPlay-only +track that the client licensed through the bridge goes only after its decode check passes, so a client +without FFmpeg does not send it. ```json -{ - "status": "ok", - "cache": { - "tokens": "...base64(zlib(bytes))...", - "session_web/": "...base64(zlib(bytes))..." - } -} +{ "track_id": "", "keys": { "": "" } } ``` -Both sides reject a cache key with a drive letter, a root, a `..` segment, an empty -segment, or more than 8 segments before it becomes a path, so a peer cannot write -outside the cache directory. Both sides also refuse a `cache` map with more than -256 entries, and the server refuses the request body of a remote session creation or of a search when it is larger than 8 MiB. The server also refuses a `cache` map whose files inflate to more than 16 MiB in total, with `400 INVALID_INPUT`. It checks every entry before it writes a file, and it removes the cache directory of a remote session creation that fails. The client gives a warning when it has more than 256 cache files or more than 16 MiB to send. It also stops saving the cache files that a server returns at 16 MiB. The server skips a cache key it cannot write, such as one that names an -existing file as a directory, and logs a warning. +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | `{}`, whatever the server stored. | +| `404` | `SESSION_NOT_FOUND` | No such remote session. | -### Remote session info response +### `POST /api/session/{session_id}/keys/bad` -`GET /api/session/{id}`: +Report a content key from `vault_keys` that did not decrypt the track (`BadKeyReport`). The server +flags the pair in each local vault that it holds and reports it to the vault that served it, and the +next licence for that KID reaches the CDM. When the CDM returns the same pair, the server removes the +flag, because then the check of the client was wrong. A server with no local SQLite vault cannot store +the flag. The server accepts a report only for a pair that it served to that remote session. The +client never learns the server vault names. ```json -{ - "session_id": "...", - "service": "EXAMPLE", - "valid": true, - "expires_in": 300, - "draining": false, - "track_count": 12, - "title_count": 40 -} +{ "kid": "", "key": "" } ``` -`draining` is `true` after the operator starts a drain before a restart. The client checks -it before each title, so it knows of the restart before it occurs. With an open remote session -channel the client reads the `drain` message and sends no request. +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | `{"flagged": true}`: the pair is flagged. `{"flagged": false}`: the CDM licensed the pair, so it is not flagged. | +| `400` | `INVALID_INPUT` | This remote session was not served that pair. | +| `404` | `SESSION_NOT_FOUND` | No such remote session. | -!!! warning "`expires_in` is the configured TTL, not time remaining" - The `expires_in` value reports the store's configured `session_ttl`, not the - seconds left before this specific remote session expires. +### `GET /api/session/{session_id}` -### Reference client: `RemoteService` +Remote session info (`SessionInfo`). The client also uses it as the keep-alive of the polling +fallback. -Source: `unshackle/core/remote_service.py`. This is the canonical consumer of the -remote session API and a good template for any client. The routes, the `AuthStatus` values, -the error codes and the request and reply shapes that it shares with the server are in -`unshackle/core/remote_protocol.py`. +=== "Response `200`" -- **`RemoteClient.request`** sets `X-Secret-Key` and `User-Agent: unshackle/`, - uses the server's `timeout` from `remote_services` (default 120s) as the read timeout, - and treats any `status_code >= 400` as fatal: it logs `Server error []: ` - and raises `SystemExit(1)`. A `200` body with `"status": "error"` is also fatal (see - the heartbeat below). -- **Heartbeat.** The `titles`, `tracks` and `license` routes send a newline every 30s while - the service works. The read timeout starts again at each byte, so a slow request stays - open for as long as the server works on it, and a reverse proxy does not close it as - idle. A route that answers within 30s sends the usual response. After 30s the status - is already `200`, so a failure after that time arrives as the usual error body with - status `200`. Your client must check `status` in the body. JSON parsers ignore the - leading newlines. The server does not gzip-compress a heartbeat response, because gzip - output cannot start before the body is ready. -- **Retries.** The download-side HTTP session mounts an adapter with - `Retry(total=5, backoff_factor=0.2, status_forcelist=[429, 500, 502, 503, 504])`. -- **Flow.** `authenticate()` → `create` (+ open the remote session channel, or poll `prompt` - every 2s without it, up to a 600s deadline, answering `pending_input` prompts. With stdin closed the client logs an - error and raises `SystemExit(1)` instead of posting an empty answer) → `get_titles()` → `get_tracks()` - (merging returned `session_headers`/`session_cookie_jar`, re-parsing `manifests`) → - get the licence in proxy mode or `server_cdm` mode → `close()` (`DELETE`, saving any returned - `cache`). -- **ID.** The client gives the remote session its ID: a version 4 UUID in the `session_id` of `create`. It uses - the ID of the reply, so a server that ignores the field also works. -- **Server restarts.** The server keeps remote sessions in memory only, so a restart - loses them all. The client recovers in two ways: - - A drain announced through `draining`: the client finishes the current title, then - deletes its remote session, so the drain can end and the refreshed cache comes back. - It waits until `/api/health` reports the restarted server without `draining`, - opens a new remote session, and continues with the next title. - - A lost remote session (`SESSION_NOT_FOUND`, a connection error, an answer cut off - after its headers, a timeout, a closed tunnel or a gateway error page): the client waits - for `/api/health`, then checks the old remote session. A live remote session takes the - call again only after a connection error, because a timed-out call can already have run. - A cut-off answer counts as a connection error, so the server can run that call twice. A lost one is replaced: the - client deletes the old one when the server did not answer `SESSION_NOT_FOUND` for the call, and - saves the cache that comes back. It then opens a new remote session, sends `titles` and the current title's `tracks` - again, and then sends the failed call again. A title or track that the new remote session - gives another ID keeps its old ID on the client, and the client sends the new ID. The client matches a title by season and episode number, and a track by its - attributes. + ```json + { + "session_id": "d4e5f6a7-...", + "service": "EXAMPLE", + "valid": true, + "expires_in": 300, + "draining": false, + "track_count": 4, + "title_count": 10 + } + ``` - The client waits up to 30 minutes for the server, which covers a deploy's drain. A Ctrl+C - ends this wait. The client stops with an error if the new remote session licenses differently from the old one, - for example after a change to the API key's `server_cdm` grant. An interactive login - asks for its input again. -- **Server resolution.** `resolve_server()` reads `config.remote_services.` - into `{url, api_key, services, server_cdm}`. It puts the `server_cdm` flag into a - copy of the services map as `_server_cdm`, and never changes the loaded config. -- **Optional routes.** A call to a route that an older server can lack (the segment filter, - bad content key reports, the log poll) counts as empty only when the server answers 404 - with no `error_code`. Any other error stops the call: a segment filter that fails on the - server stops the track download, and the client never keeps every segment in its place. +`expires_in` is the configured `session_ttl`, not the seconds that remain for this remote session. +`draining` is `true` after the operator starts a drain before a restart. The client checks it before +each title. -### When the client ends a remote session +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | Info returned. | +| `404` | `SESSION_NOT_FOUND` | No such remote session, or it expired. | -Source: `unshackle/core/remote_lifetime.py`. One owner holds the remote session, its tunnel and its channel -from before the first request until the server answers the `DELETE`. It closes the channel, sends the `DELETE`, -saves the returned cache and then stops the tunnel. It does so: +### `DELETE /api/session/{session_id}` -- when `dl` has finished every title, before the run post-scripts -- when the process exits: `--list`, an error, or Ctrl+C in any step, also before `create` answers -- when a signal or a closed console stops the process, or the cancel of a download job stops its worker -- when the login or any other step of the opening fails, or `create` times out or its answer is cut off -- when a serve that relays for a REST client closes its pooled remote session -- when such a serve stops: each remote login that waits, and all idle pooled remote sessions at the same time +End a remote session (`SessionClosed`). The server cancels the waiting prompts and CDM calls, collects +the changed cache files, and deletes the remote session and its cache directory. A create of the same +API key and IP address that still runs under this ID ends too: it makes no remote session and answers +`404 SESSION_NOT_FOUND`. When the `DELETE` ends such a create, it answers `200` with no `cache`. -The `DELETE` has a connect and read timeout of 15s each. The client sends it again only once, when a gateway answers with -an error page or asks for the API key in the other header. It does not wait for a rate limit. +=== "Response `200`" -A Ctrl+C during the downloads cancels the run. The client waits for the download threads and for the content keys that -still go to the vaults, and then ends the remote session. The cancel ends each wait of a download thread within 0.5s: -the wait for a server that restarts, for a rate limit and for a login. A cancelled thread opens no new remote session, -and the client deletes a remote session that a thread opens at that moment. The cancel does not stop a request that the -server already has: the client waits for its answer. A failed track is no cancel, so the next title can open -a new remote session. + ```json + { + "status": "ok", + "cache": { "tokens": "", "session_web/": "" } + } + ``` -While the client ends a remote session, it ignores the first Ctrl+C, so it does not lose the returned cache. The next -Ctrl+C stops the wait at once, and the process then waits for no other end. The count of Ctrl+C is one for the process. -When the run itself called the end, after the last title, that Ctrl+C also stops the run. On Windows, a Ctrl+C -counts when the network read that blocks returns, so the 15s timeout limits the wait. After the end, no thread of the -client opens a remote session again. +`cache` is present only when the remote session made cache files and the login belongs to the client +in a remote session that does not run on the server's device. It holds every file of the cache +directory of the remote session except the `titles_*` files. See [Cache files](#cache-files). -`SIGHUP` (a closed terminal) and `SIGTERM` stop `dl`, `search` and `tunnel-test` as Ctrl+C does, with an exit code other -than 0. Three things are different: - -- The `DELETE` goes first: before the wait for the download threads, for a CDM call and for the channel. -- The process ends 8s after the first signal at the latest, also when the server does not answer. -- A later signal changes nothing, and Ctrl+C keeps its own count. - -After `SIGHUP` the process writes nothing more to a terminal. A redirected output gets each line. `nohup` keeps its effect. -Source: `unshackle/core/process_exit.py`. - -On Windows, a closed console window and Ctrl+Break send the `DELETE` and then end the process, without the rest of the -Ctrl+C steps. The system gives a closed window about 5s. A kill (`SIGKILL`, a Windows task end, the cancel of a download -job on Windows) sends no `DELETE`, so only the server ends the remote session, at its own limits. - -A cancelled job that uses a remote server sends the `DELETE` for at most 4s, then its worker ends. - -The `DELETE` can arrive while the server still works on `create`. The server then answers `200` with no cache, and -the `create` makes no remote session, starts no login and answers `404 SESSION_NOT_FOUND`. +| Status | Error code | Meaning | +| --- | --- | --- | +| `200` | - | Remote session ended. | +| `404` | `SESSION_NOT_FOUND` | No such remote session. | --- -## Troubleshooting +## Cache files -!!! example "\"Could not connect to remote server at ...\"" - The client could not reach the URL. Make sure that `unshackle serve` operates on - the server, the `url`/port in `remote_services` are correct (default port `8786`), - and any firewall or reverse proxy allows the connection. +A cache key is the file path relative to the service cache directory, with `/` separators and no +`.json` suffix: the `Cacher` cache key that the service reads it with. A file in a subdirectory, such as +`session_web/`, keeps its place. The value is the file, zlib-compressed and base64-encoded. -!!! example "`403 FORBIDDEN` mid-download" - The request came from a different IP than the one that made the remote session. - Remote sessions are IP-bound. Do not move between networks (or NAT egress IPs) during a - remote download. +- Both sides refuse a cache key with a drive letter, a root, a `..` segment, an empty segment, or more + than 8 segments, before it becomes a path. +- Both sides refuse a `cache` map with more than 256 entries. The server refuses a map whose files + inflate to more than 16 MiB in total with `400 INVALID_INPUT`, before it writes a file. The client + gives a warning when it has more to send, and stops saving the returned files at 16 MiB. +- Both sides refuse a cache file that is not JSON, or that names a type other than a date or time. The + service then logs in again. +- The server skips a cache key that it cannot write, such as one that names an existing file as a + directory, and logs a warning. -!!! example "Auth times out or the prompt never resolves" - Interactive auth allows up to 600s. If you miss that window, the server marks the - remote session `failed` and cleans it up. Operate the download again. If the server - never prompts you, make sure that the credentials and cookies the client forwarded - are valid for the service. +Each remote session gets its own cache directory, named by a hash of the API key and a new UUID, so a +remote session cannot read the cache of another. A create that takes over a `session_id` never shares +the directory of the one before it. A remote session that uses a server account gets a lasting cache +for each account instead. A service can name the cache files that hold its device identity in +`Service.IDENTITY_CACHE`. A remote session on the server's device, or of an API key with its own device +config, keeps those files in a directory of the API key, so the server never sends them to a client +and never takes them from one. -!!! example "\"Multiple remote services configured. Use --server ...\"" - You have more than one entry under `remote_services`. Pass `--server ` - to pick one. +## Security properties + +The API key and owner check is in [Conventions](#conventions), the tunnel rules are in +[`GET /api/tunnel`](#get-apitunnel), and the secrets that stay on the server are in the +[create response](#post-apisessioncreate). In addition: + +- **A tunnel proxy needs its own credentials.** The SOCKS5 proxy of a tunnel listens on loopback + only, and needs a username and password for that tunnel, so a raw `socks5h://127.0.0.1:` + proxy from a client fails. +- **One log line for each record.** The server strips control characters from each user value + before it logs it, so a client cannot forge a log record. diff --git a/docs/guide/remote-sessions.md b/docs/guide/remote-sessions.md new file mode 100644 index 00000000..68d58726 --- /dev/null +++ b/docs/guide/remote-sessions.md @@ -0,0 +1,371 @@ +# Remote sessions + +A remote session runs a service on a remote unshackle server and the download on your machine. +The server logs in to the service, lists the titles, gets the tracks and their manifests, and can +license the tracks. Your machine selects the tracks, downloads and decrypts them, and muxes the +result. + +!!! note "When to use a remote session" + - The server has service accounts, cookies or a CDM that you do not want to copy to each machine. + - You want to download on a fast machine and keep the logins and the licensing in one place. + - A service is available only in the region of the server. + +The server is an `unshackle serve` instance. The routes, fields and message shapes between your +machine and the server are on the [remote session protocol](../dev/rest-api/remote-sessions.md) +page. The server settings are under [`serve`](../reference/configuration/services.md#serve). + +## Configure the client + +On your machine (the client), add a `remote_services` block to `unshackle.yaml`. Each entry names +a server and gives its URL and API key: + +```yaml title="unshackle.yaml (client)" +remote_services: + my_server: + url: "https://my-box.example:8786" + api_key: "your-api-key" + server_cdm: true # optional: the server CDM licenses the tracks + services: + EXAMPLE: + server_cdm: false # optional: your own CDM licenses EXAMPLE + title_map: + "0ABCDEF": "The Show (Renamed Locally)" +``` + +[`remote_services`](../reference/configuration/services.md#remote_services) in the configuration +reference gives each setting of a server entry. + +### Select a server + +When you configure one server, unshackle uses it: + +```bash +unshackle dl --remote EXAMPLE 0ABCDEF +``` + +When you configure more than one server, select one with `--server`: + +```bash +unshackle dl --remote --server my_server EXAMPLE 0ABCDEF +``` + +With no `remote_services` block, unshackle stops with an error that tells you to add one. + +### Make a service remote by default { #making-a-service-remote-by-default } + +To run a service on the server without `--remote`, set `remote` in the +[`services`](../reference/configuration/services.md#services) block, not in the `services` +sub-dict of `remote_services`. Add `server` to select one of several servers: + +```yaml title="unshackle.yaml (client)" +services: + EXAMPLE: + dl: + remote: true + server: my_server +``` + +`unshackle dl EXAMPLE 0ABCDEF` and `unshackle search EXAMPLE "query"` then run on `my_server`. +`--local` runs the local service code for one run. The +[`services`](../reference/configuration/services.md#services) reference gives the other rules. + +--- + +## What happens during a download + +The command looks like an ordinary download. The client takes the remote session through these +steps. + +=== "1. Log in" + + The client creates the remote session and sends what it can, so that the server does not + have to prompt: + + - The local **credentials** and **cookies** of the service and profile. + - The local **cache files** of the service (for example refreshed tokens), including the files + in subdirectories of the service cache directory, but only the files of the active profile. + The client withholds a file whose path, in any directory or file name, embeds a hash of another + credential or the name of another profile. Thus the tokens of one profile never reach the + server while you use a different profile. At worst, a withheld file makes the server log in + again. + - A resolved **proxy**, or, if you set none, your detected **region**. Without the + [`server_proxy`](../reference/configuration/services.md#serve) grant on your API key, the + proxy must be a full proxy URI on a public host, and the server rejects the remote session when + it is in a different region from yours: pass `--proxy` with your own proxy, or `--no-proxy` + to accept the server's own connection. For Control D, see + [Control D](proxies-and-vpn.md#control-d). The client also downloads playlists and segments + through the same proxy, as a local run does. `--no-proxy-download` and `--proxy-download` + change that for downloads only. + - With `--local-proxy`, the client opens a tunnel first, and the server sends the service + requests through your machine's own connection. See + [Send the server's requests through your machine](proxies-and-vpn.md#send-the-servers-requests-through-your-machine). + - Your track selection (`-r`, `-v`, `-q`, `--best-available`, `--generate-dv`) and your language and + audio codec selection (`-l`, `-vl`, `-al`, `-a`, `-fs`), so that the server fetches the right + manifests. Some services fetch one manifest for each audio language. + + The server uses its own accounts only when the operator lists the service in + `serve.server_accounts` and gives your API key `server_accounts`. For any other service, a + client that sends no credentials or cookies logs in with nothing. For a listed service the client + sends no credentials, cookies or cache: the server picks one of its own accounts that works in + your region, and rotates through them. `--proxy ca` picks a `ca` account. + + The service listing of the server gives the regions that those accounts cover. When your region is + not one of them and you set no `--proxy`, the client resolves a proxy for the first of those + regions itself, so both sides are in a region that the account works in. This is a bare region + query, so it skips Control D. A server-account service does not accept a Control D resolver from + the client. + +=== "2. Prompts" + + Some services need a one-time code, a PIN or a device confirmation. When the login on the server + asks for input, the server sends the prompt to the client. The client shows it to you, and sends + your answer back. + + ```text + Enter the 6-digit code sent to your email: 483920 + ``` + + The server also sends each record of the service's own log to the client, which prints it, so you + see the reason when a step fails on the server. + +=== "3. Titles and tracks" + + The client gets the title list, then the tracks of the title that you select. The server sends + the manifests, and the client parses them again to download the segments itself. The client + uses the HTTP headers and cookies that the server used. Each cookie keeps its domain, path and + `secure` flag, so it goes only to its own hosts. + +=== "4. Licensing" + + For a DRM-protected title, the [licensing mode](#who-licenses-the-tracks) of the remote session + decides who licenses each track. + +=== "5. Download and end" + + The client downloads, decrypts and muxes locally. While it works, the remote session stays open, + so a long download does not let it expire. When the run ends, also early (`--list`, Ctrl+C, an + error), the client ends the remote session (see + [When the client ends a remote session](#when-the-client-ends-a-remote-session)). + + When the login belongs to the client, the server returns the changed cache files (for example + a refreshed token), and the client saves them, so the **next** remote session can skip the + interactive login. The login belongs to the client when it succeeds and the remote session uses + no server account. This includes a pair code that you approve on another device. A server-account + login never belongs to the client, and neither does a remote session on the server's device (see + below). The client saves only the returned files that pass the same profile check as before it + sent them, so a file for another profile cannot overwrite that profile's local file. + +!!! tip "Rename remote titles locally" + To rename titles of a remote service that you do not have installed locally, add a `title_map` + under that service in `remote_services..services`. The server sends the titles exactly as + the service returns them, and applies no `title_map` of its own. The client applies your map, + so the output name stays under your control. + +--- + +## Who licenses the tracks + +When the server creates the remote session, it fixes the licensing mode: who licenses the tracks +for the whole remote session. There are four licensing modes: + +| Licensing mode | Who licenses | When | +|---|---|---| +| Server CDM | The server's device, up to the licence cap of your API key. The client needs no CDM. | Your API key has the `server_cdm` grant for the service, and your client did not decline it. | +| Client device | Your local CDM, through a licence relay on the server. With the [`server_vault`](../reference/configuration/services.md#serve) grant (or `server_cdm`), the server vault answers first, and a track that no server vault holds goes back to your device. | Your client declined the server CDM, the API key has no server CDM for the service, or `-q` asks for more than the licence cap. | +| Lent device | Nobody licenses live. The content keys come from the server vault (with the grant) or from your own vaults. | A service option runs the remote session on the server's device. | +| No device | Nobody licenses: only your own key vaults can give the content keys. The service on the server sees no device. | No server CDM, and your client has no local CDM. | + +### The server CDM + +The server checks its key vaults, loads the device for your API key, licenses, and returns the +content keys. When the server's `cdm` entry for the service has a `widevine` and a `playready` +device, the server loads the device of your local CDM's DRM system. See +[`cdm`](../reference/configuration/drm.md). + +- Set `server_cdm: true` in the server entry to ask for it. +- A content key from a server vault is unproven. The client decrypts with it and checks that the + output decodes, and reports a wrong pair to the server. The server flags the pair, and the next + licence for that KID reaches the CDM. The client never learns the server vault names. +- A content key in your own vaults goes first, also when the server already answered. The client + proves it, and a server key waits as the next candidate. +- When the server licence fails, or the server gives a track no content key, your own device + licenses the track only when the `cdm` entry for the service gives the loaded device (see + [`remote_services`](../reference/configuration/services.md#remote_services)). Otherwise, or when + that device also fails, the run stops at the licence step of that track with one `DRM_ERROR` line. + +!!! note "The licence cap" + An API key with `server_cdm_max_height` gets the server CDM only up to that height. Above it, + the client reads its own key vaults first, then licenses the track with its own local CDM. When + the track has no DRM of that CDM's system, the client uses the device that its own `cdm` entry + names for the DRM system of the track. With no such device, the download of that track stops. See + [`server_cdm_max_height`](../reference/configuration/services.md#serve). + +### Your own device + +Your local CDM makes the licence challenge. The server sends it to the service, and returns the +licence for your CDM to parse. + +- Your client declines the server CDM in the cases that + [`remote_services`](../reference/configuration/services.md#remote_services) gives + (`server_cdm: false`, `dl --cdm`, a `cdm` entry for the service). The server then builds the service on your + device, also when the API key has the server CDM. +- A service option that the service lists in `SERVER_DEVICE_OPTIONS` keeps the server CDM, and the + service gets the server's device whatever device you have. The client shows a warning when the + server did not apply its choice. +- The service on the server sees your device, not the server's. See + [Your own device identity](#your-own-device-identity). + +### The lent device + +A service can offer an option that builds the remote session on the server's own device and +identity, for the quality that device reaches. The remote session then makes no live licence: each +content key comes from the server vault or your own vaults, and a content key that no vault holds +stops the download with an error that names its KID, when the client knows it. The service uses the +server's own config: your identity values do not apply, but your preferences do (see +[Your preferences](#your-preferences)). The client reads the server vault only when the API key has +the `server_vault` grant (or `server_cdm`). The login tokens of such a remote session hold the +server's device identity, so the server keeps them and returns no cache files. + +!!! note "A DRM type that the client does not know" + The client rebuilds the DRM of each track from the track list of the server. When the server + sends a DRM type that the client does not know, the client stops the title with one `DRM_ERROR` + line that names the type. Update the client to the version of the server. + +### Your own device identity + +A service can need more than a licence challenge from your device: an ESN, model keys, or a +session-key exchange that runs on the CDM. The device never leaves your machine. Only these cross +to the server: + +- **Device facts.** The client sends its DRM system, security level, system ID and device type. The + service sees a stand-in with these facts. +- **CDM calls.** When the service calls the CDM, the server sends the call to the client and waits. + The client makes the challenge, or parses the licence, on its own CDM. When the service closes a + CDM session, the server tells the client, because a CDM holds only a few sessions. +- **Session keys only.** The client returns only the Widevine `OPERATOR_SESSION` and `SIGNING` keys. + It never returns a content key, and it refuses a PlayReady keys call. Thus a server cannot use your + device to license titles for itself. +- **Identity config.** A service lists the config keys that a client may send (for example a device + serial, device keys, or a map of serials). The client sends only those keys, from its own `services: :` block in + `unshackle.yaml`. When the client sends an identity, the server drops its own value for each of + those keys, so the two identities never mix. A mapping merges the client's + entries over the server's. A client entry replaces a server entry with the same key, also when the + server's key is a number. The server keeps these values in the memory of the remote session only. + +### Your preferences + +The `preferences` block of a service is the place for user choices, such as a metadata language or +a subtitle format. It is not an identity, so it crosses `--remote` in every licensing mode, whatever +CDM the client has, and no service declares anything for it: + +- The client sends each entry of its own `services: : preferences:` block in `unshackle.yaml` + that is a string, a number or a boolean. It leaves out other entries and logs one debug line for + each. +- The server merges the entries key by key over its own `preferences` block for that service. An + entry that the client sends replaces the server's value, and a config key that the client does not + send keeps the server's value. The entries never count as an identity, and they stay when the + service builds the remote session on the server's device. +- The server refuses a `preferences` value that is not an object of strings, numbers and booleans + with `INVALID_INPUT`. + +A service reads its preferences from `self.config["preferences"]`, locally and over `--remote` +alike. Keep a value that changes the server's account (a profile, an account type) out of +`preferences` unless every client of the server may choose it: a server account is shared, and the +service can store the choice in its cache. + +--- + +## When the server restarts + +The server keeps remote sessions in memory only, so a restart loses them all. The client recovers +in two ways: + +- **A drain.** The operator can announce a restart. The client then finishes the current title, + ends its remote session so that the refreshed cache comes back, waits until the server is back, + opens a new remote session and continues with the next title. +- **A lost remote session.** After a connection error, an answer cut off after its headers, a timeout, + a closed tunnel or a gateway error page, the client waits for the server and checks the old remote + session. A live remote session takes the call again only after a connection error, because a call + that timed out can already have run. A cut-off answer counts as a connection error, so the server + can run that call twice. The client replaces a lost remote session: it opens a new one, gets the + titles and the tracks of the current title again, and sends the failed call again. It matches a + title by season and episode number, and a track by its attributes, so a new ID on the server + changes nothing for the run. + +The client waits up to 30 minutes for the server, which covers the drain of a deploy. A Ctrl+C ends +this wait. The client stops with an error when the new remote session licenses differently from the +old one, for example after a change to the `server_cdm` grant of the API key. An interactive login +asks for its input again. + +## When the client ends a remote session + +The client ends the remote session, closes its tunnel, and saves the returned cache: + +- when `dl` has finished every title, before the run post-scripts +- when the process exits: `--list`, an error, or Ctrl+C in any step, also before the server answers + the create request +- when a signal or a closed console stops the process, or the cancel of a download job stops its + worker +- when the login or any other step of the opening fails, or the create request times out or its + answer is cut off +- when a server that relays for a REST client closes its pooled remote session, or stops + +The end request has a connect and read timeout of 15s each. The client sends it again only once, +when a gateway answers with an error page or asks for the API key in the other header. It does not +wait for a rate limit. + +A Ctrl+C during the downloads cancels the run. The client waits for the download threads and for +the content keys that still go to the vaults, and then ends the remote session. The cancel ends each +wait of a download thread within 0.5s: the wait for a server that restarts, for a rate limit and +for a login. A cancelled thread opens no new remote session. The cancel does not stop a request +that the server already has: the client waits for its answer. A failed track is not a cancel, so +the next title can open a new remote session. + +While the client ends a remote session, it ignores the first Ctrl+C, so it does not lose the +returned cache. The next Ctrl+C stops the wait at once. On Windows, a Ctrl+C counts when the network +read that blocks returns, so the 15s timeout limits the wait. + +`SIGHUP` (a closed terminal) and `SIGTERM` stop `dl`, `search` and `tunnel-test` as Ctrl+C does, +with an exit code other than 0. Three things are different: + +- The end request goes first: before the wait for the download threads, for a CDM call and for the + remote session channel. +- The process ends 8s after the first signal at the latest, also when the server does not answer. +- A later signal changes nothing, and Ctrl+C keeps its own count. + +After `SIGHUP` the process writes nothing more to a terminal. A redirected output gets each line. +`nohup` keeps its effect. + +On Windows, a closed console window and Ctrl+Break send the end request and then end the process, +without the rest of the Ctrl+C steps. The system gives a closed window about 5s. A kill +(`SIGKILL`, a Windows task end, the cancel of a download job on Windows) sends no end request, so +only the server ends the remote session, at its own limits (see +[Remote session lifetime](../dev/rest-api/remote-sessions.md#remote-session-lifetime)). A cancelled +job that uses a remote server sends the end request for at most 4s, then its worker ends. + +--- + +## Troubleshooting + +!!! example "\"Could not connect to remote server at ...\"" + The client could not reach the URL. Make sure that `unshackle serve` runs on the server, that + the `url` and port in `remote_services` are correct (default port `8786`), and that each firewall + or reverse proxy allows the connection. + +!!! example "`Remote server rejected the API key (HTTP 401)`" + The server does not know the `api_key` of the `remote_services` entry. Ask the operator for a + valid API key, or set `auth_headers` when a gateway in front of the server reads another header. + +!!! example "`403 FORBIDDEN` during a download" + The request came from a different IP address than the one that created the remote session. + Remote sessions are bound to that address. Do not move between networks (or NAT egress + addresses) during a remote download. + +!!! example "The login times out or the prompt never resolves" + An interactive login has a time limit (see + [Login states](../dev/rest-api/remote-sessions.md#login-states)). After that time the login + fails and the server ends the remote session. Start the download again. If the server never prompts you, make + sure that the credentials and cookies that the client sent are valid for the service. + +!!! example "\"Multiple remote services configured, pick one with --server: ...\"" + You have more than one entry under `remote_services`. Pass `--server ` to select one. diff --git a/docs/reference/configuration/services.md b/docs/reference/configuration/services.md index 750e4e6c..c720b25e 100644 --- a/docs/reference/configuration/services.md +++ b/docs/reference/configuration/services.md @@ -21,7 +21,7 @@ Per-service configuration, keyed by the service tag in any case (for example `EX several servers. On the command line, `--local` and `--server` override these keys. A REST API job ignores both keys. A REST API job takes the other keys that it accepts as download parameters as its defaults, above the `serve` defaults and below the values that the request sends. - See [making a service remote by default](../../dev/rest-api/remote-sessions.md#making-a-service-remote-by-default). + See [making a service remote by default](../../guide/remote-sessions.md#making-a-service-remote-by-default). A service can also read settings of its own, such as a preferred metadata language. The service's own `config.yaml` and its README, when it has one, name them. To change one, copy its config key into this @@ -31,10 +31,10 @@ other values in the same section stay. Over `--remote`, the server builds the service from its own config. The client sends only the config keys that the service lists for a client identity, see -[your own device identity](../../dev/rest-api/remote-sessions.md#your-own-device-identity), +[your own device identity](../../guide/remote-sessions.md#your-own-device-identity), and the strings, numbers and booleans of its `preferences` block. Each preference that you set replaces the server's value for that config key, in every licensing mode, see -[your preferences](../../dev/rest-api/remote-sessions.md#your-preferences). +[your preferences](../../guide/remote-sessions.md#your-preferences). For every other setting, the value in the server's config applies. User- or device-specific values (API keys, account IDs, device attributes) belong in this block @@ -171,7 +171,7 @@ unshackle cannot fetch the list. Each synthetic command carries the server-side documentation, so `unshackle dl --remote -h` shows the same help text as it does on the server. Service names resolve against the server's tags and aliases, not your local services. If the server does not offer a name to your API key, unshackle rejects the name and lists the -tags it does offer. See [remote sessions](../../dev/rest-api/remote-sessions.md) for the +tags it does offer. See [remote sessions](../../guide/remote-sessions.md) for the full setup. ## `serve` @@ -187,10 +187,10 @@ is the [REST API](../../dev/rest-api/index.md) section. These are the config key | `users` | dict | `{}` | Per-user API keys and their allowlists (see below). | | `tiers` | dict | `{}` | Named settings that `users` entries reference by name (see below). | | `services` | list | *(unset)* | Global service allowlist. Omit to allow all. | -| `remote_only` | bool | `false` | Expose only the remote service session endpoints (health, services, search, session) and disable the rest of the REST API. | +| `remote_only` | bool | `false` | Expose only the [remote session routes](../../dev/rest-api/remote-sessions.md#routes) and disable the rest of the REST API. | | `dashboard` | dict | *(unset)* | Developer dashboard: `key` is the API key for the read-only `/api/dashboard/` endpoints (status, remote sessions, remote session logs, jobs, keys, services, health, logs, SSE events). Unset leaves those routes unregistered, and a reload that removes the key makes them answer `404`. See [dashboard endpoints](../../dev/rest-api/dashboard.md). | -| `session_ttl` | int (s) | `300` | Seconds a remote session can stay idle before it expires. A remote client sends keep-alive requests to its remote session during a download, so the remote session does not expire during a long download. A remote session that still logs in can stay idle for the larger of this value and 600 seconds. A client that closes or loses its channel and does not come back loses its remote session sooner: see [Client presence](../../dev/rest-api/remote-sessions.md#client-presence). | -| `max_sessions` | int or null | `100` | Maximum concurrent remote sessions; at the cap the server evicts the oldest remote session of the API key that holds the most. Set it to `null` or `0` for no limit, which is also what `/api/dashboard/status` then reports, so a dashboard can tell "no cap" from a cap that happens to sit at the default. | +| `session_ttl` | int (s) | `300` | Seconds a remote session can stay idle before it expires. An open session channel, or a request that works on the remote session, keeps it from expiring, so it does not expire during a long download. A remote session that still logs in can stay idle for the larger of this value and 600 seconds. A client that closes or loses its channel and does not come back loses its remote session sooner: see [Client presence](../../dev/rest-api/remote-sessions.md#client-presence). | +| `max_sessions` | int or null | `100` | Maximum concurrent remote sessions; at the cap the server evicts the least recently used remote session of the API key that holds the most, and a remote session that a request works on goes last. Set it to `null` or `0` for no limit, which is also what `/api/dashboard/status` then reports, so a dashboard can tell "no cap" from a cap that happens to sit at the default. | | `history_limit` | int | `100` | How many finished jobs to retain in history. | | `compression_level` | int | `1` | gzip level for responses. | | `services_refresh_interval` | int (s) | `0` | How often the server pulls the git-backed service repositories in `directories.services` and hot-reloads the services that changed. `0` turns it off. A service with a running or queued job, or a live remote session, is staged and swaps to the new code as soon as its last job and session finish. | diff --git a/mkdocs.yml b/mkdocs.yml index 47d2ac69..9ac9d252 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -126,6 +126,7 @@ nav: - Key Vaults: guide/vaults.md - Output & Naming: guide/output-and-naming.md - Subtitles: guide/subtitles.md + - Remote Sessions: guide/remote-sessions.md - Troubleshooting: guide/troubleshooting.md - Configuration: - Overview: reference/configuration/index.md @@ -149,7 +150,7 @@ nav: - Endpoints: dev/rest-api/endpoints.md - Job Lifecycle: dev/rest-api/job-lifecycle.md - Dashboard: dev/rest-api/dashboard.md - - Remote Sessions: dev/rest-api/remote-sessions.md + - Remote Session Protocol: dev/rest-api/remote-sessions.md - Error Responses: dev/rest-api/errors.md - API Reference: - Service: reference/api/service.md diff --git a/tests/remote/unit/test_remote_protocol.py b/tests/remote/unit/test_remote_protocol.py index a44d606a..11b1c441 100644 --- a/tests/remote/unit/test_remote_protocol.py +++ b/tests/remote/unit/test_remote_protocol.py @@ -4,6 +4,7 @@ from __future__ import annotations import ast import functools +import re from pathlib import Path from typing import Any @@ -26,6 +27,7 @@ CLIENT_METHODS = { "ws_connect": "GET", } SERVED = {(method, path): handler for method, path, handler, _ in routes.ROUTES} +ROOT = Path(__file__).parents[3] @functools.cache @@ -103,6 +105,22 @@ def test_the_server_takes_its_remote_session_routes_from_the_protocol(): assert {path for path in served_paths if path.startswith("/api/session")} <= protocol_paths +def test_the_protocol_page_lists_each_remote_route(): + """The route table of the protocol page holds the routes that a remote-only server mounts, and no other. + + Each route of the table that the page itself documents has a section of its own. + """ + page = (ROOT / "docs" / "dev" / "rest-api" / "remote-sessions.md").read_text(encoding="utf-8") + listed = set(re.findall(r"^\| `(GET|POST|DELETE)` \| `([^`]+)` \|", page, re.MULTILINE)) + sections = set(re.findall(r"^### `(GET|POST|DELETE) ([^`]+)`$", page, re.MULTILINE)) + assert listed == {(method, path) for method, path, _, remote in routes.ROUTES if remote} + assert sections == listed - { + ("GET", protocol.HEALTH_ROUTE), + ("GET", protocol.SERVICES_ROUTE), + ("POST", protocol.SEARCH_ROUTE), + } + + def test_the_wire_values_stay_what_older_peers_send(): """Both halves read one record, so only this list catches a renamed value that an older peer still sends.""" assert {name: getattr(protocol, name) for name in ROUTE_NAMES} == {