Something went wrong. Try again.
A self-hosted custom sync server for kobo devices.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337use std::sync::Arc;
use axum::extract::Request;use axum::ServiceExt;use axum_listener::DualListener;use axum_login::AuthManagerLayerBuilder;use clap::Parser;use time::Duration;use tower::Layer;use tower_http::trace::TraceLayer;use tower_sessions::session_store::ExpiredDeletion as _;use tower_sessions::{Expiry, SessionManagerLayer};use tracing::{info, warn};use tracing_subscriber::EnvFilter;
use kobo_shelf::auth::Backend;use kobo_shelf::config::AppConfig;use kobo_shelf::db::app_db::AppDb;use kobo_shelf::db::book_store::BookStore;use kobo_shelf::db::calibre_db::CalibreDb;use kobo_shelf::ingest::calibre::CalibreIngest;use kobo_shelf::kobo::auth::AppState;use kobo_shelf::kobo::router::KoboRouter;use kobo_shelf::kobo::sync_point::gc_old_sync_points;use kobo_shelf::ldap::{LdapConfig, LdapProvider};use kobo_shelf::oidc::{OidcConfig, OidcProvider};use kobo_shelf::session_store::SqliteSessionStore;use kobo_shelf::web;
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { // Load .env (if present) before reading any config or env filters. // Existing environment variables take precedence over .env entries. let dotenv_path = dotenvy::dotenv().ok();
// Load config.toml (if present) and seed env vars it defines, without // overriding real env / .env. Done before tracing init so a `log` key can // set RUST_LOG. Precedence: CLI > env / .env > config.toml > defaults. let config_path = kobo_shelf::config::FileConfig::resolve_path(); let file_config = kobo_shelf::config::FileConfig::load(&config_path) .map_err(|e| format!("Failed to load config file: {e}"))?; if let Some(fc) = &file_config { fc.apply_to_env(); }
// Initialize tracing tracing_subscriber::fmt() .with_env_filter( EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")), ) .init();
if let Some(path) = &dotenv_path { info!(path = %path.display(), "Loaded environment from .env"); }
if file_config.is_some() { info!(path = %config_path.display(), "Loaded configuration from config.toml"); }
// Parse CLI arguments (falls back to env vars, then defaults) let config = AppConfig::parse();
info!( socket = ?config.socket, calibre_library = ?config.calibre_library_path, app_db = %config.app_db_path.display(), external_url = %config.external_url(), "Starting kobo-shelf" );
// Connect to the app database (the single source of truth for books). let app_db = AppDb::connect(&config.app_db_path) .await .map_err(|e| format!("Failed to connect to app DB: {e}"))?;
// Bootstrap the initial admin user from the environment, if configured. seed_admin_user(&app_db).await?;
// Resolve OIDC configuration (client secret from env/_FILE, kept out of // AppConfig which is logged). Refuse to start with no usable login method. let oidc = build_oidc_provider(&config)?; let ldap = build_ldap_provider(&config)?; if !config.local_login && oidc.is_none() && ldap.is_none() { return Err( "No login method enabled: set KOBO_SHELF_LOCAL_LOGIN=true, configure OIDC \ (KOBO_SHELF_OIDC_ISSUER, KOBO_SHELF_OIDC_CLIENT_ID, KOBO_SHELF_OIDC_CLIENT_SECRET), \ or configure LDAP (KOBO_SHELF_LDAP_URL, KOBO_SHELF_LDAP_USER_BASE_DN)" .into(), ); }
// Build the unified book catalog over the app DB pool. tokio::fs::create_dir_all(&config.upload_dir) .await .map_err(|e| format!("Failed to create upload dir: {e}"))?; let book_store = BookStore::new( app_db.pool().clone(), config.calibre_library_path.clone(), config.upload_dir.clone(), );
// Ingest the Calibre library into the catalog before serving, when a // library is configured and ingest is enabled. match (config.calibre_ingest, &config.calibre_library_path) { (true, Some(library_path)) => { let calibre_db = CalibreDb::connect(&library_path.join("metadata.db")) .await .map_err(|e| format!("Failed to connect to Calibre DB: {e}"))?; CalibreIngest::new(&calibre_db, &book_store, library_path) .run() .await .map_err(|e| format!("Calibre ingest failed: {e}"))?; } (false, Some(_)) => info!("Calibre ingest disabled; skipping"), (_, None) => info!("No Calibre library configured; serving uploads only"), }
// Build session layer (SQLite-backed, shares the app DB pool) let session_store = SqliteSessionStore::new(app_db.pool().clone()); session_store.migrate().await?;
// Periodically purge expired web sessions from the store. { let store = session_store.clone(); tokio::spawn(async move { let mut interval = tokio::time::interval(std::time::Duration::from_secs(3600)); interval.tick().await; // immediate first tick — skip loop { interval.tick().await; if let Err(e) = store.delete_expired().await { tracing::warn!("Session GC failed: {e}"); } } }); }
let session_layer = SessionManagerLayer::new(session_store) .with_secure(false) .with_expiry(Expiry::OnInactivity(Duration::days(7)));
// Wrap app_db in Arc for sharing between AppState and auth Backend let app_db = Arc::new(app_db);
// Build auth layer let backend = Backend::new(Arc::clone(&app_db), ldap.clone(), config.local_login); let auth_layer = AuthManagerLayerBuilder::new(backend, session_layer).build();
// Spawn periodic GC: drop sync-point snapshots older than 30 days. { let gc_db = Arc::clone(&app_db); tokio::spawn(async move { let mut interval = tokio::time::interval(std::time::Duration::from_secs(3600)); interval.tick().await; // immediate first tick — skip loop { interval.tick().await; if let Err(e) = gc_old_sync_points(&gc_db, 30).await { tracing::warn!("Sync-point GC failed: {e:?}"); } } }); }
// Build application state and router let state = AppState::from_arcs( Arc::new(book_store), app_db, Arc::new(config.clone()), oidc, ldap, );
// Kobo routes do NOT use session auth: the device authenticates with its // `Authorization: Bearer` token (rewritten into the path by the middleware // below). Web routes use session auth. let routed = KoboRouter::build(state.clone()) .merge(web::router(config.max_upload_size).with_state(state)) .layer(auth_layer) .layer(TraceLayer::new_for_http());
// Error-status logging wraps the routed app so it sees the final status of // every request (Kobo + web). let logged = axum::middleware::from_fn(kobo_shelf::kobo::token_header::log_error_responses) .layer(routed);
// Bearer-token rewrite must run BEFORE routing, so wrap from the outside — // `Router::layer` runs after `matchit`, too late to change which route a // token-free `/kobo/...` request matches. let app = axum::middleware::from_fn(kobo_shelf::kobo::token_header::inject_bearer_token) .layer(logged);
// Bind listener (TCP or Unix domain socket) let listener = DualListener::bind(&config.socket).await?; info!(socket = ?config.socket, "Server listening");
axum::serve(listener, ServiceExt::<Request>::into_make_service(app)).await?;
Ok(())}
/// Create the initial admin user from the environment when the database has no/// users yet. Credentials come from `KOBO_SHELF_ADMIN_ACCOUNT` and/// `KOBO_SHELF_ADMIN_PASSWORD` (or their `*_FILE` counterparts, which read the value/// from a file for Docker/systemd secrets). No default account is ever created:/// on a fresh database with no credentials configured, no user is seeded and/// login is impossible until they are provided.async fn seed_admin_user(app_db: &AppDb) -> Result<(), Box<dyn std::error::Error>> { let has_users = app_db .has_users() .await .map_err(|e| format!("Failed to check users: {e}"))?; if has_users { return Ok(()); }
match ( env_or_file("KOBO_SHELF_ADMIN_ACCOUNT"), env_or_file("KOBO_SHELF_ADMIN_PASSWORD"), ) { (Some(username), Some(password)) => { let password_hash = password_auth::generate_hash(&password); app_db .create_user(&username, &password_hash, true) .await .map_err(|e| format!("Failed to create admin user: {e}"))?; info!(username = %username, "Created initial admin user from environment"); } _ => { warn!( "No users exist and no admin credentials are configured. Set \ KOBO_SHELF_ADMIN_ACCOUNT and KOBO_SHELF_ADMIN_PASSWORD (or their *_FILE \ variants) to bootstrap the first account." ); } }
Ok(())}
/// Build the OIDC provider when issuer + client id + client secret are all/// configured. The secret is resolved from `KOBO_SHELF_OIDC_CLIENT_SECRET` (or its/// `_FILE` variant). The redirect URL is derived from the external URL. Partial/// configuration is ignored with a warning; a fully-absent config yields `None`.fn build_oidc_provider( config: &AppConfig,) -> Result<Option<Arc<OidcProvider>>, Box<dyn std::error::Error>> { let secret = env_or_file("KOBO_SHELF_OIDC_CLIENT_SECRET"); match (&config.oidc_issuer_url, &config.oidc_client_id, secret) { (Some(issuer), Some(client_id), Some(secret)) => { let redirect = format!( "{}/auth/oidc/callback", config.external_url().trim_end_matches('/') ); let provider = OidcProvider::new( OidcConfig { issuer_url: issuer.clone(), client_id: client_id.clone(), redirect_url: redirect.clone(), scopes: config.oidc_scopes.clone(), username_claim: config.oidc_username_claim.clone(), groups_claim: config.oidc_groups_claim.clone(), admin_group: config.oidc_admin_group.clone(), }, &secret, ) .map_err(|e| format!("Failed to configure OIDC: {e:?}"))?; info!( issuer = %issuer, redirect = %redirect, admin_group = ?config.oidc_admin_group, "OIDC login enabled" ); Ok(Some(Arc::new(provider))) } (None, None, None) => Ok(None), _ => { warn!( "Partial OIDC configuration ignored; set KOBO_SHELF_OIDC_ISSUER, \ KOBO_SHELF_OIDC_CLIENT_ID and KOBO_SHELF_OIDC_CLIENT_SECRET together to enable SSO" ); Ok(None) } }}
/// Build the LDAP provider when a directory URL is configured. The service/// account password is resolved from `KOBO_SHELF_LDAP_BIND_PASSWORD` (or its/// `_FILE` variant). An absent URL yields `None`.fn build_ldap_provider( config: &AppConfig,) -> Result<Option<Arc<LdapProvider>>, Box<dyn std::error::Error>> { let Some(url) = config.ldap_url.clone().filter(|u| !u.trim().is_empty()) else { return Ok(None); }; let ldap_config = LdapConfig { url, starttls: config.ldap_starttls, insecure_tls: config.ldap_insecure_tls, bind_dn: config.ldap_bind_dn.clone().filter(|s| !s.is_empty()), user_base_dn: config.ldap_user_base_dn.clone(), user_filter: config.ldap_user_filter.clone(), user_dn_template: config .ldap_user_dn_template .clone() .filter(|s| !s.is_empty()), username_attr: config.ldap_username_attr.clone(), admin_group_dn: config.ldap_admin_group_dn.clone().filter(|s| !s.is_empty()), timeout: std::time::Duration::from_secs(config.ldap_timeout_secs), }; let provider = LdapProvider::new(ldap_config, env_or_file("KOBO_SHELF_LDAP_BIND_PASSWORD")) .map_err(|e| format!("Failed to configure LDAP: {e:?}"))?; info!( url = %provider.url(), admin_group = ?config.ldap_admin_group_dn, "LDAP login enabled" ); Ok(Some(Arc::new(provider)))}
/// Resolve a secret from `$NAME`, falling back to the contents of the file named/// by `$NAME_FILE`. Empty values count as unset; file contents are trimmed.fn env_or_file(name: &str) -> Option<String> { if let Some(v) = std::env::var(name).ok().filter(|s| !s.is_empty()) { return Some(v); } let path = std::env::var(format!("{name}_FILE")) .ok() .filter(|s| !s.is_empty())?; match std::fs::read_to_string(&path) { Ok(contents) => Some(contents.trim().to_string()).filter(|s| !s.is_empty()), Err(e) => { warn!(path = %path, "Failed to read {name}_FILE: {e}"); None } }}