1mod browse;
16mod keys;
17mod pages;
18mod session;
19#[cfg(test)]
20mod tests;
21mod users;
22
23use std::path::PathBuf;
24use std::sync::Arc;
25
26use axum::extract::{Path, Request, State};
27use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
28use axum::middleware::{Next, from_fn, from_fn_with_state};
29use axum::response::sse::{Event, Sse};
30use axum::response::{IntoResponse, Response};
31use axum::routing::{get, post};
32use koan_core::auth;
33use koan_core::db::pool::{Handle, Pool};
34use koan_core::db::queries;
35
36use crate::auth::AuthUser;
37use crate::auth::routes::{AuthRouteState, login_rate_limit};
38use crate::covers::Covers;
39use crate::share::{asset, blocking, not_found};
40
41const PAGE_CSP: &str = "default-src 'none'; script-src 'self' 'unsafe-eval'; style-src 'self'; \
44 img-src 'self'; media-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; \
45 frame-ancestors 'none'";
46
47const PARTIAL: &str = "x-koan-partial";
49
50const UI_CSS: &str = include_str!("../../assets/ui.css");
51const UI_JS: &str = include_str!("../../assets/ui.js");
52const DATASTAR_JS: &str = include_str!("../../assets/datastar.js");
53
54#[derive(Clone)]
55pub struct UiState {
56 pool: Arc<Pool>,
57 covers: Arc<Covers>,
58 options: Arc<std::sync::Mutex<Option<(std::time::Instant, pages::Options)>>>,
60 auth: AuthRouteState,
61 auth_enabled: bool,
62 public_url: Option<String>,
64}
65
66pub fn router(
67 pool: Arc<Pool>,
68 auth: AuthRouteState,
69 auth_enabled: bool,
70 covers: Arc<Covers>,
71 public_url: Option<String>,
72) -> axum::Router {
73 let state = UiState {
74 pool,
75 covers,
76 options: Arc::default(),
77 auth,
78 auth_enabled,
79 public_url,
80 };
81 let gated = axum::Router::new()
82 .route("/", get(pages::albums))
83 .route("/albums", get(pages::albums))
84 .route("/albums/more", get(pages::albums_more))
85 .route("/album/{id}", get(pages::album))
86 .route("/album/{id}/share", post(pages::share_album))
87 .route("/artist/{id}/share", post(pages::share_artist))
88 .route("/artists", get(pages::artists))
89 .route("/artists/more", get(pages::artists_more))
90 .route("/artist/{id}", get(pages::artist))
91 .route("/search", get(pages::search))
92 .route("/search/results", get(pages::search_results))
93 .route("/queue", get(pages::queue))
94 .route("/keys", get(keys::page).post(keys::create))
95 .route("/keys/{id}/revoke", post(keys::revoke))
96 .route("/users", get(users::page).post(users::create))
97 .route("/users/{id}/invite", post(users::invite))
98 .route("/users/{id}/role", post(users::set_role))
99 .route("/users/{id}/delete", post(users::delete))
100 .route("/ui/stream/{id}", get(stream))
101 .route("/ui/cover/{id}", get(cover))
102 .layer(from_fn(require_datastar_on_post))
103 .layer(from_fn_with_state(state.clone(), gate));
104 let sign_in = get(session::login_form).merge(
107 post(session::login).layer(from_fn_with_state(state.auth.clone(), login_rate_limit)),
108 );
109 axum::Router::new()
110 .merge(gated)
111 .route("/login", sign_in)
112 .route("/auth/resume", get(session::resume))
113 .route("/auth/renew", post(session::renew))
114 .route("/auth/signout", post(session::signout))
115 .route("/ui/assets/{name}", get(ui_asset))
116 .with_state(state)
117}
118
119async fn ui_asset(Path(name): Path<String>) -> Response {
120 const JS: &str = "text/javascript; charset=utf-8";
121 match name.as_str() {
122 "ui.css" => asset(UI_CSS, "text/css; charset=utf-8"),
123 "ui.js" => asset(UI_JS, JS),
124 "player.js" => asset(crate::share::ENGINE_JS, JS),
125 "datastar.js" => asset(DATASTAR_JS, JS),
126 other => crate::share::icon(other).unwrap_or_else(not_found),
127 }
128}
129
130fn cookie<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
131 headers
132 .get_all(header::COOKIE)
133 .iter()
134 .filter_map(|v| v.to_str().ok())
135 .flat_map(|v| v.split(';'))
136 .find_map(|c| c.trim().strip_prefix(name)?.strip_prefix('='))
137}
138
139fn is_navigation(req: &Request) -> bool {
143 req.method() == Method::GET
144 && !req.headers().contains_key(PARTIAL)
145 && !req.headers().contains_key("datastar-request")
146 && !req.uri().path().starts_with("/ui/")
147}
148
149async fn gate(State(s): State<UiState>, mut req: Request, next: Next) -> Response {
152 let user = if s.auth_enabled {
153 match cookie(req.headers(), "koan_access")
154 .and_then(|t| auth::validate_access_token(&s.auth.public_pem, t).ok())
155 {
156 Some(claims) => crate::auth::current_user(&s.pool, claims).await,
157 None => None,
158 }
159 } else {
160 Some(AuthUser::anonymous_admin())
161 };
162 match user {
163 Some(user) => {
164 req.extensions_mut().insert(user);
165 next.run(req).await
166 }
167 None if is_navigation(&req) => {
168 let here = req
169 .uri()
170 .path_and_query()
171 .map_or("/", |p| p.as_str())
172 .to_owned();
173 see_other(&format!("/auth/resume?next={}", encode(&here)))
174 }
175 None => (
176 StatusCode::UNAUTHORIZED,
177 [(header::CACHE_CONTROL, "no-store")],
178 "signed out",
179 )
180 .into_response(),
181 }
182}
183
184async fn require_datastar_on_post(req: Request, next: Next) -> Response {
188 if req.method() == Method::POST && !req.headers().contains_key("datastar-request") {
189 return StatusCode::FORBIDDEN.into_response();
190 }
191 next.run(req).await
192}
193
194fn encode(s: &str) -> String {
195 form_urlencoded::byte_serialize(s.as_bytes()).collect()
196}
197
198fn see_other(location: &str) -> Response {
199 (
200 StatusCode::SEE_OTHER,
201 [
202 (header::LOCATION, location),
203 (header::CACHE_CONTROL, "no-store"),
204 ],
205 )
206 .into_response()
207}
208
209fn html(status: StatusCode, body: String) -> Response {
211 let mut resp = (status, body).into_response();
212 let h = resp.headers_mut();
213 h.insert(
214 header::CONTENT_TYPE,
215 HeaderValue::from_static("text/html; charset=utf-8"),
216 );
217 h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
218 h.insert(header::VARY, HeaderValue::from_static("x-koan-partial"));
219 h.insert(
220 header::CONTENT_SECURITY_POLICY,
221 HeaderValue::from_static(PAGE_CSP),
222 );
223 h.insert(
224 header::REFERRER_POLICY,
225 HeaderValue::from_static("same-origin"),
226 );
227 h.insert(
228 header::X_CONTENT_TYPE_OPTIONS,
229 HeaderValue::from_static("nosniff"),
230 );
231 h.insert(
232 "x-robots-tag",
233 HeaderValue::from_static("noindex, nofollow"),
234 );
235 resp
236}
237
238fn patch(html: &str, target: Option<(&str, &str)>) -> Event {
241 let mut lines = Vec::new();
242 if let Some((selector, mode)) = target {
243 lines.push(format!("selector {selector}"));
244 lines.push(format!("mode {mode}"));
245 }
246 lines.extend(html.lines().map(|l| format!("elements {l}")));
247 Event::default()
248 .event("datastar-patch-elements")
249 .data(lines.join("\n"))
250}
251
252fn events(events: Vec<Event>) -> Response {
253 let stream = tokio_stream::iter(events.into_iter().map(Ok::<_, std::convert::Infallible>));
254 let mut resp = Sse::new(stream).into_response();
255 resp.headers_mut()
256 .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
257 resp
258}
259
260fn open(pool: &Pool) -> Option<Handle<'_>> {
261 pool.get()
262 .inspect_err(|e| log::error!("web UI: cannot open the database: {e}"))
263 .ok()
264}
265
266async fn stream(State(s): State<UiState>, Path(id): Path<i64>, headers: HeaderMap) -> Response {
269 let path = blocking(move || {
270 let db = open(&s.pool)?;
271 let t = queries::tracks_by_ids(&db.conn, &[id]).ok()?.pop()?;
272 crate::subsonic::track_file_path(&t).map(PathBuf::from)
273 })
274 .await;
275 let Some(path) = path else {
276 return not_found();
277 };
278 match crate::subsonic::serve_local_file(&path, &headers).await {
279 Ok(mut resp) => {
280 resp.headers_mut().insert(
281 header::CACHE_CONTROL,
282 HeaderValue::from_static("private, max-age=3600"),
283 );
284 resp
285 }
286 Err(_) => not_found(),
287 }
288}
289
290#[derive(serde::Deserialize, Default)]
292#[serde(default)]
293struct CoverQuery {
294 size: Option<u32>,
295 v: Option<String>,
298}
299
300async fn cover(
303 State(s): State<UiState>,
304 Path(id): Path<i64>,
305 axum::extract::Query(q): axum::extract::Query<CoverQuery>,
306) -> Response {
307 let size = crate::covers::snap(q.size);
308 let art = blocking(move || {
309 let tracks = queries::tracks_for_album(&open(&s.pool)?.conn, id).ok()?;
310 s.covers.cover(&tracks, size)
311 })
312 .await;
313 crate::share::jpeg(art, q.v.is_some())
314}