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