The HTTP API
Every app - the web page, the Android and iPhone shells, the native Apple TV app -
talks to the same /api. It is built in one function, Routes() in
internal/httpapi/httpapi.go, out of three nested muxes and a short chain of
middleware that every request passes through.
Three muxes, one chain
The routes are registered on three http.ServeMuxes, each behind a stricter door
than the last:
The public mux
Only what must work before anybody signs in: the app shell at / (one page for
every state - it asks /api/session and draws the sign-up form, the sign-in form or the
library), /static/, the service worker and manifest (served from the root, because a
service worker's scope is its own directory), /healthz (status, the server's name,
whether it has an owner yet - what a device searching the network shows), /ca.crt for a
device that wants to trust the local authority, the name service's reachability challenge, and
GET /api/session, POST /api/signup, /api/login (and asking
how a held sign-in went) and /api/logout. A few more must work before a session
exists, each carrying its own proof: an invitation's page and its acceptance (the token is the
proof), "Who's listening?" (/api/profiles, which a TV asks before anybody is signed
in, and switching between the people kept on this device), a TV asking for a sign-in code and
asking how it went, a TV being switched to somebody by a one-time code, and on a box the power
button's password reset.
Before any of it: plain http only at home
One port speaks both plain HTTP and TLS, and with remote access on the router forwards both.
So in front of everything, OnlyHomeOverHTTP (in internal/servetls)
sends a plain-http GET or HEAD on to https unless the address typed only works inside the house -
a private, loopback or link-local address, Tailscale's 100.64/10, a name with no dot, or one
under .local, .lan, .home and the like. Anything else
over plain http is refused, as its body has already crossed in the clear. It goes by the address
typed, not by who asks, because under Docker Desktop every connection arrives from Docker's own
gateway. The one exception is the name service's reachability check, which asks over plain http
and follows no redirect.
The guarded mux
Everything else under /api/ is mounted as
s.auth.Require(s.withUserContext(guarded)). Require refuses a request
without a valid session with 401. withUserContext then turns away three kinds of
session before anything else runs, each with a 403 the apps recognise:
- Held to a new password (
{"mustRenew": true}): the owner asked everybody to choose one, or theirs no longer meets the rules. Only/api/account/passwordanswers until they do. - Playing only (
{"limited": true}): a TV switched to somebody from their phone holds a session for playing, not for the account. It may do what playing does - positions, plays, favorites, playlists, the player itself - and nothing else, owner routes included, until that person chooses themselves in "Who's listening?" with their PIN or password. - The demo account (
{"demo": true}, only whenSOUNDSTORM_DEMO_USERnames one): the same kind of allowlist - a route added later is refused to it until somebody decides it is harmless.
Otherwise it renews the session, and puts two things into the request's context: the account
id (source.WithUserID) and what that account may reach
(source.WithAccess).
Registry.All, Matching and ByID all take a context, so a
handler physically cannot reach a source without passing the request's context - and with it
the restriction. Changing those three signatures made the compiler find every call site;
remembering to check in each handler would not have. A test walks every endpoint that can hand
over bytes, metadata or a playable address and checks a restricted account is refused.The owner mux
Routes only the owner may use live on a third mux, wrapped in
s.auth.RequireOwner. One trap shaped how it is wired: an owner route must be
mounted as well as registered. The owner mux only answers for paths also handed to the
guarded mux with guarded.Handle("/api/...", RequireOwner(owner)). The read-along
switch in Settings was once registered but not mounted, and answered 404 unnoticed until a test
for another feature went through the same door. TestOwnerSettingsAnswer now asks
every owner setting.
The middleware, outermost first
Logging
withLogging records method, path, status and milliseconds for each request.
Media, art, book resources and static files log at debug - a film is hundreds of requests and
would bury everything else. Paths that carry a secret - an invitation's token, a TV's sign-in
code or id, a held sign-in's id - are logged with that part replaced by ..., as the
log's last lines go into a file people are told to send when setup fails. It wraps the response writer in a statusRecorder, and
that recorder has an Unwrap method for a reason that cost months:
http.ResponseController reaches the real connection only through wrappers that
unwrap. Without it, every read deadline set behind the logger answered
ErrNotSupported, each caller discarded the error, and both the body deadline and the
upload window silently did nothing. Their unit tests built the handler without the logger and
passed throughout; a test through the real route chain is what found it.
Security headers
secureHeaders sets X-Frame-Options: SAMEORIGIN (a PDF opens in an
iframe of EmberStorm's own, so not DENY), nosniff and a same-origin referrer policy.
HSTS is sent only on the real certificate's name and only while a valid real certificate is
loaded - and for a week, not a year. A home server's certificate can genuinely lapse, and a
browser pinned for a year to a name now served by the untrusted fallback would have no way
through. A week heals itself, and every visit while the certificate works pushes it back out.
Same origin
The session cookie is SameSite=Lax, which is normally enough against cross-site
writes. Here it is not: every install's real name is under emberstorm.app, which is
not yet on the Public Suffix List, so to a browser another install - including one an attacker
set up - is the same site. So sameOrigin refuses any request other than
GET, HEAD or OPTIONS whose Sec-Fetch-Site is anything but
same-origin or none, falling back to comparing Origin with
the host. A request with neither header did not come from a browser page - the installer, curl,
the Apple TV app - and carries no cookie a page could have borrowed. Reads under
/api/ are guarded too, more lightly: a GET whose Sec-Fetch-Site is
same-site or cross-site is refused, because some reads start work - a
film's conversion, a song heard, a voice's sample - that another site's page could otherwise fire
through a visitor's browser.
Body deadlines
bodyDeadline gives any request that has a body thirty seconds to send it. Every
body here except a file is a few hundred bytes of JSON, so that is generous, and it stops a
client holding a connection open by sending a byte at a time. File uploads - /api/upload,
a piece of a large upload, a phone's photo backup, a piece of a photo download - get a rolling window instead
(stallReader): the deadline moves a minute forward only once 16KB has arrived since
it last moved. A bad mobile link manages that easily; a trickle of one byte every fifty-nine
seconds never does. An account may also have at most four uploads in flight (a phone's
backups have an allowance of their own, 64, and are refused at once rather than held waiting,
since a held request's unread body would stall the others sharing its connection).
Why there is no global ReadTimeout
The http.Server has a ReadHeaderTimeout of ten seconds, an
IdleTimeout of two minutes and a 64KB header limit - and deliberately no
ReadTimeout or WriteTimeout. A write timeout would cut off a film
mid-playback. A read timeout is subtler: a read deadline that expires while a response is still
being written cancels the request's context, and a stream stops with it. A film is a request
with no body and a response that runs for two hours, so the deadline belongs on the body
alone, which is exactly what bodyDeadline does.
Rate limits: allowances
Some writes are cheap to send and expensive to receive - each rewrites a person's whole
collections file, or state.json under the lock every request takes, or calls a
service outside the house. Those go through an allowance: a per-person token bucket
with a burst and a refill rate (a few open routes key it by address instead), put in front of a handler with
s.limited(&bucket, burst, every, handler). Past it the answer is 429, "too many
changes at once; wait a moment".
| Allowance | Covers | Shape |
|---|---|---|
listWrites | Favorites, playlists, photo albums and sharing them, custom covers, preferences, film matching and posters, episode numbering | 60, then one a second |
plays | Recording a play (rewrites the collections file and appends to the listen log) | 20, then one every 10s; dropped quietly past it |
positions | Reading positions (each rewrites state.json) | 30, then one every 2s; the app keeps an unsynced copy and retries |
otherWrites | Audiobook positions sent to Audiobookshelf, the scrobbling token check, the read-along queue | per route |
nowPlaying, imports, plexPins, artUploads | "Playing now" to ListenBrainz, playlist imports, Plex sign-ins, cover uploads | per route |
startAsks, sendAsks, photoChecks, checkAsks, pieceStarts | Work that starts something - a read-along sync, an ebook made, a voice sample, a photo import, taking photos sent; sending photos (ten, then one every 30 seconds); a phone's backup checks; checking names already taken; starting an upload in pieces | per route |
keeps, playerCommands, guideAsks, reports, linkAsks, inviteTries | "Keep me on this device", commands to another player, the episode guide, playback reports, TV sign-in codes and invitation lookups (these two keyed by address, as nobody is signed in yet) | per route |
The tables behind them forget full buckets once they pass 1,024 entries and refuse newcomers
past 100,000, so a flood of new names or addresses cannot grow them without end. Other ceilings
are not token buckets: at most four live Jellyfin play sessions per person, counted per video as
well (hlsSessions), four uploads in flight, two password hashes at once across the
whole server (see accounts), and minimum gaps between library
rescans.
Error conventions
- JSON everywhere.
writeJSONsets the content type andnosniff;writeErroranswers{"error": "..."}with a sentence written for a person, because the app shows it as it is. - Search never fails. A federated search is always 200, with
degradedand a per-source error slot saying what is missing. A dead backend must never take the search down. - Declining on purpose is not failing. An upload of something already in the library is a 409 ("already in your library"), and the app shows it as skipped, not failed. A full photo space is a 507.
- A refusal the app acts on says why in the body. Beside
error, a 403 carriesmustRenew,limitedordemo, and the app shows the matching screen or message rather than a bare "forbidden". - No secrets in errors. A transport error's text can carry the request
address, and a Subsonic address carries its credential in the query;
httpx.Redactstrips it. Members see "did not answer"; the owner sees setup detail; the log gets the rest. Filesystem errors have the container's own paths taken out before a browser sees them. - A shelf you may not see is not there. For a restricted account the
registry's
ByIDreports a source outside its access exactly as it reports one that does not exist, so streams, art and lookups fail as "no such source". Uploading, where a person chose the shelf, says so plainly: "you do not have the films library", a 403.
Notable endpoints
| Area | Endpoints |
|---|---|
| Session | GET /api/session (signed in? secure name to move to? remote-access state), POST /api/signup, /api/login (202 and a pending id when a new device needs approval), /api/login/pending/{id}, /api/logout, POST /api/account/password, PUT /api/account/pin, PUT|DELETE /api/account/picture |
| Devices and people | GET /api/devices/pending and POST /api/devices/pending/{id} (allowing a new device), GET /api/profiles, POST /api/profiles/switch, POST /api/profiles/keep, DELETE /api/profiles/{id}, GET /api/profiles/{id}/picture ("Who's listening?"), POST /api/link, GET /api/link/{id}, /api/link/{id}/qr.png, GET|POST /api/link/code/{code} (signing a TV in from a phone), GET|POST /api/invite/{token} (accepting an invitation) |
| Players | POST /api/players/hello, /state, GET /api/players/{id}/next (a long poll for commands), POST /api/players/{id}/command, GET|POST /api/players/{id}/ask/{ask} (a TV in use asking whether to let somebody take over), POST /api/players/switch (playing on, and controlling, another device) |
| Setup and library | GET /api/setup (backends getting ready), GET /api/library (counts, free space), POST /api/library/rescan, GET /api/probe (a link-speed sample), POST /api/diagnostics/playback (a playback report, on the developer's install) |
| Search and browse | GET /api/search (empty q browses a shelf), GET /api/home, GET /api/continue, GET /api/genres, GET /api/books/pairs|authors|series, GET /api/tv/show, /api/tv/next |
| Playing | GET /api/stream/{source}/{id}, GET /api/art/{source}/{id}, GET /api/playback/{source}/{id} (direct or HLS, tracks, chapters, position), PUT /api/playback/... (audiobook position), GET /api/hls/{source}/{path}, GET /api/bookhls/... (a long audiobook in pieces), GET /api/subtitle/... |
| Books | GET /api/book/manifest, /api/book/resource (one file from inside an EPUB), GET|PUT /api/book/progress, GET|POST /api/readalong, POST /api/readalong/next, /api/voices, /api/voices/sample, POST /api/voices/make|make-ebook, /api/voices/jobs (making an audiobook or an ebook, and its queue) |
| Music | /api/music/albums, /artists, /mixes, GET|POST /api/music/radio, /api/music/sound, /api/music/beats, /api/music/lyrics/..., POST /api/history, /api/scrobble, GET /api/recap, GET|PUT /api/training/song (the developer's install only) |
| Collections | /api/favorites, /api/playlists (and items, move, import), /api/plex/*, /api/myart, GET|PATCH /api/prefs |
| Uploads | POST /api/upload/plan (where would these go?), POST /api/upload/check (names already taken), POST /api/upload/describe (a name for a second file of the same name), PUT /api/upload?path=&kind= (one file as the whole body), /api/upload/pieces (a large file in 8MB pieces), /api/drives/... (a USB drive on a box, owner only) |
| Photos | /api/photos/people, /places, /on-this-day, /of?type= (videos, Live Photos, stills), /usage, POST /api/photos/backup/check, GET /api/photos/backup/marker, PUT /api/photos/backup, /api/photos/import (resumable pieces), /api/photos/months and /month (the timeline), /api/photos/albums (albums, and sharing, leaving and accepting them through /api/photos/shares), POST /api/photos/save (copies of a shared album's photos), GET /api/photos/send-to, POST /api/photos/send and /api/photos/inbox (sending photos to somebody) |
| Owner only | /api/users (add, remove, reset password, libraries, photo limit, may make books), /api/tvs (TVs shared with the house), /api/photos/limit-default, POST /api/users/new-passwords (everyone must choose a new password), /api/invites, PUT /api/remote, /api/settings/lyrics|discovery|readalong|new-devices|server-name|web-name|findable, /api/books/pairs/not-same|by-hand, /api/films/... (find the right film or show, its poster), /api/tv/numbering and /api/tv/guide (numbering a show's episodes), POST /api/move, POST /api/delete/preview, /api/delete, /api/delete/undo, /api/reset (Start over and Erase, on a box), /api/box/... (a box's updates, time zone, switching it off) |
Item ids in paths are attacker-supplied and are treated as such: the hardened client in
internal/httpx refuses absolute references, a second leading slash and dot segments
for every adapter, after a path like /api/hls/jellyfin/%252e%252e/System/Info once
reached Jellyfin's admin API through a double decode. HLS paths must match the shapes Jellyfin's
own playlists use.
Body limits
Every JSON body is read through http.MaxBytesReader with a cap sized to what it
can legitimately hold:
| Body | Cap |
|---|---|
| Sign-in, sign-up, password change, account creation | 4KB (maxCredentialBody) - an unauthenticated endpoint must not be a memory sink |
| Reading position | 8KB (maxProgressBody); a CFI is also capped at 2KB and a fraction must be in [0, 1] |
| Small settings (lyrics, discovery, radio taste, scrobbling token) | 1KB |
| Favorites, playlists, preferences, read-along requests | per-route constants of a few KB |
| Photo backup check, Plex import list | 1MB, 64KB |
| Custom cover | 4MB, and only JPEG, PNG or WebP by their bytes |
| File uploads | no fixed cap; refused when they would leave under 1GB free on the library's disk |