//! im — the Dizey SSO. Server by default; the CLI covers bootstrapping //! (the first admin invite) and the two admin actions that must work even //! when the panel cannot be reached. Everything else lives in /admin. use std::sync::Arc; use im_core::store::Store; use topcoat::Result; use topcoat::asset::RouterBuilderAssetExt; use topcoat::cookie::RouterBuilderCookieExt; use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, route}; mod admin; mod auth; mod config; mod directory; mod dropdown; mod health; mod i18n; mod layout; mod live; mod mailer; mod oidc; mod pack; mod pages; mod people; mod photo; mod server; use config::Config; #[route(GET "/healthz")] async fn healthz() -> Result<&'static str> { // The build's commit, baked by build.rs — the deploy asserts the exact // body after the restart, so a stale process holding the port cannot // pass for this one. Ok(concat!("ok ", env!("IM_BUILD_SHA"))) } #[tokio::main] async fn main() { let args: Vec = std::env::args().collect(); let config = match Config::load() { Ok(config) => config, Err(problem) => { eprintln!("im: {problem}"); std::process::exit(2); } }; match args.get(1).map(String::as_str) { None => serve(config).await, Some("invite") => { let mut email = None; let mut admin = false; for arg in &args[2..] { match arg.as_str() { "--admin" => admin = true, other if email.is_none() => email = Some(other.to_string()), other => { eprintln!("usage: im-web invite [--admin]"); eprintln!("im: unexpected argument {other}"); std::process::exit(2); } } } let Some(email) = email else { eprintln!("usage: im-web invite [--admin]"); std::process::exit(2); }; invite(config, &email, admin).await; } Some("revoke") => { let Some(email) = args.get(2) else { eprintln!("usage: im-web revoke "); std::process::exit(2); }; revoke(config, email).await; } Some("create-client") => { let (Some(name), uris) = (args.get(2), args.get(3..).unwrap_or(&[])) else { eprintln!("usage: im-web create-client [more-uris...]"); std::process::exit(2); }; if uris.is_empty() { eprintln!("usage: im-web create-client [more-uris...]"); std::process::exit(2); } create_client(config, name, uris).await; } Some("promote") => { let Some(email) = args.get(2) else { eprintln!("usage: im-web promote "); std::process::exit(2); }; set_admin_cli(config, email, true).await; } Some("demote") => { let Some(email) = args.get(2) else { eprintln!("usage: im-web demote "); std::process::exit(2); }; set_admin_cli(config, email, false).await; } Some("rotate-client") => { let Some(id) = args.get(2) else { eprintln!("usage: im-web rotate-client "); std::process::exit(2); }; rotate_client(config, id).await; } Some("revoke-client") => { let Some(id) = args.get(2) else { eprintln!("usage: im-web revoke-client "); std::process::exit(2); }; revoke_client(config, id).await; } Some("pack") => { let mut root = None; let mut out = None; let mut rest = args[2..].iter(); while let Some(arg) = rest.next() { match arg.as_str() { "--root" => match rest.next() { Some(value) => root = Some(value.clone()), None => { eprintln!("usage: im-web pack [--root DIR] [--out FILE]"); eprintln!("im: --root needs a directory"); std::process::exit(2); } }, "--out" => match rest.next() { Some(value) => out = Some(value.clone()), None => { eprintln!("usage: im-web pack [--root DIR] [--out FILE]"); eprintln!("im: --out needs a file"); std::process::exit(2); } }, other => { eprintln!("usage: im-web pack [--root DIR] [--out FILE]"); eprintln!("im: unexpected argument {other}"); std::process::exit(2); } } } pack::pack_command(&config, root.as_deref(), out.as_deref()).await; } Some("unpack") => { let Some(archive) = args.get(2) else { eprintln!("usage: im-web unpack FILE [--root DIR] [--force]"); std::process::exit(2); }; let mut root: Option = None; let mut force = false; let mut rest = args[3..].iter(); while let Some(arg) = rest.next() { match arg.as_str() { "--force" => force = true, "--root" => match rest.next() { Some(value) => root = Some(value.clone()), None => { eprintln!("usage: im-web unpack FILE [--root DIR] [--force]"); eprintln!("im: --root needs a directory"); std::process::exit(2); } }, other => { eprintln!("usage: im-web unpack FILE [--root DIR] [--force]"); eprintln!("im: unexpected argument {other}"); std::process::exit(2); } } } pack::unpack_command(archive, root.as_deref(), force); } Some(other) => { eprintln!( "im: unknown command {other:?} (expected: invite, revoke, promote, demote, create-client, rotate-client, revoke-client, pack, unpack, or none to serve)" ); std::process::exit(2); } } } /// `im-web promote|demote `: the admin flag for an account that /// already exists — the migration path's way in, since invites refuse /// addresses with accounts. async fn set_admin_cli(config: Config, email: &str, admin: bool) { let store = open_store(&config).await; let Some(user) = im_core::accounts::user_by_email(&store, email) .await .expect("failed to read users") else { eprintln!("im: no account for {email}"); std::process::exit(1); }; im_core::accounts::set_admin(&store, &user.id, admin) .await .expect("failed to update"); im_core::events::log( &store, if admin { "user_promoted" } else { "user_demoted" }, Some("cli"), Some(email), ) .await; println!("im {email}: admin = {admin}"); } async fn open_store(config: &Config) -> Arc { Arc::new( Store::open(&config.database) .await .expect("failed to open the database"), ) } /// The one-time seed: a database with no services yet takes the config's /// `[[services]]` list as the family's starting rows. Afterwards the admin /// panel owns the list and the same file lines are dead letters — the seed /// only fires again if the table is emptied. async fn seed_services(store: &Store, config: &Config) { if config.services.is_empty() { return; } let seed: Vec = config .services .iter() .map(|service| im_core::services::Service { key: service.key.clone(), name: service.name.clone(), url: service.url.clone(), owner: None, client_id: None, storage_limit_bytes: None, }) .collect(); match im_core::services::seed_from(store, &seed).await { Ok(true) => println!( "im services seeded from config ({} entries)", seed.len() ), Ok(false) => {} Err(e) => eprintln!("im: seeding services from config failed: {e}"), } } /// im's own row of the family, written on every boot from `issuer`: the /// address is the running app's, not a config line someone edits once and /// forgets. A seeded `im` row is claimed here (its name stays the admin's); /// afterwards the panel can rename and reorder it, but not re-point or /// remove it. Never a reason to refuse boot — the family is a convenience, /// the sign-in is not. async fn register_self(store: &Store, config: &Config) { match im_core::services::register( store, im_core::services::SELF_OWNER, "Account", &config.issuer, im_core::services::SELF_OWNER, // im is nobody's client: its own row carries no credential stamp. None, ) .await { Ok(service) => println!("im registered itself in the family at {}", service.url), Err(e) => eprintln!("im: registering itself in the family failed: {e}"), } } /// `im-web invite [--admin]`: creates the invite, mails it when the /// panel has configured a sender, prints the link otherwise (dev mode). /// /// Needs the server stopped: Turso is a single-writer engine, and this /// process would hold the same file. async fn invite(config: Config, email: &str, admin: bool) { let store = open_store(&config).await; let token = match im_core::accounts::create_invite(&store, email, None, admin).await { Ok(token) => token, Err(im_core::accounts::AccountError::EmailTaken) => { eprintln!( "im: {email} already has an account — `im-web promote {email}` if you mean admin" ); std::process::exit(1); } Err(e) => panic!("failed to create the invite: {e}"), }; im_core::events::log( &store, "invite_created", Some("cli"), Some(&format!( "for {email}{}", if admin { " (admin)" } else { "" } )), ) .await; match mailer::send_invite(&store, &config.issuer, email, token.expose()).await { Ok(link) => println!("im invite mailed to {email}\nim {link}"), Err(_) => println!( "im invite for {email}: {}/invite/{}", config.issuer, token.expose() ), } } /// `im-web revoke `: signs the person out everywhere — central /// sessions, refresh tokens, and the app sessions introspection answers for. async fn revoke(config: Config, email: &str) { let store = open_store(&config).await; let Some(user) = im_core::accounts::user_by_email(&store, email) .await .expect("failed to read users") else { eprintln!("im: no account for {email}"); std::process::exit(1); }; let count = im_core::sessions::revoke_user_sessions(&store, &user.id) .await .expect("failed to revoke"); im_core::events::log(&store, "sessions_revoked", Some("cli"), Some(email)).await; println!("im {email}: {count} session(s) revoked, everywhere, now"); } /// `im-web create-client `: registers a relying party and /// prints the secret exactly once. async fn create_client(config: Config, name: &str, uris: &[String]) { let store = open_store(&config).await; let (id, secret) = im_core::oidc::create_client(&store, name, uris.to_vec()) .await .expect("failed to create the client"); println!("im client {name}"); println!(" client_id {id}"); println!(" client_secret {}", secret.expose()); println!(" (the secret is shown once; its digest is all the database keeps)"); } /// `im-web rotate-client `: replaces the client's secret and /// prints the new one exactly once — the app's old pair dies with the write. /// /// Needs the server stopped, like every CLI arm: Turso is a single-writer /// engine, and this process would hold the same file. async fn rotate_client(config: Config, id: &str) { let store = open_store(&config).await; let name = client_name(&store, id).await; match im_core::oidc::rotate_client_secret(&store, id) .await .expect("failed to rotate the client secret") { Some(secret) => { im_core::events::log(&store, "client_rotated", Some("cli"), Some(&name)).await; println!("im client {id} ({name})"); println!(" client_secret {}", secret.expose()); println!(" (the secret is shown once; its digest is all the database keeps)"); } None => { eprintln!("im: no client {id}"); std::process::exit(1); } } } /// `im-web revoke-client `: deletes the registry row and every /// refresh token and app session minted under it; the person's own sign-in /// sessions stay. /// /// Needs the server stopped, like every CLI arm: Turso is a single-writer /// engine, and this process would hold the same file. async fn revoke_client(config: Config, id: &str) { let store = open_store(&config).await; // The name rides the log line and the goodbye, so it comes off the row // before the row goes. let name = client_name(&store, id).await; match im_core::oidc::revoke_client(&store, id) .await .expect("failed to revoke the client") { true => { println!( "im client {id} ({name}) revoked — its tokens and app sessions went with it" ); } false => { eprintln!("im: no client {id}"); std::process::exit(1); } } } /// The client's display name, or its id when no row stands behind it — the /// log's detail is the name when there is one. async fn client_name(store: &Arc, id: &str) -> String { im_core::oidc::client_by_id(store, id) .await .expect("failed to read the client") .map(|client| client.name) .unwrap_or_else(|| id.to_string()) } async fn serve(config: Config) { for line in config.report() { println!("im {line}"); } let store = open_store(&config).await; seed_services(&store, &config).await; register_self(&store, &config).await; let (live, _) = tokio::sync::broadcast::channel(64); // Told when the process is stopping, so the live streams end instead of // being waited out — see `live::Shutdown`. let (stop, stopping) = tokio::sync::watch::channel(false); let app = server::App { store, config: config.clone(), live, }; let bundle = topcoat::asset::AssetBundle::load().unwrap_or_else(|err| { eprintln!("im: the asset bundle beside the executable failed to load: {err}"); eprintln!("im: run `topcoat asset bundle -p im-web` first"); std::process::exit(2); }); let router = Router::builder() .discover() // Headroom over the photo cap: the boundary and part headers ride // inside the body limit, so the handler's byte cap — not this layer — // stays the one that says "over 5 MB". .layer(BodyLimit::max(photo::PHOTO_LIMIT_BYTES as usize + 4096).at("/api/profile_photo")) .cookies() .assets(bundle) .trusted_proxies(server::trusted_proxies()) .app_context(app) .app_context(live::Shutdown(stopping)) .build(); // `topcoat::start` binds HOST/PORT from the environment; the listen // address is a config/im.toml decision, so the listener is bound // explicitly against the same value the boot log just printed. let listener = tokio::net::TcpListener::bind(config.listen) .await .expect("failed to bind the listen address"); topcoat::serve_until(listener, router, shutdown_signal(stop)) .await .expect("server error"); } /// Resolves when the process is asked to stop: Ctrl+C, or `SIGTERM` from a /// service manager. The live streams hear it first, so the graceful shutdown /// does not sit waiting on one long-lived connection per open tab. async fn shutdown_signal(stop: tokio::sync::watch::Sender) { let ctrl_c = async { tokio::signal::ctrl_c() .await .expect("failed to install the Ctrl+C handler"); }; #[cfg(unix)] let terminate = async { tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) .expect("failed to install the SIGTERM handler") .recv() .await; }; #[cfg(not(unix))] let terminate = std::future::pending::<()>(); tokio::select! { () = ctrl_c => {}, () = terminate => {}, } // Streams end on their own; the browser reconnects when we are back. let _ = stop.send(true); }