Files
unshackle/docs/dev/rest-api/remote-sessions.md
T

49 KiB

Remote session protocol

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.

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 in the user guide.

Routes

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
GET /api/health Version, and the liveness check of a client that waits for a restarted server. See endpoints.
GET /api/services The services, their options and client_config keys, and the regions of the server accounts. See endpoints.
POST /api/search Search a service. See endpoints.
POST /api/session/create Create a remote session and start its login.
GET /api/tunnel The WebSocket of a --local-proxy tunnel.
GET /api/tunnel/check The exit IP address through a tunnel.
GET /api/session/{session_id}/channel The remote session channel: the messages the server starts, and the client's answers.
GET /api/session/{session_id}/prompt The login state and a waiting prompt, the polling fallback of the remote session channel.
POST /api/session/{session_id}/prompt Answer a prompt, the polling fallback.
GET /api/session/{session_id}/logs Service log records, the polling fallback.
GET /api/session/{session_id}/titles The titles.
POST /api/session/{session_id}/tracks The tracks, chapters and manifests of a title.
POST /api/session/{session_id}/segments The URL, DRM, headers and cookies of the selected tracks.
POST /api/session/{session_id}/segment_filter The HLS segments the service drops.
POST /api/session/{session_id}/samples Decrypt the samples of a track the service decrypts itself.
POST /api/session/{session_id}/license A licence relay, a certificate, or the content keys of the server CDM.
POST /api/session/{session_id}/keys Store the content keys the client proved.
POST /api/session/{session_id}/keys/bad Report a server-vault content key that did not decrypt.
GET /api/session/{session_id} Remote session info.
DELETE /api/session/{session_id} End the remote session and return the changed cache files.

A client walks a remote session in this order:

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

Conventions

  • API key and owner. Each request carries the API key in X-Secret-Key (see Authentication). 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 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.

Slow responses

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.

A failure after the first 30 seconds arrives with status 200: see Late failures with status 200.

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.

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.
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 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.
profile The credentials profile. At the top level it never means a service's own --profile option.
proxy A full proxy URI, tunnel:<id> 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://<resolver>@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:<id> 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.

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": "<tunnel id>"}. The client then sends proxy: "tunnel:<id>" 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=<tunnel 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=<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=<seq> 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.
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.

{ "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": "authenticated" }
{ "status": "failed", "error": "Invalid credentials" }

CDM calls

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": "<base64>"} 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.

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.

POST /api/session/{session_id}/prompt

Answer the waiting prompt or CDM call. Body: { "response": "..." } (PromptAnswer).

=== "Response 200"

```json
{ "status": "accepted" }
```
Status Error code Meaning
200 - Answer accepted.
400 INVALID_INPUT No response, or no prompt waits.
404 SESSION_NOT_FOUND No such remote session.

GET /api/session/{session_id}/logs

The polling fallback of the remote session channel: the records of the service's own log (LogsReply). Pass since=<seq> to get only the records after the last sequence number. The route answers in each login state, failed too.

=== "Response 200"

```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
}
```

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.

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.

=== "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.

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 <id>: 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": "<base64 zlib xml>", "track_ids": [ "v-1", "a-1" ], "filtered_period_ids": [ "ad-1" ] } ],
  "track_manifests": [ { "track_id": "s-1", "type": "dash", "url": "https://...", "data": "<base64 zlib xml>" } ],
  "hls_playlists": [ { "track_id": "v-1", "url": "https://...", "data": "<base64 zlib m3u8>" } ],
  "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_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.
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.

POST /api/session/{session_id}/segments

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.

=== "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 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.

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.

POST /api/session/{session_id}/segment_filter

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": "<hex>" }, 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.

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": "<base64 CDM challenge>", "drm_type": "widevine" }
```

=== "Response 200"

```json
{ "license": "<base64 licence bytes>" }
```

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": { "<kid_hex>": "<key_hex>" }, "vault_keys": ["<kid_hex>"], "drm_type": "widevine" }
```

=== "Batch: Response 200"

```json
{ "keys": { "v-1": { "<kid_hex>": "<key_hex>" } }, "vault_keys": ["<kid_hex>"], "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.

{ "track_id": "<track_id>", "keys": { "<kid_hex>": "<key_hex>" } }
Status Error code Meaning
200 - {}, whatever the server stored.
404 SESSION_NOT_FOUND No such remote session.

POST /api/session/{session_id}/keys/bad

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.

{ "kid": "<kid_hex>", "key": "<key_hex>" }
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.

GET /api/session/{session_id}

Remote session info (SessionInfo). The client also uses it as the keep-alive of the polling fallback.

=== "Response 200"

```json
{
  "session_id": "d4e5f6a7-...",
  "service": "EXAMPLE",
  "valid": true,
  "expires_in": 300,
  "draining": false,
  "track_count": 4,
  "title_count": 10
}
```

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.

Status Error code Meaning
200 - Info returned.
404 SESSION_NOT_FOUND No such remote session, or it expired.

DELETE /api/session/{session_id}

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.

=== "Response 200"

```json
{
  "status": "ok",
  "cache": { "tokens": "<base64 zlib bytes>", "session_web/<sha1>": "<base64 zlib bytes>" }
}
```

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.

Status Error code Meaning
200 - Remote session ended.
404 SESSION_NOT_FOUND No such remote session.

Cache files

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/<sha1>, keeps its place. The value is the file, zlib-compressed and base64-encoded.

  • 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.

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.

Security properties

The API key and owner check is in Conventions, the tunnel rules are in GET /api/tunnel, and the secrets that stay on the server are in the create response. 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:<port> 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.