use axum::{ extract::{DefaultBodyLimit, Multipart, Path, Query, State}, http::{header, HeaderMap, HeaderValue, StatusCode, Uri}, response::{Html, IntoResponse, Redirect, Response}, routing::{delete, get, post, put}, Form, Json, Router, }; use axum_login::{AuthUser, AuthnBackend}; use rust_embed::RustEmbed; use serde::{Deserialize, Serialize}; use tower_sessions::Session; use tracing::error; use uuid::Uuid; /// The Leptos SPA bundle produced by `trunk build` in `web-ui/`. /// /// Baked into the binary for release (single-binary deploy); read from disk in /// debug builds so a `trunk build` is picked up without recompiling the server. #[derive(RustEmbed)] #[folder = "web-ui/dist/"] struct WebAssets; use crate::auth::{AuthSession, Credentials, User}; use crate::db::book_store::BookAccess; use crate::kobo::auth::AppState; use crate::upload::handler::{ api_backfill_kepub, api_delete_upload, api_upload, api_upload_check, api_upload_formats, }; /// Session keys holding the in-flight OIDC login secrets between redirect and /// callback. const OIDC_CSRF_KEY: &str = "oidc.csrf"; const OIDC_NONCE_KEY: &str = "oidc.nonce"; const OIDC_PKCE_KEY: &str = "oidc.pkce"; /// JSON representation of a book for the web API. #[derive(Serialize)] struct BookJson { id: i64, uuid: String, title: String, authors: Vec, publisher: Option, language: Option, description: Option, series: Option, series_index: Option, has_cover: bool, formats: Vec, /// `"calibre"` or `"upload"` — the UI shows a delete control for uploads. source: String, /// Whether this book syncs to the requesting user's devices (their /// per-book override, else the book's default). Toggled from the library. sync_enabled: bool, /// RFC 3339 catalog-entry time (upload time, or Calibre add date). Uniform /// format so the web UI can sort by recency with a plain string compare. timestamp: String, /// Override-cover version (0 = none). The UI appends it as `/covers/{id}?v=` /// to bust the browser cache when the cover changes. cover_version: i64, /// Whether the book is soft-deleted (shown only in the UI's "Deleted" view; /// hidden from normal views and from all device syncs). deleted: bool, /// Whether the requesting user uploaded this book. owned: bool, /// Username of the uploader; `None` for the server (Calibre) library. owner: Option, /// Whether the owner opened this upload to every user. Always `true` for /// the server library. shared: bool, /// Whether the requesting user may edit, share, or delete it (own upload, /// server library, or admin). Shared books from other users are read-only. editable: bool, } /// JSON representation of the current user. #[derive(Serialize)] struct UserJson { username: String, is_admin: bool, } /// A user as listed to admins by `GET /api/users`. #[derive(Serialize)] struct AdminUserJson { id: i64, username: String, is_admin: bool, /// Where the account authenticates: `"local"`, `"oidc"`, or `"ldap"`. source: &'static str, } /// Classify an account by its external link. fn user_source(oidc_sub: Option<&str>, ldap_dn: Option<&str>) -> &'static str { match (oidc_sub, ldap_dn) { (Some(_), _) => "oidc", (None, Some(_)) => "ldap", (None, None) => "local", } } /// Body of `POST /api/users` — a new local account. #[derive(Deserialize)] struct CreateUserReq { username: String, password: String, #[serde(default)] is_admin: bool, } /// Body of `PUT /api/users/{id}/admin`. #[derive(Deserialize)] struct UserAdminReq { is_admin: bool, } /// Body of `PUT /api/books/{id}/share`. #[derive(Deserialize)] struct BookShareReq { shared: bool, } /// JSON representation of a Kobo auth token. #[derive(Serialize)] struct TokenJson { id: i64, token: String, /// Token-free base to configure as the device's `api_endpoint`. The device /// presents `token` (JWT-wrapped, as its `KoboAccessToken`) via /// `Authorization: Bearer` when calling it. api_endpoint: String, /// Serial of a device currently bound to this token, if any. The UI shows a /// badge and, on delete, confirms before revoking a device's token. device_serial: Option, } /// Global server settings, exposed to and updated from the Settings page. #[derive(Serialize, Deserialize)] struct SettingsJson { /// Redirect unimplemented Kobo store endpoints to the real store. proxy_unimplemented: bool, /// Newly uploaded books sync to devices by default. sync_new_uploads: bool, } /// Body of `PUT /api/books/{id}/sync` — the desired per-user sync state. #[derive(Deserialize)] struct BookSyncReq { enabled: bool, } /// Body of `PUT /api/books/{id}/meta` — editable book metadata. Every field is /// optional; an omitted or blank value clears that override (the book falls back /// to its Calibre/upload value). #[derive(Deserialize)] struct BookMetaReq { #[serde(default)] title: Option, #[serde(default)] authors: Option>, #[serde(default)] series: Option, #[serde(default)] series_index: Option, #[serde(default)] description: Option, } /// Build the web UI router (mounted at server root). /// /// The browser UI is a Leptos client-side SPA (`web-ui/`), served as static /// assets with a client-routing fallback to `index.html`. Data lives behind the /// `/api/...` and `/covers/...` routes, which enforce auth per-handler and /// return `401` (not a redirect) so the SPA can react; the SPA shell itself is /// public and gates its own content via `/api/me`. Auth POST/OIDC/logout routes /// are the browser's login flow. None of this touches the Kobo `/kobo/...` /// wire contract. pub fn router(max_upload_size: usize) -> Router { let api = Router::new() .route("/api/books", get(api_books)) .route("/api/me", get(api_me)) .route("/api/tokens", get(api_list_tokens)) .route("/api/tokens", post(api_create_token)) .route("/api/register-device", post(api_register_device)) .route("/api/ingest/calibre", post(api_ingest_calibre)) .route("/api/tokens/{token_id}", delete(api_delete_token)) .route( "/api/settings", get(api_get_settings).put(api_update_settings), ) .route("/api/books/{book_id}/sync", put(api_set_book_sync)) .route("/api/books/{book_id}/share", put(api_set_book_shared)) .route("/api/users", get(api_list_users).post(api_create_user)) .route("/api/users/{user_id}", delete(api_delete_user)) .route("/api/users/{user_id}/admin", put(api_set_user_admin)) .route("/api/books/{book_id}", delete(api_soft_delete_book)) .route("/api/books/{book_id}/restore", post(api_restore_book)) .route("/api/books/{book_id}/meta", put(api_set_book_meta)) .route("/api/books/{book_id}/meta/search", get(api_search_meta)) .route("/api/books/{book_id}/cover/search", get(api_search_cover)) // PUT sets the cover from a chosen search-result URL; POST uploads a // custom image file (multipart, so it needs a body limit). .route( "/api/books/{book_id}/cover", put(api_set_cover_url) .post(api_upload_cover) .delete(api_reset_cover) .layer(DefaultBodyLimit::max(20 * 1024 * 1024)), ) .route("/covers/{book_id}", get(cover)) // Upload routes authenticate via the `ApiUser` extractor (browser // session cookie OR `Authorization: Bearer` token) so the Calibre // plugin can post with a token. .route( "/api/upload", post(api_upload).layer(DefaultBodyLimit::max(max_upload_size)), ) // Cheap pre-check so the Calibre plugin can skip already-uploaded books // instead of POSTing each full file only to be 409'd. .route("/api/upload/check", post(api_upload_check)) .route("/api/upload/backfill-kepub", post(api_backfill_kepub)) .route("/api/upload/formats", get(api_upload_formats)) .route("/api/upload/{id}", delete(api_delete_upload)); let public = Router::new() .route("/login", post(login)) .route("/register", post(register)) .route("/api/auth_config", get(api_auth_config)) .route("/auth/oidc/login", get(oidc_login)) .route("/auth/oidc/callback", get(oidc_callback)) .route("/logout", get(logout)); // Everything else (/, /login, /setup, /register, hashed JS/WASM/CSS) is // served from the embedded SPA bundle, falling back to index.html for // client-side routes. api.merge(public).fallback(static_handler) } // ---- Static SPA serving ---- /// Serve an embedded SPA asset, falling back to `index.html` for client routes. async fn static_handler(uri: Uri) -> Response { let path = uri.path().trim_start_matches('/'); let path = if path.is_empty() { "index.html" } else { path }; if let Some(file) = WebAssets::get(path) { return asset_response(path, file.data.into_owned()); } // Unknown path: hand the SPA its shell so client-side routing can render it. match WebAssets::get("index.html") { Some(file) => Html(file.data.into_owned()).into_response(), None => ( StatusCode::SERVICE_UNAVAILABLE, "Web UI not built (run `trunk build` in web-ui/)", ) .into_response(), } } /// Wrap embedded asset bytes in a response with a content type from the path. fn asset_response(path: &str, data: Vec) -> Response { let mime = match path.rsplit('.').next() { Some("html") => "text/html; charset=utf-8", Some("js") => "text/javascript; charset=utf-8", Some("wasm") => "application/wasm", Some("css") => "text/css; charset=utf-8", Some("json") => "application/json", Some("svg") => "image/svg+xml", Some("png") => "image/png", Some("ico") => "image/x-icon", _ => "application/octet-stream", }; let mut headers = HeaderMap::new(); headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(mime)); (headers, data).into_response() } // ---- Protected Handlers ---- /// GET /api/books — Return every book the user may see as JSON. async fn api_books( auth_session: AuthSession, State(state): State, ) -> Result>, (StatusCode, String)> { let user = require_user(auth_session)?; let books = state.books.list_catalog(user.id()).await.map_err(|e| { error!("Failed to fetch books: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; let result = books .into_iter() .map(|b| BookJson { owned: b.owner_user_id == Some(user.id()), // The server library has no owner and is always open to everyone. shared: b.shared || b.owner_user_id.is_none(), editable: user.is_admin || b.owner_user_id.is_none_or(|o| o == user.id()), owner: b.owner, id: b.id, uuid: b.uuid, title: b.title, authors: b.authors, publisher: b.publisher, language: b.language, description: b.description, series: b.series_name, series_index: b.series_index, has_cover: b.has_cover, formats: vec![b.file_format], source: b.source.as_str().to_string(), sync_enabled: b.sync_enabled, timestamp: b.timestamp.to_rfc3339(), cover_version: b.cover_version, deleted: b.deleted, }) .collect(); Ok(Json(result)) } /// GET /api/settings — Return the global server settings. Admin only. async fn api_get_settings( auth_session: AuthSession, State(state): State, ) -> Result, (StatusCode, String)> { require_admin(auth_session)?; let read = |key: &'static str| { let db = state.app_db.clone(); async move { db.get_bool_setting(key, true).await } }; let (proxy_unimplemented, sync_new_uploads) = tokio::try_join!(read("proxy_unimplemented"), read("sync_new_uploads")).map_err(|e| { error!("Failed to read settings: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; Ok(Json(SettingsJson { proxy_unimplemented, sync_new_uploads, })) } /// PUT /api/settings — Persist the global server settings. Admin only. async fn api_update_settings( auth_session: AuthSession, State(state): State, Json(req): Json, ) -> Result { require_admin(auth_session)?; let map_err = |e: error_stack::Report| { error!("Failed to write settings: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) }; state .app_db .set_bool_setting("proxy_unimplemented", req.proxy_unimplemented) .await .map_err(map_err)?; state .app_db .set_bool_setting("sync_new_uploads", req.sync_new_uploads) .await .map_err(map_err)?; Ok(StatusCode::NO_CONTENT) } /// PUT /api/books/{book_id}/sync — Set the requesting user's per-book sync flag. async fn api_set_book_sync( auth_session: AuthSession, State(state): State, Path(book_id): Path, Json(req): Json, ) -> Result { let user = require_user(auth_session)?; ensure_book_visible(&state, user.id(), book_id).await?; state .app_db .set_book_sync_pref(user.id(), book_id, req.enabled) .await .map_err(|e| { error!("Failed to set book sync preference: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; Ok(StatusCode::NO_CONTENT) } /// DELETE /api/books/{book_id} — Soft-delete a book: hide it from the library /// and remove it from every device on next sync, keeping its row and files so it /// can be restored. Global, so limited to users who may edit the book. async fn api_soft_delete_book( auth_session: AuthSession, State(state): State, Path(book_id): Path, ) -> Result { let user = require_user(auth_session)?; ensure_book_writable(&state, user.id(), book_id).await?; state.books.soft_delete_book(book_id).await.map_err(|e| { error!("Failed to soft-delete book: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; Ok(StatusCode::NO_CONTENT) } /// POST /api/books/{book_id}/restore — Undo a soft delete. async fn api_restore_book( auth_session: AuthSession, State(state): State, Path(book_id): Path, ) -> Result { let user = require_user(auth_session)?; ensure_book_writable(&state, user.id(), book_id).await?; state.books.restore_book(book_id).await.map_err(|e| { error!("Failed to restore book: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; Ok(StatusCode::NO_CONTENT) } /// PUT /api/books/{book_id}/meta — Update a book's editable metadata (title, /// authors, series, description). Stored as a per-book override so Calibre /// re-ingest does not clobber it; blank fields clear the override. Reflected in /// the web catalog and on the device at its next sync. async fn api_set_book_meta( auth_session: AuthSession, State(state): State, Path(book_id): Path, Json(req): Json, ) -> Result { let user = require_user(auth_session)?; ensure_book_writable(&state, user.id(), book_id).await?; // Treat blank strings as "no override" so clearing a field reverts to source. let blank = |s: &String| s.trim().is_empty(); let title = req.title.filter(|s| !blank(s)); let series = req.series.filter(|s| !blank(s)); let description = req.description.filter(|s| !blank(s)); // Drop blank author entries; an empty list clears the override. let authors = req.authors.and_then(|list| { let cleaned: Vec = list .into_iter() .map(|a| a.trim().to_string()) .filter(|a| !a.is_empty()) .collect(); (!cleaned.is_empty()) .then(|| serde_json::to_string(&cleaned).unwrap_or_else(|_| "[]".to_string())) }); state .app_db .set_book_meta( book_id, title.as_deref(), authors.as_deref(), series.as_deref(), req.series_index, description.as_deref(), ) .await .map_err(|e| { error!("Failed to set book metadata: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; Ok(StatusCode::NO_CONTENT) } /// GET /api/me — Return the currently logged-in user. async fn api_me(auth_session: AuthSession) -> Result, StatusCode> { let user = auth_session.user.ok_or(StatusCode::UNAUTHORIZED)?; Ok(Json(UserJson { username: user.username, is_admin: user.is_admin, })) } /// GET /covers/{book_id} — Serve a book cover image. async fn cover( auth_session: AuthSession, State(state): State, Path(book_id): Path, ) -> Result { let user = require_user(auth_session)?; let book = state .books .fetch_book_by_id_for(user.id(), book_id) .await .map_err(|e| { error!("Failed to fetch book: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })? .ok_or_else(|| (StatusCode::NOT_FOUND, "Book not found".to_string()))?; let cover_path = state .books .cover_path(&book) .await .map_err(|e| { error!("Failed to resolve cover: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })? .ok_or_else(|| (StatusCode::NOT_FOUND, "Cover not found".to_string()))?; if !cover_path.exists() { return Err((StatusCode::NOT_FOUND, "Cover not found".to_string())); } let content = tokio::fs::read(&cover_path).await.map_err(|e| { error!("Failed to read cover: {e}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; let mut headers = HeaderMap::new(); headers.insert("content-type", HeaderValue::from_static("image/jpeg")); headers.insert( "cache-control", HeaderValue::from_static("public, max-age=86400"), ); Ok((headers, content)) } // ---- Cover editing ---- /// Query params for the cover-search endpoint. #[derive(Deserialize)] struct CoverSearchQuery { #[serde(default)] q: String, } /// A candidate cover returned by the search endpoint. #[derive(Serialize)] struct CoverCandidateJson { thumb_url: String, full_url: String, source: String, #[serde(skip_serializing_if = "Option::is_none")] title: Option, } /// Request body for setting a cover from a chosen search-result URL. #[derive(Deserialize)] struct CoverUrlReq { url: String, } /// A candidate book record returned by the metadata-search endpoint. The UI /// applies a chosen one to the edit form (and its `cover_full_url`, if any). #[derive(Serialize)] struct MetaCandidateJson { #[serde(skip_serializing_if = "Option::is_none")] title: Option, authors: Vec, #[serde(skip_serializing_if = "Option::is_none")] description: Option, #[serde(skip_serializing_if = "Option::is_none")] year: Option, #[serde(skip_serializing_if = "Option::is_none")] cover_thumb_url: Option, #[serde(skip_serializing_if = "Option::is_none")] cover_full_url: Option, source: String, } /// GET /api/books/{book_id}/cover/search?q=… — Search online cover candidates. /// `q` defaults to the book's title when omitted. async fn api_search_cover( auth_session: AuthSession, State(state): State, Path(book_id): Path, Query(params): Query, ) -> Result>, (StatusCode, String)> { let user = require_user(auth_session)?; let book = state .books .fetch_book_by_id_for(user.id(), book_id) .await .map_err(|e| { error!("Failed to fetch book: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })? .ok_or((StatusCode::NOT_FOUND, "Book not found".to_string()))?; let query = if params.q.trim().is_empty() { book.title } else { params.q }; let candidates = crate::upload::cover_search::search_covers(&query) .await .into_iter() .map(|c| CoverCandidateJson { thumb_url: c.thumb_url, full_url: c.full_url, source: c.source.to_string(), title: c.title, }) .collect(); Ok(Json(candidates)) } /// GET /api/books/{book_id}/meta/search?q=… — Search online providers for book /// records to fill the edit form. `q` defaults to the book's title when omitted. async fn api_search_meta( auth_session: AuthSession, State(state): State, Path(book_id): Path, Query(params): Query, ) -> Result>, (StatusCode, String)> { let user = require_user(auth_session)?; let book = state .books .fetch_book_by_id_for(user.id(), book_id) .await .map_err(|e| { error!("Failed to fetch book: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })? .ok_or((StatusCode::NOT_FOUND, "Book not found".to_string()))?; let query = if params.q.trim().is_empty() { book.title } else { params.q }; let candidates = crate::upload::metadata_search::search_metadata(&query) .await .into_iter() .map(|c| MetaCandidateJson { title: c.title, authors: c.authors, description: c.description, year: c.year, cover_thumb_url: c.cover_thumb_url, cover_full_url: c.cover_full_url, source: c.source.to_string(), }) .collect(); Ok(Json(candidates)) } /// PUT /api/books/{book_id}/cover — Set the cover from an allowlisted image URL. async fn api_set_cover_url( auth_session: AuthSession, State(state): State, Path(book_id): Path, Json(req): Json, ) -> Result { let user = require_user(auth_session)?; ensure_book_writable(&state, user.id(), book_id).await?; if !crate::upload::cover_search::is_allowed_cover_url(&req.url) { return Err(( StatusCode::BAD_REQUEST, "Cover URL host not allowed".to_string(), )); } let raw = crate::upload::enrich::fetch_cover(&req.url).await.ok_or(( StatusCode::BAD_GATEWAY, "Failed to download cover".to_string(), ))?; store_override_cover(&state, book_id, raw).await } /// POST /api/books/{book_id}/cover — Set the cover from an uploaded image file /// (`multipart/form-data`, single `file` field). async fn api_upload_cover( auth_session: AuthSession, State(state): State, Path(book_id): Path, mut multipart: Multipart, ) -> Result { let user = require_user(auth_session)?; ensure_book_writable(&state, user.id(), book_id).await?; let mut bytes: Option> = None; while let Some(field) = multipart .next_field() .await .map_err(|e| (StatusCode::BAD_REQUEST, format!("Malformed upload: {e}")))? { let is_file = field.name() == Some("file") || field.file_name().is_some(); if bytes.is_some() || !is_file { continue; } let data = field.bytes().await.map_err(|e| { ( StatusCode::BAD_REQUEST, format!("Failed to read image: {e}"), ) })?; bytes = Some(data.to_vec()); } let raw = bytes.ok_or((StatusCode::BAD_REQUEST, "No image uploaded".to_string()))?; store_override_cover(&state, book_id, raw).await } /// DELETE /api/books/{book_id}/cover — Remove the override cover so the book /// reverts to its source (Calibre / upload) cover, on both the web and the /// device. Removes the override file and clears the cover record. Idempotent. async fn api_reset_cover( auth_session: AuthSession, State(state): State, Path(book_id): Path, ) -> Result { let user = require_user(auth_session)?; ensure_book_writable(&state, user.id(), book_id).await?; let path = state.books.cover_override_path(book_id); if let Err(e) = tokio::fs::remove_file(&path).await { if e.kind() != std::io::ErrorKind::NotFound { error!("Failed to remove override cover for {book_id}: {e}"); } } state.app_db.remove_book_cover(book_id).await.map_err(|e| { error!("Failed to reset cover: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; Ok(StatusCode::NO_CONTENT) } /// PUT /api/books/{book_id}/share — Open one of the user's uploads to every /// user, or make it private again. Admins can share any upload. The server /// (Calibre) library is always shared, so it refuses with `409`. async fn api_set_book_shared( auth_session: AuthSession, State(state): State, Path(book_id): Path, Json(req): Json, ) -> Result { let user = require_user(auth_session)?; ensure_book_writable(&state, user.id(), book_id).await?; let updated = state .books .set_shared(book_id, req.shared) .await .map_err(|e| { error!("Failed to set shared flag: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; updated.then_some(StatusCode::NO_CONTENT).ok_or(( StatusCode::CONFLICT, "Only uploaded books can be shared; the server library is visible to everyone".to_string(), )) } // ---- Access helpers ---- /// 401 unless logged in. fn require_user(auth_session: AuthSession) -> Result { auth_session .user .ok_or((StatusCode::UNAUTHORIZED, "Not logged in".to_string())) } /// 401 unless logged in; 403 unless an admin. fn require_admin(auth_session: AuthSession) -> Result { let user = require_user(auth_session)?; user.is_admin .then_some(user) .ok_or((StatusCode::FORBIDDEN, "Admin access required".to_string())) } /// 404 unless `book_id` exists and `user_id` may see it (an invisible book is /// reported exactly like a missing one, so private libraries leak nothing). async fn ensure_book_visible( state: &AppState, user_id: i64, book_id: i64, ) -> Result { state .books .book_access(user_id, book_id) .await .map_err(|e| { error!("Failed to resolve book access: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })? .filter(|a| a.visible()) .ok_or((StatusCode::NOT_FOUND, "Book not found".to_string())) } /// 404 unless visible; 403 unless `user_id` may edit, share, or delete it. async fn ensure_book_writable( state: &AppState, user_id: i64, book_id: i64, ) -> Result<(), (StatusCode, String)> { let access = ensure_book_visible(state, user_id, book_id).await?; access.writable().then_some(()).ok_or(( StatusCode::FORBIDDEN, "You can only edit your own books".to_string(), )) } /// Transcode `raw` to JPEG, write it as the book's override cover, and record the /// version bump (busts browser + device caches). Returns `204` on success. async fn store_override_cover( state: &AppState, book_id: i64, raw: Vec, ) -> Result { let jpeg = tokio::task::spawn_blocking(move || crate::upload::cover::to_jpeg(&raw)) .await .map_err(|e| { error!("cover transcode task panicked: {e}"); ( StatusCode::INTERNAL_SERVER_ERROR, "Failed to process image".to_string(), ) })? .ok_or((StatusCode::BAD_REQUEST, "Not a valid image".to_string()))?; let path = state.books.cover_override_path(book_id); if let Some(parent) = path.parent() { tokio::fs::create_dir_all(parent).await.map_err(|e| { error!("Failed to create cover dir: {e}"); ( StatusCode::INTERNAL_SERVER_ERROR, "Failed to store cover".to_string(), ) })?; } tokio::fs::write(&path, &jpeg).await.map_err(|e| { error!("Failed to write cover: {e}"); ( StatusCode::INTERNAL_SERVER_ERROR, "Failed to store cover".to_string(), ) })?; state.app_db.set_book_cover(book_id).await.map_err(|e| { error!("Failed to record cover: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; Ok(StatusCode::NO_CONTENT) } // ---- Token Management Handlers ---- /// GET /api/tokens — List all Kobo auth tokens for the logged-in user. async fn api_list_tokens( auth_session: AuthSession, State(state): State, ) -> Result>, (StatusCode, String)> { let user = auth_session .user .ok_or((StatusCode::UNAUTHORIZED, "Not logged in".to_string()))?; let base_url = state.config.external_url(); let tokens = state .app_db .list_auth_tokens(user.id()) .await .map_err(|e| { error!("Failed to list tokens: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; let result = tokens .into_iter() .map(|t| TokenJson { id: t.id, api_endpoint: format!("{base_url}/kobo"), token: t.auth_token, device_serial: t.device_serial, }) .collect(); Ok(Json(result)) } /// POST /api/tokens — Generate a new Kobo auth token for the logged-in user. async fn api_create_token( auth_session: AuthSession, State(state): State, ) -> Result, (StatusCode, String)> { let user = auth_session .user .ok_or((StatusCode::UNAUTHORIZED, "Not logged in".to_string()))?; let token = Uuid::new_v4().to_string(); let base_url = state.config.external_url(); let id = state .app_db .create_auth_token(user.id(), &token) .await .map_err(|e| { error!("Failed to create token: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; Ok(Json(TokenJson { id, api_endpoint: format!("{base_url}/kobo"), token, // A freshly minted token is not yet bound to any device. device_serial: None, })) } /// Request body for `POST /api/register-device`. #[derive(Deserialize)] struct RegisterDeviceReq { token: String, } /// POST /api/register-device — Mark a token as awaiting a device, so the next /// `device_auth` (which carries the serial but no Bearer) binds that device's /// serial to this token. Called by the setup page after writing the device. async fn api_register_device( auth_session: AuthSession, State(state): State, Json(req): Json, ) -> Result { let user = auth_session .user .ok_or((StatusCode::UNAUTHORIZED, "Not logged in".to_string()))?; state .app_db .add_pending_registration(user.id(), &req.token) .await .map_err(|e| { error!("Failed to register device: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; Ok(StatusCode::NO_CONTENT) } /// POST /api/ingest/calibre — Re-ingest the configured Calibre library into /// the catalog on demand. Returns the number of books ingested. Admin only. async fn api_ingest_calibre( auth_session: AuthSession, State(state): State, ) -> Result, (StatusCode, String)> { require_admin(auth_session)?; let Some(library_path) = state.config.calibre_library_path.clone() else { return Err(( StatusCode::CONFLICT, "No Calibre library configured".to_string(), )); }; let calibre_db = crate::db::calibre_db::CalibreDb::connect(&library_path.join("metadata.db")) .await .map_err(|e| { error!("Failed to connect to Calibre DB: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; let count = crate::ingest::calibre::CalibreIngest::new(&calibre_db, &state.books, &library_path) .run() .await .map_err(|e| { error!("Calibre ingest failed: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; Ok(Json(serde_json::json!({ "ingested": count }))) } /// Query parameters for `DELETE /api/tokens/{token_id}`. #[derive(Deserialize)] struct DeleteTokenParams { /// Proceed even when the token is bound to a device. #[serde(default)] force: bool, } /// DELETE /api/tokens/{token_id} — Delete a specific Kobo auth token. /// /// Deleting a token a Kobo device is actively syncing with breaks that device /// (its Bearer stops resolving, so `/v1/initialization` falls back to Kobo and /// covers/annotations break). So when the token is bound in /// `device_registrations` and `?force=true` is not set, this returns `409` with /// the bound serial instead of deleting — a confirmation, not a hard denial, so /// a lost or stolen device's token can still be revoked with `force`. async fn api_delete_token( auth_session: AuthSession, State(state): State, Path(token_id): Path, Query(params): Query, ) -> Result { let user = auth_session .user .ok_or((StatusCode::UNAUTHORIZED, "Not logged in".to_string()))?; if !params.force { let bound = state .app_db .token_device_serial(token_id, user.id()) .await .map_err(|e| { error!("Failed to check token binding: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; if let Some(serial) = bound { return Ok(( StatusCode::CONFLICT, Json(serde_json::json!({ "device_serial": serial })), ) .into_response()); } } let deleted = state .app_db .delete_auth_token_by_id(token_id, user.id()) .await .map_err(|e| { error!("Failed to delete token: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; if deleted { Ok(StatusCode::NO_CONTENT.into_response()) } else { Err((StatusCode::NOT_FOUND, "Token not found".to_string())) } } // ---- User Management (admin) ---- /// GET /api/users — List every account. Admin only. async fn api_list_users( auth_session: AuthSession, State(state): State, ) -> Result>, (StatusCode, String)> { require_admin(auth_session)?; let users = state.app_db.list_users().await.map_err(|e| { error!("Failed to list users: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; Ok(Json( users .into_iter() .map(|u| AdminUserJson { id: u.id, username: u.username, is_admin: u.is_admin, source: user_source(u.oidc_sub.as_deref(), u.ldap_dn.as_deref()), }) .collect(), )) } /// POST /api/users — Create a local account, optionally as an admin. Admin only. async fn api_create_user( auth_session: AuthSession, State(state): State, Json(req): Json, ) -> Result<(StatusCode, Json), (StatusCode, String)> { require_admin(auth_session)?; let username = req.username.trim().to_string(); if username.is_empty() { return Err((StatusCode::BAD_REQUEST, "Username is required".to_string())); } if req.password.len() < 8 { return Err(( StatusCode::BAD_REQUEST, "Password must be at least 8 characters".to_string(), )); } let taken = state .app_db .find_user_by_username(&username) .await .map_err(|e| { error!("Failed to check username: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })? .is_some(); if taken { return Err((StatusCode::CONFLICT, "Username already taken".to_string())); } let password_hash = password_auth::generate_hash(&req.password); let id = state .app_db .create_user(&username, &password_hash, req.is_admin) .await .map_err(|e| { error!("Failed to create user: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; Ok(( StatusCode::CREATED, Json(AdminUserJson { id, username, is_admin: req.is_admin, source: "local", }), )) } /// PUT /api/users/{user_id}/admin — Grant or revoke the admin role. Admin only. /// Revoking the last admin is refused with `409`. async fn api_set_user_admin( auth_session: AuthSession, State(state): State, Path(user_id): Path, Json(req): Json, ) -> Result { require_admin(auth_session)?; ensure_user_exists(&state, user_id).await?; let updated = state .app_db .set_user_admin(user_id, req.is_admin) .await .map_err(|e| { error!("Failed to set admin role: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; updated.then_some(StatusCode::NO_CONTENT).ok_or(( StatusCode::CONFLICT, "Cannot remove the last admin".to_string(), )) } /// DELETE /api/users/{user_id} — Delete an account with all its devices, /// reading state, and uploaded books (files included). Admin only; an admin /// cannot delete their own account, and the last admin cannot be deleted. async fn api_delete_user( auth_session: AuthSession, State(state): State, Path(user_id): Path, ) -> Result { let admin = require_admin(auth_session)?; if admin.id() == user_id { return Err(( StatusCode::BAD_REQUEST, "You cannot delete your own account".to_string(), )); } ensure_user_exists(&state, user_id).await?; let locators = state .app_db .delete_user(user_id) .await .map_err(|e| { error!("Failed to delete user: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })? .ok_or(( StatusCode::CONFLICT, "Cannot delete the last admin".to_string(), ))?; // The rows are gone; the files are best-effort cleanup. for locator in locators { let dir = state.config.upload_dir.join(&locator); if let Err(e) = tokio::fs::remove_dir_all(&dir).await { error!("Failed to remove upload files {}: {e}", dir.display()); } } Ok(StatusCode::NO_CONTENT) } /// 404 unless a user with `user_id` exists. async fn ensure_user_exists(state: &AppState, user_id: i64) -> Result<(), (StatusCode, String)> { state .app_db .find_user_by_id(user_id) .await .map_err(|e| { error!("Failed to fetch user: {e:?}"); (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })? .map(|_| ()) .ok_or((StatusCode::NOT_FOUND, "User not found".to_string())) } // ---- Public Handlers (Login / Logout) ---- /// POST /login — Authenticate the user with a username and password: a local /// account, else the LDAP directory when one is configured. async fn login( mut auth_session: AuthSession, State(state): State, Form(creds): Form, ) -> impl IntoResponse { // Password login can be disabled for SSO-only deployments. if !state.password_login() { return Redirect::to("/login").into_response(); } let user = match auth_session.authenticate(creds).await { Ok(Some(user)) => user, Ok(None) => return Redirect::to("/login?error=1").into_response(), Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), }; match auth_session.login(&user).await { Ok(_) => Redirect::to("/").into_response(), Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), } } /// GET /api/auth_config — Public flags the login page uses to decide which /// login methods to render. async fn api_auth_config(State(state): State) -> impl IntoResponse { Json(serde_json::json!({ "oidc_enabled": state.oidc.is_some(), // Show the username/password form: local accounts and/or LDAP. "local_login": state.password_login(), "ldap_enabled": state.ldap.is_some(), // Registration is a local-account feature; meaningless without it. "registration_enabled": state.config.allow_registration && state.local_login, })) } /// GET /auth/oidc/login — Begin an OIDC Authorization Code (+PKCE) login by /// redirecting the browser to the IdP. Returns 404 when OIDC is not configured. async fn oidc_login(State(state): State, session: Session) -> impl IntoResponse { let Some(oidc) = state.oidc.clone() else { return (StatusCode::NOT_FOUND, "OIDC login is not enabled").into_response(); }; let auth = match oidc.authorize().await { Ok(auth) => auth, Err(e) => { error!("OIDC authorize failed: {e:?}"); return Redirect::to("/login?error=oidc").into_response(); } }; // Persist the CSRF state, nonce, and PKCE verifier for the callback to check. let stash = async { session.insert(OIDC_CSRF_KEY, &auth.csrf_state).await?; session.insert(OIDC_NONCE_KEY, &auth.nonce).await?; session.insert(OIDC_PKCE_KEY, &auth.pkce_verifier).await }; if let Err(e) = stash.await { error!("Failed to stash OIDC login state: {e:?}"); return Redirect::to("/login?error=oidc").into_response(); } Redirect::to(&auth.authorize_url).into_response() } /// Query parameters returned by the IdP to the OIDC callback. #[derive(Deserialize)] struct OidcCallback { code: Option, state: Option, error: Option, } /// GET /auth/oidc/callback — Complete the OIDC login: verify CSRF state, exchange /// the code, validate the ID token, provision/link the user, and start a session. async fn oidc_callback( mut auth_session: AuthSession, State(state): State, session: Session, Query(params): Query, ) -> impl IntoResponse { let Some(oidc) = state.oidc.clone() else { return Redirect::to("/login").into_response(); }; if let Some(err) = params.error { error!("OIDC provider returned error: {err}"); return Redirect::to("/login?error=oidc").into_response(); } let (Some(code), Some(returned_state)) = (params.code, params.state) else { return Redirect::to("/login?error=oidc").into_response(); }; // Pull and clear the one-time login secrets. let csrf: Option = session.remove(OIDC_CSRF_KEY).await.ok().flatten(); let nonce: Option = session.remove(OIDC_NONCE_KEY).await.ok().flatten(); let pkce: Option = session.remove(OIDC_PKCE_KEY).await.ok().flatten(); let (Some(csrf), Some(nonce), Some(pkce)) = (csrf, nonce, pkce) else { error!("OIDC callback without a matching login session"); return Redirect::to("/login?error=oidc").into_response(); }; if returned_state != csrf { error!("OIDC CSRF state mismatch"); return Redirect::to("/login?error=oidc").into_response(); } let identity = match oidc.exchange(code, pkce, nonce).await { Ok(identity) => identity, Err(e) => { error!("OIDC token exchange failed: {e:?}"); return Redirect::to("/login?error=oidc").into_response(); } }; let user_id = match oidc.provision(&state.app_db, &identity).await { Ok(user_id) => user_id, Err(e) => { error!("OIDC user provisioning failed: {e:?}"); return Redirect::to("/login?error=oidc").into_response(); } }; // Establish the session through the auth backend. let user = match auth_session.backend.get_user(&user_id).await { Ok(Some(user)) => user, _ => { error!("OIDC user {user_id} missing after provisioning"); return Redirect::to("/login?error=oidc").into_response(); } }; match auth_session.login(&user).await { Ok(_) => Redirect::to("/").into_response(), Err(e) => { error!("OIDC session login failed: {e:?}"); Redirect::to("/login?error=oidc").into_response() } } } /// POST /register — Create a new web user, then log them in. async fn register( mut auth_session: AuthSession, State(state): State, Form(creds): Form, ) -> impl IntoResponse { if !state.local_login || !state.config.allow_registration { return Redirect::to("/login").into_response(); } if creds.password.len() < 8 { return Redirect::to("/register?error=short").into_response(); } let existing = match state.app_db.find_user_by_username(&creds.username).await { Ok(user) => user, Err(e) => { error!("Failed to check username: {e:?}"); return StatusCode::INTERNAL_SERVER_ERROR.into_response(); } }; if existing.is_some() { return Redirect::to("/register?error=taken").into_response(); } let password_hash = password_auth::generate_hash(&creds.password); if let Err(e) = state .app_db .create_user(&creds.username, &password_hash, false) .await { error!("Failed to create user: {e:?}"); return Redirect::to("/register?error=1").into_response(); } // Log the new user straight in. let user = match auth_session.authenticate(creds).await { Ok(Some(user)) => user, _ => return Redirect::to("/login").into_response(), }; match auth_session.login(&user).await { Ok(_) => Redirect::to("/").into_response(), Err(_) => Redirect::to("/login").into_response(), } } /// GET /logout — Log the user out and redirect to login. async fn logout(mut auth_session: AuthSession) -> impl IntoResponse { match auth_session.logout().await { Ok(_) => Redirect::to("/login"), Err(_) => Redirect::to("/login"), } }