Skip to main content

koan_server/ui/
mod.rs

1//! The web UI: sign in, browse the library and play it in the browser.
2//!
3//! Server-rendered HTML, with Datastar for the parts that change in place
4//! (search as you type, the share button) and a small script of
5//! its own that swaps only the page content on navigation, so the player keeps
6//! playing. Playback happens in the browser, streaming from `/ui/stream`: a
7//! headless server has no speakers.
8//!
9//! Sign-in is koan's own session: the same `HttpOnly` access and refresh
10//! cookies the JSON login sets, so tokens never reach page script. The gate
11//! accepts a valid access cookie; a page load without one goes through
12//! `/auth/resume`, which spends the refresh cookie (scoped to `/auth`, so only
13//! that route sees it) for fresh cookies, or on to the sign-in form.
14
15mod account;
16mod browse;
17mod connect;
18mod favourite;
19mod history;
20mod oauth;
21mod pages;
22mod pair;
23mod scrobbling;
24mod session;
25#[cfg(test)]
26mod tests;
27mod users;
28
29pub use oauth::RESOURCE_METADATA;
30pub use session::ProxyAuth;
31
32use std::path::PathBuf;
33use std::sync::Arc;
34
35use axum::extract::{Path, RawQuery, Request, State};
36use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
37use axum::middleware::{Next, from_fn, from_fn_with_state};
38use axum::response::sse::{Event, Sse};
39use axum::response::{IntoResponse, Response};
40use axum::routing::{get, post};
41use koan_core::auth;
42use koan_core::db::pool::{Handle, Pool};
43use koan_core::db::queries;
44
45use crate::auth::AuthUser;
46use crate::auth::routes::{AuthRouteState, RateLimiter, login_rate_limit, rate_limit};
47use crate::covers::Covers;
48use crate::share::{asset, blocking, not_found};
49
50/// `'unsafe-eval'` because Datastar compiles its attribute expressions.
51/// Everything else is this server's own, and nothing is inline.
52const PAGE_CSP: &str = "default-src 'none'; script-src 'self' 'unsafe-eval'; style-src 'self'; font-src 'self'; \
53     img-src 'self'; media-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; \
54     frame-ancestors 'none'";
55
56/// Sent by the UI's own navigation, which wants the page content without the shell.
57const PARTIAL: &str = "x-koan-partial";
58
59const UI_CSS: &str = include_str!("../../assets/ui.css");
60const UI_JS: &str = include_str!("../../assets/ui.js");
61const DATASTAR_JS: &str = include_str!("../../assets/datastar.js");
62const NO_COVER_SVG: &str = include_str!("../../assets/no-cover.svg");
63
64/// The page's stylesheet and scripts, each URL carrying a hash of its asset.
65pub(super) struct AssetUrls {
66    pub css: String,
67    pub css_hash: String,
68    pub ui_js: String,
69    pub player_js: String,
70    pub datastar_js: String,
71}
72
73pub(super) static ASSETS: std::sync::LazyLock<AssetUrls> = std::sync::LazyLock::new(|| {
74    use crate::share::versioned;
75    AssetUrls {
76        css: versioned("/ui/assets/ui.css", UI_CSS),
77        css_hash: crate::share::content_hash(UI_CSS),
78        ui_js: versioned("/ui/assets/ui.js", UI_JS),
79        player_js: versioned("/ui/assets/player.js", crate::share::ENGINE_JS),
80        datastar_js: versioned("/ui/assets/datastar.js", DATASTAR_JS),
81    }
82});
83
84#[derive(Clone)]
85pub struct UiState {
86    pool: Arc<Pool>,
87    covers: Arc<Covers>,
88    /// The codecs and genres the filters offer, with when they were read.
89    options: Arc<std::sync::Mutex<Option<(std::time::Instant, pages::Options)>>>,
90    auth: AuthRouteState,
91    auth_enabled: bool,
92    /// `sharing.public_url`, the address invites point clients at.
93    public_url: Option<String>,
94    /// OAuth codes awaiting their token request.
95    codes: oauth::Codes,
96    /// `mcp.redirect_hosts`.
97    redirect_hosts: Arc<Vec<String>>,
98    /// `graphql.proxy_auth_header`, when an authenticating proxy is trusted.
99    proxy_auth: Option<ProxyAuth>,
100}
101
102pub fn router(
103    pool: Arc<Pool>,
104    auth: AuthRouteState,
105    auth_enabled: bool,
106    covers: Arc<Covers>,
107    public_url: Option<String>,
108    redirect_hosts: Vec<String>,
109    proxy_auth: Option<ProxyAuth>,
110) -> axum::Router {
111    let state = UiState {
112        pool,
113        covers,
114        options: Arc::default(),
115        auth,
116        auth_enabled,
117        public_url,
118        codes: oauth::Codes::default(),
119        redirect_hosts: Arc::new(redirect_hosts),
120        proxy_auth,
121    };
122    let gated = axum::Router::new()
123        .route("/", get(pages::albums))
124        .route("/albums", get(pages::albums))
125        .route("/album/{id}", get(pages::album))
126        .route("/album/{id}/share", post(pages::share_album))
127        .route("/artist/{id}/share", post(pages::share_artist))
128        .route("/artists", get(pages::artists))
129        .route("/artist/{id}", get(pages::artist))
130        .route("/tracks", get(pages::tracks))
131        .route("/playlists", get(pages::playlists))
132        .route("/playlist/{id}", get(pages::playlist))
133        .route("/search", get(pages::search))
134        .route("/search/results", get(pages::search_results))
135        .route("/queue", get(pages::queue))
136        .route("/library", get(pages::library))
137        .route("/favourites", get(pages::favourites))
138        .route("/recent", get(pages::recent))
139        .route("/history", get(history::page))
140        .route("/favourite/{kind}/{id}", post(favourite::toggle))
141        .route("/history/forget", post(history::forget))
142        .route("/connect", get(connect::page))
143        .route("/account", get(account::page))
144        .route("/account/keys", post(account::create_key))
145        .route("/account/keys/{id}/revoke", post(account::revoke_key))
146        .route("/account/app-passwords", post(account::create_app_password))
147        .route(
148            "/account/app-passwords/{id}/revoke",
149            post(account::revoke_app_password),
150        )
151        // Where the keys page was.
152        .route("/keys", get(|| async { see_other("/account") }))
153        .route("/scrobbling", get(scrobbling::page))
154        .route("/scrobbling/listenbrainz", post(scrobbling::connect))
155        .route(
156            "/scrobbling/listenbrainz/disconnect",
157            post(scrobbling::disconnect),
158        )
159        .route("/users", get(users::page).post(users::create))
160        .route("/users/{id}/invite", post(users::invite))
161        .route("/users/{id}/password", post(users::set_password))
162        .route("/users/{id}/password/form", post(users::password_form))
163        .route("/users/{id}/role", post(users::set_role))
164        .route("/users/{id}/delete", post(users::delete))
165        .route("/ui/stream/{id}", get(stream))
166        .route("/ui/cover/{id}", get(cover))
167        .layer(from_fn(require_datastar_on_post))
168        .layer(from_fn_with_state(state.clone(), gate))
169        .layer(axum::middleware::map_response(stamp_stylesheet));
170    // A plain form, since it answers with a redirect to the client: it proves
171    // its origin the way the sign-in form does.
172    let consent = axum::Router::new()
173        .route(
174            "/oauth/authorize",
175            get(oauth::authorize).post(oauth::approve),
176        )
177        .layer(from_fn_with_state(state.clone(), gate));
178    // Approving a device waiting to sign in: plain forms too, reached from a
179    // phone that may never have opened the UI. See `crate::pair`.
180    let pairing = axum::Router::new()
181        .route("/pair", get(pair::form))
182        .route("/pair/{pair}", get(pair::confirm))
183        .route("/pair/{pair}/approve", post(pair::approve))
184        .route("/pair/{pair}/decline", post(pair::decline))
185        .layer(from_fn_with_state(state.clone(), gate));
186    // Checking a password is deliberately expensive, so the form shares the
187    // JSON login's per-IP window.
188    let sign_in = get(session::login_form).merge(
189        post(session::login).layer(from_fn_with_state(state.auth.clone(), login_rate_limit)),
190    );
191    axum::Router::new()
192        .merge(gated)
193        .merge(consent)
194        .merge(pairing)
195        .route(
196            "/.well-known/oauth-protected-resource",
197            get(oauth::protected_resource),
198        )
199        .route(oauth::RESOURCE_METADATA, get(oauth::protected_resource))
200        .route(
201            "/.well-known/oauth-authorization-server",
202            get(oauth::authorization_server),
203        )
204        // Unauthenticated, so capped per IP: registering stores nothing, but
205        // signs a client id each time.
206        .route(
207            "/oauth/register",
208            post(oauth::register)
209                .layer(axum::extract::DefaultBodyLimit::max(
210                    oauth::MAX_REGISTRATION_BODY,
211                ))
212                .layer(from_fn_with_state(
213                    Arc::new(RateLimiter::new(3600, 10)),
214                    rate_limit,
215                )),
216        )
217        .route(
218            "/oauth/token",
219            post(oauth::token).layer(from_fn_with_state(
220                Arc::new(RateLimiter::new(60, 60)),
221                rate_limit,
222            )),
223        )
224        .route("/login", sign_in)
225        .route("/auth/resume", get(session::resume))
226        .route(session::PROXY_RESUME, get(session::proxy_resume))
227        .route("/ui/renew", post(session::proxy_renew))
228        .route("/auth/renew", post(session::renew))
229        .route("/auth/signout", post(session::signout))
230        .route("/ui/assets/{name}", get(ui_asset))
231        // Where anything that wants an icon for this host looks first, before
232        // reading a page: without it, a favicon service settles for the parent
233        // domain's.
234        .route(
235            "/favicon.ico",
236            get(|| ui_asset(Path("icon-192.png".into()), RawQuery(None))),
237        )
238        .route(
239            "/apple-touch-icon.png",
240            get(|| ui_asset(Path("apple-touch-icon.png".into()), RawQuery(None))),
241        )
242        .with_state(state)
243}
244
245/// Which stylesheet the markup was written for. A tab open across an upgrade
246/// keeps the old one while navigation and patches bring new markup; ui.js
247/// swaps the stylesheet when this names another.
248async fn stamp_stylesheet(mut res: Response) -> Response {
249    if let Ok(v) = HeaderValue::from_str(&ASSETS.css_hash) {
250        res.headers_mut().insert("x-koan-css", v);
251    }
252    res
253}
254
255async fn ui_asset(Path(name): Path<String>, query: RawQuery) -> Response {
256    const JS: &str = "text/javascript; charset=utf-8";
257    match name.as_str() {
258        "ui.css" => asset(UI_CSS, "text/css; charset=utf-8", query),
259        "ui.js" => asset(UI_JS, JS, query),
260        "player.js" => asset(crate::share::ENGINE_JS, JS, query),
261        "datastar.js" => asset(DATASTAR_JS, JS, query),
262        other => crate::share::binary_asset(other).unwrap_or_else(not_found),
263    }
264}
265
266fn cookie<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
267    headers
268        .get_all(header::COOKIE)
269        .iter()
270        .filter_map(|v| v.to_str().ok())
271        .flat_map(|v| v.split(';'))
272        .find_map(|c| c.trim().strip_prefix(name)?.strip_prefix('='))
273}
274
275/// A request the UI's script makes rather than a page the browser navigates to.
276/// Such a request cannot follow a redirect to a sign-in page usefully, so it
277/// is refused outright and the script reloads.
278fn is_navigation(req: &Request) -> bool {
279    req.method() == Method::GET
280        && !req.headers().contains_key(PARTIAL)
281        && !req.headers().contains_key("datastar-request")
282        && !req.uri().path().starts_with("/ui/")
283}
284
285/// Let a signed-in user through; send a page load to resume its session, and
286/// refuse anything else. Behind an authenticating proxy a session is good only
287/// for the account the proxy names, so a browser whose proxy sign-in changed
288/// hands over to the new account, and a header from the proxy that names no
289/// one account lets no session through.
290async fn gate(State(s): State<UiState>, mut req: Request, next: Next) -> Response {
291    let user = if s.auth_enabled {
292        let vouched = session::vouched(&s, req.headers(), req.extensions());
293        if vouched == session::Vouch::Unusable {
294            return session::unusable_header(&s);
295        }
296        let claims = cookie(req.headers(), "koan_access")
297            .and_then(|t| auth::validate_access_token(&s.auth.public_pem, t).ok());
298        match (claims, vouched) {
299            (Some(claims), session::Vouch::Absent) => {
300                crate::auth::current_user(&s.pool, claims).await
301            }
302            (Some(claims), session::Vouch::Named(name)) if name == claims.username => {
303                crate::auth::current_user(&s.pool, claims).await
304            }
305            _ => None,
306        }
307    } else {
308        Some(AuthUser::anonymous_admin())
309    };
310    match user {
311        Some(user) => {
312            req.extensions_mut().insert(user);
313            next.run(req).await
314        }
315        None if is_navigation(&req) => {
316            let here = req
317                .uri()
318                .path_and_query()
319                .map_or("/", |p| p.as_str())
320                .to_owned();
321            let resume = if s.proxy_auth.is_some() {
322                session::PROXY_RESUME
323            } else {
324                "/auth/resume"
325            };
326            see_other(&format!("{resume}?next={}", encode(&here)))
327        }
328        None => (
329            StatusCode::UNAUTHORIZED,
330            [(header::CACHE_CONTROL, "no-store")],
331            "signed out",
332        )
333            .into_response(),
334    }
335}
336
337/// Datastar sends this header on every request it makes, and a cross-site form
338/// or a CORS-safelisted fetch cannot set it: a state-changing POST without it
339/// did not come from this UI.
340async fn require_datastar_on_post(req: Request, next: Next) -> Response {
341    if req.method() == Method::POST && !req.headers().contains_key("datastar-request") {
342        return StatusCode::FORBIDDEN.into_response();
343    }
344    next.run(req).await
345}
346
347fn encode(s: &str) -> String {
348    form_urlencoded::byte_serialize(s.as_bytes()).collect()
349}
350
351fn see_other(location: &str) -> Response {
352    (
353        StatusCode::SEE_OTHER,
354        [
355            (header::LOCATION, location),
356            (header::CACHE_CONTROL, "no-store"),
357        ],
358    )
359        .into_response()
360}
361
362/// An HTML page with the UI's security headers.
363fn html(status: StatusCode, body: String) -> Response {
364    let mut resp = (status, body).into_response();
365    let h = resp.headers_mut();
366    h.insert(
367        header::CONTENT_TYPE,
368        HeaderValue::from_static("text/html; charset=utf-8"),
369    );
370    h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
371    h.insert(header::VARY, HeaderValue::from_static("x-koan-partial"));
372    h.insert(
373        header::CONTENT_SECURITY_POLICY,
374        HeaderValue::from_static(PAGE_CSP),
375    );
376    h.insert(
377        header::REFERRER_POLICY,
378        HeaderValue::from_static("same-origin"),
379    );
380    h.insert(
381        header::X_CONTENT_TYPE_OPTIONS,
382        HeaderValue::from_static("nosniff"),
383    );
384    h.insert(
385        "x-robots-tag",
386        HeaderValue::from_static("noindex, nofollow"),
387    );
388    resp
389}
390
391/// A Datastar `patch-elements` event. Without a selector the element replaces
392/// the one with its id; with one, `mode` says where it goes.
393fn patch(html: &str, target: Option<(&str, &str)>) -> Event {
394    let mut lines = Vec::new();
395    if let Some((selector, mode)) = target {
396        lines.push(format!("selector {selector}"));
397        lines.push(format!("mode {mode}"));
398    }
399    lines.extend(html.lines().map(|l| format!("elements {l}")));
400    Event::default()
401        .event("datastar-patch-elements")
402        .data(lines.join("\n"))
403}
404
405fn events(events: Vec<Event>) -> Response {
406    let stream = tokio_stream::iter(events.into_iter().map(Ok::<_, std::convert::Infallible>));
407    let mut resp = Sse::new(stream).into_response();
408    resp.headers_mut()
409        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
410    resp
411}
412
413fn open(pool: &Pool) -> Option<Handle<'_>> {
414    pool.get()
415        .inspect_err(|e| log::error!("web UI: cannot open the database: {e}"))
416        .ok()
417}
418
419/// A track's audio, from a local file; Range requests are honoured, so the
420/// browser can seek a stream.
421async fn stream(State(s): State<UiState>, Path(id): Path<i64>, headers: HeaderMap) -> Response {
422    let path = blocking(move || {
423        let db = open(&s.pool)?;
424        let t = queries::tracks_by_ids(&db.conn, &[id]).ok()?.pop()?;
425        crate::subsonic::track_file_path(&t).map(PathBuf::from)
426    })
427    .await;
428    let Some(path) = path else {
429        return not_found();
430    };
431    match crate::subsonic::serve_local_file(&path, &headers).await {
432        Ok(mut resp) => {
433            resp.headers_mut().insert(
434                header::CACHE_CONTROL,
435                HeaderValue::from_static("private, max-age=3600"),
436            );
437            resp
438        }
439        Err(_) => not_found(),
440    }
441}
442
443/// Query parameters for `cover`.
444#[derive(serde::Deserialize, Default)]
445#[serde(default)]
446struct CoverQuery {
447    size: Option<u32>,
448    /// The album's cover version, from `pages::cover_url`. With it the URL
449    /// names these exact bytes, so the browser may keep them for good.
450    v: Option<String>,
451}
452
453/// An album's cover at one of `covers::SIZES`, from the art embedded in the
454/// first of its tracks that has any.
455async fn cover(
456    State(s): State<UiState>,
457    Path(id): Path<i64>,
458    axum::extract::Query(q): axum::extract::Query<CoverQuery>,
459) -> Response {
460    let size = crate::covers::snap(q.size);
461    let found = blocking(move || {
462        let tracks = queries::tracks_for_album(&open(&s.pool)?.conn, id).ok()?;
463        (!tracks.is_empty()).then(|| s.covers.cover(&tracks, size))
464    })
465    .await;
466    match found {
467        Some(Some(art)) => crate::share::jpeg(Some(art), q.v.is_some()),
468        // A record with no artwork draws what the apps draw, not a broken
469        // image. Not kept for good: art added beside the files changes no
470        // track's mtime, so the URL stays the same when it arrives.
471        Some(None) => (
472            [
473                (header::CONTENT_TYPE, "image/svg+xml"),
474                (header::CACHE_CONTROL, "private, max-age=3600"),
475            ],
476            NO_COVER_SVG,
477        )
478            .into_response(),
479        None => not_found(),
480    }
481}