1mod browse;
16mod connect;
17mod keys;
18mod oauth;
19mod pages;
20mod session;
21#[cfg(test)]
22mod tests;
23mod users;
24
25pub use oauth::RESOURCE_METADATA;
26
27use std::path::PathBuf;
28use std::sync::Arc;
29
30use axum::extract::{Path, RawQuery, Request, State};
31use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
32use axum::middleware::{Next, from_fn, from_fn_with_state};
33use axum::response::sse::{Event, Sse};
34use axum::response::{IntoResponse, Response};
35use axum::routing::{get, post};
36use koan_core::auth;
37use koan_core::db::pool::{Handle, Pool};
38use koan_core::db::queries;
39
40use crate::auth::AuthUser;
41use crate::auth::routes::{AuthRouteState, RateLimiter, login_rate_limit, rate_limit};
42use crate::covers::Covers;
43use crate::share::{asset, blocking, not_found};
44
45const PAGE_CSP: &str = "default-src 'none'; script-src 'self' 'unsafe-eval'; style-src 'self'; font-src 'self'; \
48 img-src 'self'; media-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; \
49 frame-ancestors 'none'";
50
51const PARTIAL: &str = "x-koan-partial";
53
54const UI_CSS: &str = include_str!("../../assets/ui.css");
55const UI_JS: &str = include_str!("../../assets/ui.js");
56const DATASTAR_JS: &str = include_str!("../../assets/datastar.js");
57
58pub(super) struct AssetUrls {
60 pub css: String,
61 pub css_hash: String,
62 pub ui_js: String,
63 pub player_js: String,
64 pub datastar_js: String,
65}
66
67pub(super) static ASSETS: std::sync::LazyLock<AssetUrls> = std::sync::LazyLock::new(|| {
68 use crate::share::versioned;
69 AssetUrls {
70 css: versioned("/ui/assets/ui.css", UI_CSS),
71 css_hash: crate::share::content_hash(UI_CSS),
72 ui_js: versioned("/ui/assets/ui.js", UI_JS),
73 player_js: versioned("/ui/assets/player.js", crate::share::ENGINE_JS),
74 datastar_js: versioned("/ui/assets/datastar.js", DATASTAR_JS),
75 }
76});
77
78#[derive(Clone)]
79pub struct UiState {
80 pool: Arc<Pool>,
81 covers: Arc<Covers>,
82 options: Arc<std::sync::Mutex<Option<(std::time::Instant, pages::Options)>>>,
84 auth: AuthRouteState,
85 auth_enabled: bool,
86 public_url: Option<String>,
88 codes: oauth::Codes,
90 redirect_hosts: Arc<Vec<String>>,
92}
93
94pub fn router(
95 pool: Arc<Pool>,
96 auth: AuthRouteState,
97 auth_enabled: bool,
98 covers: Arc<Covers>,
99 public_url: Option<String>,
100 redirect_hosts: Vec<String>,
101) -> axum::Router {
102 let state = UiState {
103 pool,
104 covers,
105 options: Arc::default(),
106 auth,
107 auth_enabled,
108 public_url,
109 codes: oauth::Codes::default(),
110 redirect_hosts: Arc::new(redirect_hosts),
111 };
112 let gated = axum::Router::new()
113 .route("/", get(pages::albums))
114 .route("/albums", get(pages::albums))
115 .route("/albums/more", get(pages::albums_more))
116 .route("/album/{id}", get(pages::album))
117 .route("/album/{id}/share", post(pages::share_album))
118 .route("/artist/{id}/share", post(pages::share_artist))
119 .route("/artists", get(pages::artists))
120 .route("/artists/more", get(pages::artists_more))
121 .route("/artist/{id}", get(pages::artist))
122 .route("/playlists", get(pages::playlists))
123 .route("/playlist/{id}", get(pages::playlist))
124 .route("/search", get(pages::search))
125 .route("/search/results", get(pages::search_results))
126 .route("/queue", get(pages::queue))
127 .route("/connect", get(connect::page))
128 .route("/keys", get(keys::page).post(keys::create))
129 .route("/keys/{id}/revoke", post(keys::revoke))
130 .route("/users", get(users::page).post(users::create))
131 .route("/users/{id}/invite", post(users::invite))
132 .route("/users/{id}/password", post(users::set_password))
133 .route("/users/{id}/password/form", post(users::password_form))
134 .route("/users/{id}/role", post(users::set_role))
135 .route("/users/{id}/delete", post(users::delete))
136 .route("/ui/stream/{id}", get(stream))
137 .route("/ui/cover/{id}", get(cover))
138 .layer(from_fn(require_datastar_on_post))
139 .layer(from_fn_with_state(state.clone(), gate))
140 .layer(axum::middleware::map_response(stamp_stylesheet));
141 let consent = axum::Router::new()
144 .route(
145 "/oauth/authorize",
146 get(oauth::authorize).post(oauth::approve),
147 )
148 .layer(from_fn_with_state(state.clone(), gate));
149 let sign_in = get(session::login_form).merge(
152 post(session::login).layer(from_fn_with_state(state.auth.clone(), login_rate_limit)),
153 );
154 axum::Router::new()
155 .merge(gated)
156 .merge(consent)
157 .route(
158 "/.well-known/oauth-protected-resource",
159 get(oauth::protected_resource),
160 )
161 .route(oauth::RESOURCE_METADATA, get(oauth::protected_resource))
162 .route(
163 "/.well-known/oauth-authorization-server",
164 get(oauth::authorization_server),
165 )
166 .route(
169 "/oauth/register",
170 post(oauth::register)
171 .layer(axum::extract::DefaultBodyLimit::max(
172 oauth::MAX_REGISTRATION_BODY,
173 ))
174 .layer(from_fn_with_state(
175 Arc::new(RateLimiter::new(3600, 10)),
176 rate_limit,
177 )),
178 )
179 .route(
180 "/oauth/token",
181 post(oauth::token).layer(from_fn_with_state(
182 Arc::new(RateLimiter::new(60, 60)),
183 rate_limit,
184 )),
185 )
186 .route("/login", sign_in)
187 .route("/auth/resume", get(session::resume))
188 .route("/auth/renew", post(session::renew))
189 .route("/auth/signout", post(session::signout))
190 .route("/ui/assets/{name}", get(ui_asset))
191 .route(
195 "/favicon.ico",
196 get(|| ui_asset(Path("icon-192.png".into()), RawQuery(None))),
197 )
198 .route(
199 "/apple-touch-icon.png",
200 get(|| ui_asset(Path("apple-touch-icon.png".into()), RawQuery(None))),
201 )
202 .with_state(state)
203}
204
205async fn stamp_stylesheet(mut res: Response) -> Response {
209 if let Ok(v) = HeaderValue::from_str(&ASSETS.css_hash) {
210 res.headers_mut().insert("x-koan-css", v);
211 }
212 res
213}
214
215async fn ui_asset(Path(name): Path<String>, query: RawQuery) -> Response {
216 const JS: &str = "text/javascript; charset=utf-8";
217 match name.as_str() {
218 "ui.css" => asset(UI_CSS, "text/css; charset=utf-8", query),
219 "ui.js" => asset(UI_JS, JS, query),
220 "player.js" => asset(crate::share::ENGINE_JS, JS, query),
221 "datastar.js" => asset(DATASTAR_JS, JS, query),
222 other => crate::share::binary_asset(other).unwrap_or_else(not_found),
223 }
224}
225
226fn cookie<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
227 headers
228 .get_all(header::COOKIE)
229 .iter()
230 .filter_map(|v| v.to_str().ok())
231 .flat_map(|v| v.split(';'))
232 .find_map(|c| c.trim().strip_prefix(name)?.strip_prefix('='))
233}
234
235fn is_navigation(req: &Request) -> bool {
239 req.method() == Method::GET
240 && !req.headers().contains_key(PARTIAL)
241 && !req.headers().contains_key("datastar-request")
242 && !req.uri().path().starts_with("/ui/")
243}
244
245async fn gate(State(s): State<UiState>, mut req: Request, next: Next) -> Response {
248 let user = if s.auth_enabled {
249 match cookie(req.headers(), "koan_access")
250 .and_then(|t| auth::validate_access_token(&s.auth.public_pem, t).ok())
251 {
252 Some(claims) => crate::auth::current_user(&s.pool, claims).await,
253 None => None,
254 }
255 } else {
256 Some(AuthUser::anonymous_admin())
257 };
258 match user {
259 Some(user) => {
260 req.extensions_mut().insert(user);
261 next.run(req).await
262 }
263 None if is_navigation(&req) => {
264 let here = req
265 .uri()
266 .path_and_query()
267 .map_or("/", |p| p.as_str())
268 .to_owned();
269 see_other(&format!("/auth/resume?next={}", encode(&here)))
270 }
271 None => (
272 StatusCode::UNAUTHORIZED,
273 [(header::CACHE_CONTROL, "no-store")],
274 "signed out",
275 )
276 .into_response(),
277 }
278}
279
280async fn require_datastar_on_post(req: Request, next: Next) -> Response {
284 if req.method() == Method::POST && !req.headers().contains_key("datastar-request") {
285 return StatusCode::FORBIDDEN.into_response();
286 }
287 next.run(req).await
288}
289
290fn encode(s: &str) -> String {
291 form_urlencoded::byte_serialize(s.as_bytes()).collect()
292}
293
294fn see_other(location: &str) -> Response {
295 (
296 StatusCode::SEE_OTHER,
297 [
298 (header::LOCATION, location),
299 (header::CACHE_CONTROL, "no-store"),
300 ],
301 )
302 .into_response()
303}
304
305fn html(status: StatusCode, body: String) -> Response {
307 let mut resp = (status, body).into_response();
308 let h = resp.headers_mut();
309 h.insert(
310 header::CONTENT_TYPE,
311 HeaderValue::from_static("text/html; charset=utf-8"),
312 );
313 h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
314 h.insert(header::VARY, HeaderValue::from_static("x-koan-partial"));
315 h.insert(
316 header::CONTENT_SECURITY_POLICY,
317 HeaderValue::from_static(PAGE_CSP),
318 );
319 h.insert(
320 header::REFERRER_POLICY,
321 HeaderValue::from_static("same-origin"),
322 );
323 h.insert(
324 header::X_CONTENT_TYPE_OPTIONS,
325 HeaderValue::from_static("nosniff"),
326 );
327 h.insert(
328 "x-robots-tag",
329 HeaderValue::from_static("noindex, nofollow"),
330 );
331 resp
332}
333
334fn patch(html: &str, target: Option<(&str, &str)>) -> Event {
337 let mut lines = Vec::new();
338 if let Some((selector, mode)) = target {
339 lines.push(format!("selector {selector}"));
340 lines.push(format!("mode {mode}"));
341 }
342 lines.extend(html.lines().map(|l| format!("elements {l}")));
343 Event::default()
344 .event("datastar-patch-elements")
345 .data(lines.join("\n"))
346}
347
348fn events(events: Vec<Event>) -> Response {
349 let stream = tokio_stream::iter(events.into_iter().map(Ok::<_, std::convert::Infallible>));
350 let mut resp = Sse::new(stream).into_response();
351 resp.headers_mut()
352 .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
353 resp
354}
355
356fn open(pool: &Pool) -> Option<Handle<'_>> {
357 pool.get()
358 .inspect_err(|e| log::error!("web UI: cannot open the database: {e}"))
359 .ok()
360}
361
362async fn stream(State(s): State<UiState>, Path(id): Path<i64>, headers: HeaderMap) -> Response {
365 let path = blocking(move || {
366 let db = open(&s.pool)?;
367 let t = queries::tracks_by_ids(&db.conn, &[id]).ok()?.pop()?;
368 crate::subsonic::track_file_path(&t).map(PathBuf::from)
369 })
370 .await;
371 let Some(path) = path else {
372 return not_found();
373 };
374 match crate::subsonic::serve_local_file(&path, &headers).await {
375 Ok(mut resp) => {
376 resp.headers_mut().insert(
377 header::CACHE_CONTROL,
378 HeaderValue::from_static("private, max-age=3600"),
379 );
380 resp
381 }
382 Err(_) => not_found(),
383 }
384}
385
386#[derive(serde::Deserialize, Default)]
388#[serde(default)]
389struct CoverQuery {
390 size: Option<u32>,
391 v: Option<String>,
394}
395
396async fn cover(
399 State(s): State<UiState>,
400 Path(id): Path<i64>,
401 axum::extract::Query(q): axum::extract::Query<CoverQuery>,
402) -> Response {
403 let size = crate::covers::snap(q.size);
404 let art = blocking(move || {
405 let tracks = queries::tracks_for_album(&open(&s.pool)?.conn, id).ok()?;
406 s.covers.cover(&tracks, size)
407 })
408 .await;
409 crate::share::jpeg(art, q.v.is_some())
410}