diff --git a/Cargo.toml b/Cargo.toml index e825be1..9a13a0c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ members = [ [workspace.package] version = "0.1.0" edition = "2024" +license = "AGPL-3.0-or-later" repository = "https://github.com/DizeyLab/im" [workspace.dependencies] diff --git a/crates/im-client/src/lib.rs b/crates/im-client/src/lib.rs index b09f457..f8b6129 100644 --- a/crates/im-client/src/lib.rs +++ b/crates/im-client/src/lib.rs @@ -91,27 +91,58 @@ fn client(cx: &Cx) -> &ImClient { try_app_context::(cx).expect("im_client::mount was called on the router") } -/// The authenticated person, if this browser has one. Transparently refreshes -/// against im when the access token has aged out; `None` means signed out. +/// The authenticated person, if this browser has one. Every call asks im: +/// the cookie holds an opaque session token, introspected per request, so an +/// admin revoking the person signs them out of this app immediately — there +/// is no token-validity window in which a ghost lives. pub async fn current_user(cx: &Cx) -> Option { let state = client(cx); let sealed = cookies(cx).get(&state.config.cookie_name)?; - let mut session: Session = open_json(&state.config.cookie_key, sealed.value())?; - if session.access_exp > OffsetDateTime::now_utc().unix_timestamp() { - return Some(session.user()); + let session: Session = open_json(&state.config.cookie_key, sealed.value())?; + if session.exp <= OffsetDateTime::now_utc().unix_timestamp() { + clear_cookie(cx, &state.config.cookie_name); + return None; } - match refresh(cx, state, &mut session).await { - Ok(()) => { - set_session_cookie(cx, state, &session); - Some(session.user()) - } - Err(_) => { + match introspect(state, &session.app_session).await { + Some((user, _exp)) => Some(user), + None => { clear_cookie(cx, &state.config.cookie_name); None } } } +/// POSTs the session token to im's `/introspect` with this app's credentials. +/// Network failure reads as signed-out for this request — the cookie stays, +/// so the next request tries again. +async fn introspect(state: &ImClient, token: &str) -> Option<(User, i64)> { + let answer: serde_json::Value = state + .http + .post(format!("{}/introspect", state.config.issuer)) + .form(&[ + ("token", token), + ("client_id", &state.config.client_id), + ("client_secret", &state.config.client_secret), + ]) + .send() + .await + .ok()? + .json() + .await + .ok()?; + if answer["active"] != true { + return None; + } + Some(( + User { + sub: answer["sub"].as_str()?.to_string(), + email: answer["email"].as_str()?.to_string(), + name: answer["name"].as_str()?.to_string(), + }, + answer["exp"].as_i64()?, + )) +} + /// Who this browser is, from the claims. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct User { @@ -126,15 +157,10 @@ pub struct User { #[derive(Serialize, Deserialize)] struct Session { - user: User, - refresh_token: String, - access_exp: i64, -} - -impl Session { - fn user(&self) -> User { - self.user.clone() - } + /// The opaque token im issued at the code exchange; introspected per + /// request, never trusted on its own. + app_session: String, + exp: i64, } /// The in-flight login: PKCE verifier, state, nonce, and where to land after. @@ -394,13 +420,12 @@ fn urlencoded(raw: &str) -> String { #[derive(Deserialize)] struct TokenAnswer { - /// Present on the wire; the app reads identity from the id_token and - /// never calls userinfo, so the access token is carried, not used. - #[serde(rename = "access_token")] - _access_token: String, - refresh_token: String, + /// Validated for its nonce and signature; the identity the app serves + /// comes from introspection, not from these claims. id_token: String, - expires_in: i64, + /// Not OIDC — im's own: the opaque session this crate introspects per + /// request. Absent means the issuer is not a current im. + app_session: Option, } async fn exchange_code(state: &ImClient, code: &str, flight: &InFlight) -> Result { @@ -427,43 +452,15 @@ async fn exchange_code(state: &ImClient, code: &str, flight: &InFlight) -> Resul if claims["nonce"].as_str() != Some(flight.nonce.as_str()) { return Err(Error::Token("nonce mismatch".into())); } - Ok(session_from(&answer, claims)) -} - -async fn refresh(cx: &Cx, state: &ImClient, session: &mut Session) -> Result<()> { - let _ = cx; - let answer: TokenAnswer = state - .http - .post(format!("{}/token", state.config.issuer)) - .form(&[ - ("grant_type", "refresh_token"), - ("refresh_token", &session.refresh_token), - ("client_id", &state.config.client_id), - ("client_secret", &state.config.client_secret), - ]) - .send() - .await - .map_err(|e| Error::Http(e.to_string()))? - .error_for_status() - .map_err(|e| Error::Refused(e.to_string()))? - .json() + let app_session = answer + .app_session + .ok_or_else(|| Error::Token("issuer gave no app session".into()))?; + // The session's expiry and identity come from a live introspection, not + // from the token answer — the same check every later request will make. + let (_user, exp) = introspect(state, &app_session) .await - .map_err(|e| Error::Http(e.to_string()))?; - let claims = validate_id_token(state, &answer.id_token).await?; - *session = session_from(&answer, claims); - Ok(()) -} - -fn session_from(answer: &TokenAnswer, claims: serde_json::Value) -> Session { - Session { - user: User { - sub: claims["sub"].as_str().unwrap_or_default().to_string(), - email: claims["email"].as_str().unwrap_or_default().to_string(), - name: claims["name"].as_str().unwrap_or_default().to_string(), - }, - refresh_token: answer.refresh_token.clone(), - access_exp: OffsetDateTime::now_utc().unix_timestamp() + answer.expires_in, - } + .ok_or_else(|| Error::Refused("fresh app session does not introspect".into()))?; + Ok(Session { app_session, exp }) } /// Validates an id_token: RS256 against im's JWKS, issuer, audience, expiry. @@ -693,17 +690,12 @@ mod tests { fn cookie_seal_roundtrip() { let key = [7u8; 32]; let session = Session { - user: User { - sub: "u".into(), - email: "e".into(), - name: "n".into(), - }, - refresh_token: "r".into(), - access_exp: 1, + app_session: "opaque-token".into(), + exp: 1, }; let sealed = seal_json(&key, &session); let back: Session = open_json(&key, &sealed).unwrap(); - assert_eq!(back.refresh_token, "r"); + assert_eq!(back.app_session, "opaque-token"); assert!(open_json::(&[8u8; 32], &sealed).is_none()); assert!(open_json::(&key, "garbage").is_none()); } diff --git a/crates/im-core/src/accounts.rs b/crates/im-core/src/accounts.rs index f4e4bd0..7b2a72c 100644 --- a/crates/im-core/src/accounts.rs +++ b/crates/im-core/src/accounts.rs @@ -226,6 +226,7 @@ pub async fn create_invite( store: &Store, email: &str, invited_by: Option, + admin: bool, ) -> std::result::Result { let token = Token::mint(); let now = store::now(); @@ -233,12 +234,13 @@ pub async fn create_invite( store .conn .execute( - "INSERT INTO invites (token, email, invited_by, created_at, expires_at) \ - VALUES (?1, ?2, ?3, ?4, ?5)", + "INSERT INTO invites (token, email, invited_by, admin, created_at, expires_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", turso::params![ token.hash(), email, invited_by.map(|id| id.to_string()), + admin as i64, store::stamp(now)?, store::stamp(expires)?, ], @@ -254,7 +256,7 @@ pub async fn invite_by_token(store: &Store, token: &str) -> Result Result Some(store::parse_stamp(&raw)?), None => None, }, @@ -299,6 +302,7 @@ pub async fn create_user_from_invite( email: invite.email.clone(), name: name.to_string(), totp_confirmed: false, + admin: invite.admin, disabled: false, created_at: store::now(), }; @@ -313,13 +317,14 @@ pub async fn create_user_from_invite( store .conn .execute( - "INSERT INTO users (id, email, name, password_hash, created_at) \ - VALUES (?1, ?2, ?3, ?4, ?5)", + "INSERT INTO users (id, email, name, password_hash, admin, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", turso::params![ user.id.to_string(), user.email.clone(), user.name.clone(), password_hash, + user.admin as i64, store::stamp(user.created_at)?, ], ) @@ -366,7 +371,7 @@ pub async fn verify_login( let mut rows = store .conn .query( - "SELECT id, email, name, password_hash, totp_confirmed, disabled, created_at \ + "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at \ FROM users WHERE email = ?1 COLLATE NOCASE", turso::params![email], ) @@ -381,8 +386,9 @@ pub async fn verify_login( email: store::text(&row, 1)?, name: store::text(&row, 2)?, totp_confirmed: store::int(&row, 4)? != 0, - disabled: store::int(&row, 5)? != 0, - created_at: store::parse_stamp(&store::text(&row, 6)?)?, + admin: store::int(&row, 5)? != 0, + disabled: store::int(&row, 6)? != 0, + created_at: store::parse_stamp(&store::text(&row, 7)?)?, }; let phc = store::text(&row, 3)?; if !verify_password(password, &phc) || user.disabled { @@ -391,12 +397,28 @@ pub async fn verify_login( Ok(user) } -/// Looks a user up by id — what sessions and tokens resolve to. +/// Looks a user up by email — the CLI's revoke path resolves names this way. +pub async fn user_by_email(store: &Store, email: &str) -> Result> { + let mut rows = store + .conn + .query( + "SELECT id FROM users WHERE email = ?1 COLLATE NOCASE", + turso::params![email], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(None); + }; + let id = UserId::from(store::text(&row, 0)?); + user_by_id(store, &id).await +} + pub async fn user_by_id(store: &Store, id: &UserId) -> Result> { let mut rows = store .conn .query( - "SELECT id, email, name, totp_confirmed, disabled, created_at \ + "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \ FROM users WHERE id = ?1", turso::params![id.to_string()], ) @@ -410,11 +432,53 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result> { email: store::text(&row, 1)?, name: store::text(&row, 2)?, totp_confirmed: store::int(&row, 3)? != 0, - disabled: store::int(&row, 4)? != 0, - created_at: store::parse_stamp(&store::text(&row, 5)?)?, + admin: store::int(&row, 4)? != 0, + disabled: store::int(&row, 5)? != 0, + created_at: store::parse_stamp(&store::text(&row, 6)?)?, })) } +/// Every user, oldest first — the admin panel's roster. +pub async fn list_users(store: &Store) -> Result> { + let mut rows = store + .conn + .query( + "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \ + FROM users ORDER BY created_at", + (), + ) + .await + .map_err(backend)?; + let mut users = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + users.push(User { + id: UserId::from(store::text(&row, 0)?), + email: store::text(&row, 1)?, + name: store::text(&row, 2)?, + totp_confirmed: store::int(&row, 3)? != 0, + admin: store::int(&row, 4)? != 0, + disabled: store::int(&row, 5)? != 0, + created_at: store::parse_stamp(&store::text(&row, 6)?)?, + }); + } + Ok(users) +} + +/// Enables or disables an account. A disabled account cannot log in, its +/// sessions resolve to nobody, and introspection says inactive — every door +/// closes on the same flag. +pub async fn set_disabled(store: &Store, user: &UserId, disabled: bool) -> Result<()> { + store + .conn + .execute( + "UPDATE users SET disabled = ?1 WHERE id = ?2", + turso::params![disabled as i64, user.to_string()], + ) + .await + .map_err(backend)?; + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -455,7 +519,7 @@ mod tests { #[tokio::test] async fn invite_to_user_to_login() { let store = fixture().await; - let token = create_invite(&store, "ann@example.com", None) + let token = create_invite(&store, "ann@example.com", None, false) .await .unwrap(); let invite = invite_by_token(&store, token.expose()) @@ -493,13 +557,13 @@ mod tests { #[tokio::test] async fn duplicate_email_is_refused() { let store = fixture().await; - let first = create_invite(&store, "ann@example.com", None) + let first = create_invite(&store, "ann@example.com", None, false) .await .unwrap(); create_user_from_invite(&store, first.expose(), "Ann", "tDLr9!mZQ2xv") .await .unwrap(); - let second = create_invite(&store, "ann@example.com", None) + let second = create_invite(&store, "ann@example.com", None, false) .await .unwrap(); assert!(matches!( diff --git a/crates/im-core/src/events.rs b/crates/im-core/src/events.rs new file mode 100644 index 0000000..18ed7d5 --- /dev/null +++ b/crates/im-core/src/events.rs @@ -0,0 +1,82 @@ +//! The audit log: one row per thing that happened to identity — logins, +//! refusals, invites, enrolments, revocations. The admin panel's Logs +//! section reads it; nothing here is a hot path (introspection is +//! deliberately NOT logged — it runs per request and would drown the rest). + +use crate::store::{self, Result, Store, backend}; + +#[derive(Debug, Clone)] +pub struct Event { + pub id: String, + pub at: time::OffsetDateTime, + pub kind: String, + pub actor: Option, + pub detail: Option, +} + +/// Appends an event. Never fails the caller's operation: a log that cannot +/// be written is printed, not propagated. +pub async fn log(store: &Store, kind: &str, actor: Option<&str>, detail: Option<&str>) { + let outcome = store + .conn + .execute( + "INSERT INTO events (id, at, kind, actor, detail) VALUES (?1, ?2, ?3, ?4, ?5)", + turso::params![ + ulid::Ulid::new().to_string(), + store::stamp(store::now()).expect("rfc3339 of now"), + kind, + actor, + detail, + ], + ) + .await; + if let Err(e) = outcome { + eprintln!("im event {kind} ({actor:?}): could not be logged: {e}"); + } +} + +/// Newest-first page of the log for the admin panel. +pub async fn list(store: &Store, limit: i64) -> Result> { + let mut rows = store + .conn + .query( + "SELECT id, at, kind, actor, detail FROM events ORDER BY at DESC, id DESC LIMIT ?1", + turso::params![limit], + ) + .await + .map_err(backend)?; + let mut events = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + events.push(Event { + id: store::text(&row, 0)?, + at: store::parse_stamp(&store::text(&row, 1)?)?, + kind: store::text(&row, 2)?, + actor: store::opt_text(&row, 3)?, + detail: store::opt_text(&row, 4)?, + }); + } + Ok(events) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::Path; + + #[tokio::test] + async fn log_and_list_newest_first() { + let store = Store::open(Path::new(":memory:")).await.unwrap(); + log(&store, "login_ok", Some("ann@example.com"), None).await; + log( + &store, + "login_fail", + Some("bob@example.com"), + Some("wrong password"), + ) + .await; + let events = list(&store, 10).await.unwrap(); + assert_eq!(events.len(), 2); + assert_eq!(events[0].kind, "login_fail"); + assert_eq!(events[1].actor.as_deref(), Some("ann@example.com")); + } +} diff --git a/crates/im-core/src/lib.rs b/crates/im-core/src/lib.rs index 9ba82e6..d3477de 100644 --- a/crates/im-core/src/lib.rs +++ b/crates/im-core/src/lib.rs @@ -8,6 +8,8 @@ #[cfg(feature = "server")] pub mod accounts; #[cfg(feature = "server")] +pub mod events; +#[cfg(feature = "server")] pub mod keys; #[cfg(feature = "server")] pub mod oidc; @@ -16,6 +18,8 @@ mod secret; #[cfg(feature = "server")] pub mod sessions; #[cfg(feature = "server")] +pub mod settings; +#[cfg(feature = "server")] pub mod store; #[cfg(feature = "server")] pub mod totp; diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs index bd163c3..f8787d7 100644 --- a/crates/im-core/src/model.rs +++ b/crates/im-core/src/model.rs @@ -51,6 +51,9 @@ pub struct User { pub email: String, pub name: String, pub totp_confirmed: bool, + /// im's own admin flag — never crosses a token; AuthN stays the only + /// thing apps receive. + pub admin: bool, pub disabled: bool, pub created_at: OffsetDateTime, } @@ -61,6 +64,8 @@ pub struct User { pub struct Invite { pub email: String, pub invited_by: Option, + /// An admin invite mints an admin. + pub admin: bool, pub created_at: OffsetDateTime, pub expires_at: OffsetDateTime, pub accepted_at: Option, diff --git a/crates/im-core/src/oidc.rs b/crates/im-core/src/oidc.rs index a10eea1..9ae5732 100644 --- a/crates/im-core/src/oidc.rs +++ b/crates/im-core/src/oidc.rs @@ -411,6 +411,111 @@ pub async fn verify_jwt( Ok(Some(claims)) } +// --------------------------------------------------------------------------- +// App sessions: the opaque, introspected session an app actually holds +// --------------------------------------------------------------------------- + +/// How long an app session may live when nothing revokes it first. +pub const APP_SESSION_DAYS: i64 = 30; + +/// Mints an opaque app session bound to the central session that authorized +/// it. The app stores only this token; every request it serves introspects +/// the token against im, so revocation is immediate rather than +/// token-TTL-bounded. +pub async fn issue_app_session( + store: &Store, + user: &UserId, + client_id: &ClientId, + session_hash: &str, +) -> Result { + let token = Token::mint(); + let now = store::now(); + store + .conn + .execute( + "INSERT INTO app_sessions \ + (token_hash, user_id, client_id, session_hash, created_at, expires_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + turso::params![ + token.hash(), + user.to_string(), + client_id.to_string(), + session_hash, + store::stamp(now)?, + store::stamp(now + time::Duration::days(APP_SESSION_DAYS))?, + ], + ) + .await + .map_err(backend)?; + Ok(token) +} + +/// RFC 7662's answer shape: who this token is, or inactive. Inactive covers +/// unknown, expired, revoked, a revoked central session, a disabled user, or +/// a token presented by a client it was never issued to. +pub async fn introspect_app_session( + store: &Store, + token: &str, + client_id: &str, +) -> Result> { + let mut rows = store + .conn + .query( + "SELECT user_id, client_id, session_hash, expires_at, revoked_at \ + FROM app_sessions WHERE token_hash = ?1", + turso::params![hash_token(token)], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(None); + }; + if store::opt_text(&row, 4)?.is_some() { + return Ok(None); + } + let expires = store::parse_stamp(&store::text(&row, 3)?)?; + if expires < store::now() { + return Ok(None); + } + if store::text(&row, 1)? != client_id { + return Ok(None); + } + // The central session must still be alive — this is what makes admin + // revocation immediate. + let session_hash = store::text(&row, 2)?; + let mut sessions = store + .conn + .query( + "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1", + turso::params![session_hash], + ) + .await + .map_err(backend)?; + let Some(session) = sessions.next().await.map_err(backend)? else { + return Ok(None); + }; + if store::opt_text(&session, 1)?.is_some() { + return Ok(None); + } + if store::parse_stamp(&store::text(&session, 0)?)? < store::now() { + return Ok(None); + } + let user_id = UserId::from(store::text(&row, 0)?); + let Some(user) = crate::accounts::user_by_id(store, &user_id).await? else { + return Ok(None); + }; + if user.disabled { + return Ok(None); + } + Ok(Some(serde_json::json!({ + "active": true, + "sub": user.id.as_str(), + "email": user.email, + "name": user.name, + "exp": expires.unix_timestamp(), + }))) +} + #[cfg(test)] mod tests { use super::*; @@ -419,13 +524,49 @@ mod tests { use rsa::signature::Verifier; use std::path::Path; + #[tokio::test] + async fn app_session_introspection_and_instant_revoke() { + let (store, client_id, user_id) = fixture().await; + let session = create_session(&store, &user_id).await.unwrap(); + let app_token = issue_app_session(&store, &user_id, &client_id, &session.hash()) + .await + .unwrap(); + + let active = introspect_app_session(&store, app_token.expose(), client_id.as_str()) + .await + .unwrap() + .unwrap(); + assert_eq!(active["active"], true); + assert_eq!(active["sub"], user_id.as_str()); + + // Another client cannot spend the token. + assert!( + introspect_app_session(&store, app_token.expose(), "someone-else") + .await + .unwrap() + .is_none() + ); + + // Admin revokes the person: the very next introspection is inactive. + crate::sessions::revoke_user_sessions(&store, &user_id) + .await + .unwrap(); + assert!( + introspect_app_session(&store, app_token.expose(), client_id.as_str()) + .await + .unwrap() + .is_none(), + "no ghost after admin revocation" + ); + } + async fn fixture() -> (Store, ClientId, UserId) { let store = Store::open(Path::new(":memory:")).await.unwrap(); let (client_id, _secret) = create_client(&store, "demo", vec!["http://app/callback".into()]) .await .unwrap(); - let invite = create_invite(&store, "ann@example.com", None) + let invite = create_invite(&store, "ann@example.com", None, false) .await .unwrap(); let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") diff --git a/crates/im-core/src/sessions.rs b/crates/im-core/src/sessions.rs index 895d39a..18eedea 100644 --- a/crates/im-core/src/sessions.rs +++ b/crates/im-core/src/sessions.rs @@ -61,15 +61,22 @@ pub async fn resolve_session(store: &Store, token: &str) -> Result> } } -/// Revokes a session and every refresh token bound to it. +/// Revokes a session and everything bound to it: refresh tokens and the +/// opaque app sessions introspection answers for. pub async fn revoke_session(store: &Store, token: &str) -> Result<()> { - let now = store::stamp(store::now())?; let hash = hash_token(token); + revoke_session_hash(store, &hash).await +} + +/// The hash-level half of [`revoke_session`], shared with the admin's +/// revoke-everything below. +pub(crate) async fn revoke_session_hash(store: &Store, hash: &str) -> Result<()> { + let now = store::stamp(store::now())?; store .conn .execute( "UPDATE sessions SET revoked_at = ?1 WHERE token_hash = ?2 AND revoked_at IS NULL", - turso::params![now.clone(), hash.clone()], + turso::params![now.clone(), hash], ) .await .map_err(backend)?; @@ -77,6 +84,14 @@ pub async fn revoke_session(store: &Store, token: &str) -> Result<()> { .conn .execute( "UPDATE refresh_tokens SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL", + turso::params![now.clone(), hash], + ) + .await + .map_err(backend)?; + store + .conn + .execute( + "UPDATE app_sessions SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL", turso::params![now, hash], ) .await @@ -84,6 +99,49 @@ pub async fn revoke_session(store: &Store, token: &str) -> Result<()> { Ok(()) } +/// The admin's "log this person out everywhere": every central session of +/// theirs dies, and the cascades above take every refresh token and every +/// live app session down with them. Introspection is per-request, so the +/// next call any app makes on their behalf comes back inactive — no ghost. +pub async fn revoke_user_sessions(store: &Store, user: &UserId) -> Result { + let mut rows = store + .conn + .query( + "SELECT token_hash FROM sessions WHERE user_id = ?1 AND revoked_at IS NULL", + turso::params![user.to_string()], + ) + .await + .map_err(backend)?; + let mut hashes = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + hashes.push(store::text(&row, 0)?); + } + let count = hashes.len() as u64; + for hash in hashes { + revoke_session_hash(store, &hash).await?; + } + // Sessions already revoked earlier still own live app sessions; sweep + // those too so nothing outlives the person being signed out. + let now = store::stamp(store::now())?; + store + .conn + .execute( + "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", + turso::params![now.clone(), user.to_string()], + ) + .await + .map_err(backend)?; + store + .conn + .execute( + "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", + turso::params![now, user.to_string()], + ) + .await + .map_err(backend)?; + Ok(count) +} + #[cfg(test)] mod tests { use super::*; @@ -92,7 +150,7 @@ mod tests { async fn fixture() -> (Store, UserId) { let store = Store::open(Path::new(":memory:")).await.unwrap(); - let invite = create_invite(&store, "ann@example.com", None) + let invite = create_invite(&store, "ann@example.com", None, false) .await .unwrap(); let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") diff --git a/crates/im-core/src/settings.rs b/crates/im-core/src/settings.rs new file mode 100644 index 0000000..6f538e0 --- /dev/null +++ b/crates/im-core/src/settings.rs @@ -0,0 +1,172 @@ +//! Admin-managed settings in the database, sealed where they are secrets — +//! the same contract izlek-core's `store/secret.rs` keeps for SMTP. The TOML +//! config holds deployment facts (paths, listen, issuer); the settings table +//! holds what an admin rotates from the panel. + +use crate::secret; +use crate::store::{self, Result, Store, backend}; + +/// The SMTP sender, as the panel sets it. `password` only ever comes back +/// opened; the row holds the sealed envelope. +#[derive(Debug, Clone, Default)] +pub struct Smtp { + pub host: String, + pub port: u16, + pub username: String, + pub from: String, + pub password: Option, +} + +impl Smtp { + pub fn configured(&self) -> bool { + !self.host.is_empty() && self.port > 0 && !self.from.is_empty() + } +} + +async fn get(store: &Store, key: &str) -> Result> { + let mut rows = store + .conn + .query( + "SELECT value FROM settings WHERE key = ?1", + turso::params![key], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(None); + }; + store::opt_text(&row, 0) +} + +async fn set(store: &Store, key: &str, value: &str) -> Result<()> { + store + .conn + .execute( + "INSERT INTO settings (key, value) VALUES (?1, ?2) \ + ON CONFLICT(key) DO UPDATE SET value = excluded.value", + turso::params![key, value], + ) + .await + .map_err(backend)?; + Ok(()) +} + +/// Reads the SMTP settings; a sealed password that no longer opens reads as +/// absent (wrong im.key, restored backup) — the same degradation izlek-core +/// chose. +pub async fn smtp(store: &Store) -> Result { + let host = get(store, "smtp_host").await?.unwrap_or_default(); + let port = get(store, "smtp_port") + .await? + .and_then(|raw| raw.parse().ok()) + .unwrap_or(465); + let username = get(store, "smtp_username").await?.unwrap_or_default(); + let from = get(store, "smtp_from").await?.unwrap_or_default(); + let password = get(store, "smtp_password") + .await? + .and_then(|sealed| secret::open(store.key(), &sealed)) + .and_then(|bytes| String::from_utf8(bytes).ok()); + Ok(Smtp { + host, + port, + username, + from, + password, + }) +} + +/// Writes the SMTP settings. `password: None` keeps the stored one — the +/// panel's password field is write-only, like izlek's. +pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Result<()> { + if smtp.host.is_empty() { + for key in [ + "smtp_host", + "smtp_port", + "smtp_username", + "smtp_from", + "smtp_password", + ] { + store + .conn + .execute("DELETE FROM settings WHERE key = ?1", turso::params![key]) + .await + .map_err(backend)?; + } + return Ok(()); + } + set(store, "smtp_host", &smtp.host).await?; + set(store, "smtp_port", &smtp.port.to_string()).await?; + set(store, "smtp_username", &smtp.username).await?; + set(store, "smtp_from", &smtp.from).await?; + if let Some(password) = password { + if !password.is_empty() { + set( + store, + "smtp_password", + &secret::seal(store.key(), password.as_bytes()), + ) + .await?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::Path; + + #[tokio::test] + async fn smtp_roundtrip_with_sealed_password() { + let store = Store::open(Path::new(":memory:")).await.unwrap(); + assert!(!smtp(&store).await.unwrap().configured()); + + let value = Smtp { + host: "smtp.example.com".into(), + port: 465, + username: "im".into(), + from: "im ".into(), + password: None, + }; + set_smtp(&store, &value, Some("s3cret")).await.unwrap(); + let read = smtp(&store).await.unwrap(); + assert!(read.configured()); + assert_eq!(read.password.as_deref(), Some("s3cret")); + + // A write without a password keeps the stored one. + set_smtp(&store, &value, None).await.unwrap(); + assert_eq!( + smtp(&store).await.unwrap().password.as_deref(), + Some("s3cret") + ); + + // An empty host clears the sender. + set_smtp(&store, &Smtp::default(), None).await.unwrap(); + assert!(!smtp(&store).await.unwrap().configured()); + } + + #[tokio::test] + async fn sealed_password_needs_the_key() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("im.db"); + { + let store = Store::open(&path).await.unwrap(); + let value = Smtp { + host: "smtp.example.com".into(), + port: 465, + username: String::new(), + from: "a@b.c".into(), + password: None, + }; + set_smtp(&store, &value, Some("s3cret")).await.unwrap(); + } + // A different key cannot open it. + let sealed = { + let store = Store::open(&path).await.unwrap(); + super::get(&store, "smtp_password").await.unwrap().unwrap() + }; + assert!(secret::is_sealed(&sealed)); + let wrong_key = [9u8; 32]; + assert!(secret::open(&wrong_key, &sealed).is_none()); + } +} diff --git a/crates/im-core/src/store.rs b/crates/im-core/src/store.rs index 58bc415..dc6fa66 100644 --- a/crates/im-core/src/store.rs +++ b/crates/im-core/src/store.rs @@ -35,6 +35,7 @@ CREATE TABLE IF NOT EXISTS users ( password_hash TEXT NOT NULL, totp_secret BLOB, totp_confirmed INTEGER NOT NULL DEFAULT 0, + admin INTEGER NOT NULL DEFAULT 0, disabled INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL ); @@ -42,6 +43,7 @@ CREATE TABLE IF NOT EXISTS invites ( token TEXT PRIMARY KEY, email TEXT NOT NULL, invited_by TEXT, + admin INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, expires_at TEXT NOT NULL, accepted_at TEXT @@ -86,6 +88,26 @@ CREATE TABLE IF NOT EXISTS signing_keys ( created_at TEXT NOT NULL, active INTEGER NOT NULL DEFAULT 1 ); +CREATE TABLE IF NOT EXISTS app_sessions ( + token_hash TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id), + client_id TEXT NOT NULL REFERENCES oidc_clients(client_id), + session_hash TEXT NOT NULL REFERENCES sessions(token_hash), + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + revoked_at TEXT +); +CREATE TABLE IF NOT EXISTS events ( + id TEXT PRIMARY KEY, + at TEXT NOT NULL, + kind TEXT NOT NULL, + actor TEXT, + detail TEXT +); +CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); "; /// One database handle with the at-rest key beside it. Turso is a diff --git a/crates/im-core/src/totp.rs b/crates/im-core/src/totp.rs index 6f31d51..bd823e3 100644 --- a/crates/im-core/src/totp.rs +++ b/crates/im-core/src/totp.rs @@ -179,7 +179,7 @@ mod tests { #[tokio::test] async fn store_roundtrip_and_confirm() { let store = Store::open(Path::new(":memory:")).await.unwrap(); - let invite = create_invite(&store, "ann@example.com", None) + let invite = create_invite(&store, "ann@example.com", None, false) .await .unwrap(); let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") diff --git a/crates/im-web/assets/main.css b/crates/im-web/assets/main.css index fc217fa..7a716c2 100644 --- a/crates/im-web/assets/main.css +++ b/crates/im-web/assets/main.css @@ -339,3 +339,164 @@ body:has(.auth-stage) > .auth-stage::-webkit-scrollbar { padding: 0 16px 24px; } } +body:has(.admin-shell) { + min-height: 100vh; + min-height: 100dvh; +} + +.admin-shell { + display: flex; + justify-content: center; + padding: 24px 24px 48px; +} + +.admin-column { + width: 760px; + max-width: 100%; + display: flex; + flex-direction: column; + gap: 16px; +} + +.admin-bar { + display: flex; + align-items: center; + gap: 20px; + height: var(--control-h-lg); +} +.admin-bar .wordmark-text { + font-size: 15px; +} + +.admin-tabs { + display: flex; + gap: 16px; +} + +.admin-nav { + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); + text-decoration: none; + padding-bottom: 2px; +} +.admin-nav:hover { + color: var(--ink); +} +.admin-nav-on { + color: var(--ink); + box-shadow: inset 0 -2px 0 var(--ink); +} + +.admin-bar .auth-alt { + margin-left: auto; + align-self: auto; +} + +.admin-card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + padding: 24px; + display: flex; + flex-direction: column; + gap: 16px; +} + +.admin-table { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} +.admin-table th { + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + color: var(--muted-soft); + text-align: left; + padding: 0 12px 6px 0; +} +.admin-table td { + padding: 8px 12px 8px 0; + border-top: 1px solid var(--border-soft); + vertical-align: middle; +} + +.mono { + font-family: var(--font-mono); +} + +.muted { + color: var(--muted); +} + +.actions { + display: flex; + gap: 8px; + justify-content: flex-end; +} +.actions form { + display: inline; +} + +.admin-action { + height: var(--control-h); + --control-h: 32px; + padding: 0 10px; + background: var(--surface); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + color: var(--ink); + font-size: 12px; + cursor: pointer; +} +.admin-action:hover { + background: var(--row-hover, var(--panel-sunken)); +} + +.admin-action-wide { + width: 100%; +} + +.admin-invite { + display: flex; + gap: 8px; + align-items: center; +} +.admin-invite .auth-input { + flex: 1; +} +.admin-invite .admin-action-wide { + width: auto; + padding: 0 20px; +} + +.admin-check { + display: flex; + align-items: center; + gap: 6px; + font-size: 12px; + color: var(--muted); + white-space: nowrap; +} + +.admin-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +input[type=checkbox] { + accent-color: var(--accent); +} + +@media (max-width: 720px) { + .admin-shell { + padding: 16px 12px 32px; + } + .admin-invite { + flex-wrap: wrap; + } +} diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs new file mode 100644 index 0000000..6c73337 --- /dev/null +++ b/crates/im-web/src/admin.rs @@ -0,0 +1,434 @@ +//! The admin panel: users, mail, logs. One page, three sections, every +//! action a plain form post answering a 303 back to its section — the same +//! idiom as izlek-web's settings.rs/logs.rs, minus the client script. + +use im_core::accounts; +use im_core::events; +use im_core::model::{User, UserId}; +use im_core::settings::{self, Smtp}; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::content::Form; +use topcoat::router::response::{IntoResponse, Response}; +use topcoat::router::{HeaderValue, StatusCode, header, route}; +use topcoat::view::view; + +use crate::layout::shell; +use crate::mailer; +use crate::pages::{error_text, query_value}; +use crate::server::{self, App}; + +fn app(cx: &Cx) -> &App { + server::app(cx) +} + +/// The admin behind this request, or the redirect the request gets instead. +async fn require_admin(cx: &Cx) -> std::result::Result { + match server::current_user(cx).await { + Some(user) if user.admin => Ok(user), + _ => Err(( + StatusCode::SEE_OTHER, + [(header::LOCATION, HeaderValue::from_static("/"))], + ) + .into_response(cx) + .expect("a redirect can always be built")), + } +} + +/// Everything user-controlled crosses the panel escaped — a display name is +/// free text and the panel renders raw HTML. +fn escape(raw: &str) -> String { + raw.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) +} + +fn back(cx: &Cx, section: &str, extra: &str) -> Result { + ( + StatusCode::SEE_OTHER, + [( + header::LOCATION, + HeaderValue::from_str(&format!("/admin?section={section}{extra}")) + .unwrap_or_else(|_| HeaderValue::from_static("/admin")), + )], + ) + .into_response(cx) +} + +#[route(GET "/admin")] +async fn admin_page(cx: &Cx) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + let query = topcoat::router::request::uri(cx) + .query() + .unwrap_or("") + .to_string(); + let section = query_value(&query, "section").unwrap_or_else(|| "users".to_string()); + let error = query_value(&query, "error"); + let ok = query_value(&query, "ok"); + let invited = query_value(&query, "invited"); + + let nav = |current: &str| { + [("users", "Users"), ("mail", "Mail"), ("logs", "Logs")] + .into_iter() + .map(|(id, label)| { + format!( + r#"{label}"#, + if id == current { " admin-nav-on" } else { "" } + ) + }) + .collect::() + }; + + let section_html = match section.as_str() { + "mail" => mail_section(cx).await?, + "logs" => logs_section(cx).await?, + _ => users_section(cx, &me, invited.as_deref()).await?, + }; + + let banner = match (ok.as_deref(), error.as_deref()) { + (Some(code), _) => Some(format!( + r#"
{}
"#, + match code { + "invited" => "Invite created.", + "revoked" => "Sessions revoked — every device is signed out.", + "disabled" => "Account disabled.", + "enabled" => "Account enabled.", + "smtp" => "Mail settings saved.", + "smtp_test" => "Test mail sent.", + _ => "Done.", + } + )), + (_, Some(code)) => Some(format!( + r#"
{}
"#, + error_text(code) + )), + _ => None, + }; + + let stage = view! { + cx => +
+
+
+ "im" + + (escape(&me.email)) +
+ if let Some(banner) = banner { + (topcoat::view::Unescaped::new_unchecked(banner)) + } + (topcoat::view::Unescaped::new_unchecked(section_html)) +
+
+ }; + shell(cx, "Admin · im", stage).await?.into_response(cx) +} + +async fn users_section( + cx: &Cx, + me: &User, + invited: Option<&str>, +) -> Result { + let users = accounts::list_users(&app(cx).store).await?; + let mut rows = String::new(); + for user in &users { + let flags = [ + user.admin.then_some("admin"), + user.disabled.then_some("disabled"), + (!user.totp_confirmed).then_some("no 2fa"), + ] + .into_iter() + .flatten() + .collect::>() + .join(" · "); + let actions = if user.id == me.id { + // Never let the only admin lock themselves out by reflex. + r#"you"#.to_string() + } else { + let id = escape(&user.id.to_string()); + let toggle = if user.disabled { + format!( + r#"
"# + ) + } else { + format!( + r#"
"# + ) + }; + format!( + r#"{toggle}
"# + ) + }; + rows.push_str(&format!( + "{}{}{}{}", + escape(&user.email), + escape(&user.name), + flags, + actions + )); + } + let invited_html = invited + .map(|link| { + format!( + r#"
The link exists once. It is shown once:
{}
"#, + escape(link) + ) + }) + .unwrap_or_default(); + Ok(format!( + r#"
+
People
+ {invited_html} + + + {rows} +
EmailName
+
+ + + +
+
"# + )) +} + +async fn mail_section(cx: &Cx) -> Result { + let smtp = settings::smtp(&app(cx).store).await?; + let password_note = if smtp.password.is_some() { + "password is set — fill to replace, leave empty to keep" + } else { + "no password set" + }; + Ok(format!( + r#"
+
Mail
+
Invites go out through this sender. The password is sealed under im.key; without a sender, invite links are shown here instead of mailed.
+
+ + + + + + +
+
+ +
+
"#, + escape(&smtp.host), + smtp.port, + escape(&smtp.username), + escape(&smtp.from) + )) +} + +async fn logs_section(cx: &Cx) -> Result { + let entries = events::list(&app(cx).store, 200).await?; + let mut rows = String::new(); + for event in &entries { + rows.push_str(&format!( + "{}{}{}{}", + escape(&event.at.format(&time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]:[second]")).unwrap_or_default()), + escape(&event.kind), + escape(event.actor.as_deref().unwrap_or("")), + escape(event.detail.as_deref().unwrap_or("")), + )); + } + Ok(format!( + r#"
+
Logs
+
Everything identity did, newest first. Introspection is not logged — it runs per request and would drown the rest.
+ + + {rows} +
WhenWhatWhoDetail
+
"# + )) +} + +// --------------------------------------------------------------------------- +// Handlers +// --------------------------------------------------------------------------- + +#[derive(Deserialize)] +struct InviteForm { + email: String, + admin: Option, +} + +#[route(POST "/admin/invite")] +async fn invite(cx: &Cx, Form(input): Form) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + let store = &app(cx).store; + let email = input.email.trim().to_string(); + let admin = input.admin.as_deref() == Some("yes"); + let token = accounts::create_invite(store, &email, Some(me.id.clone()), admin) + .await + .map_err(|e| topcoat::Error::from(std::io::Error::other(e.to_string())))?; + // Mailed when a sender is configured; shown once on the page otherwise. + let mailed = mailer::send_invite(store, &app(cx).config.issuer, &email, token.expose()) + .await + .is_ok(); + events::log( + store, + "invite_created", + Some(&me.email), + Some(&format!( + "for {email}{}", + if admin { " (admin)" } else { "" } + )), + ) + .await; + if mailed { + back(cx, "users", "&ok=invited") + } else { + let link = format!("{}/invite/{}", app(cx).config.issuer, token.expose()); + back( + cx, + "users", + &format!("&ok=invited&invited={}", crate::oidc::urlencode(&link)), + ) + } +} + +#[derive(Deserialize)] +struct UserAction { + user: String, +} + +#[route(POST "/admin/revoke")] +async fn revoke(cx: &Cx, Form(input): Form) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + let store = &app(cx).store; + let user_id = UserId::from(input.user); + let sessions = im_core::sessions::revoke_user_sessions(store, &user_id).await?; + let email = accounts::user_by_id(store, &user_id) + .await? + .map(|u| u.email); + events::log( + store, + "sessions_revoked", + Some(&me.email), + Some(&format!( + "{}: {sessions} session(s)", + email.as_deref().unwrap_or("unknown") + )), + ) + .await; + back(cx, "users", "&ok=revoked") +} + +#[route(POST "/admin/disable")] +async fn disable(cx: &Cx, Form(input): Form) -> Result { + set_disabled(cx, input, true).await +} + +#[route(POST "/admin/enable")] +async fn enable(cx: &Cx, Form(input): Form) -> Result { + set_disabled(cx, input, false).await +} + +async fn set_disabled(cx: &Cx, input: UserAction, disabled: bool) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + let store = &app(cx).store; + let user_id = UserId::from(input.user); + accounts::set_disabled(store, &user_id, disabled).await?; + if disabled { + // A disabled account keeps no sessions either. + im_core::sessions::revoke_user_sessions(store, &user_id).await?; + } + let email = accounts::user_by_id(store, &user_id) + .await? + .map(|u| u.email); + events::log( + store, + if disabled { + "user_disabled" + } else { + "user_enabled" + }, + Some(&me.email), + email.as_deref(), + ) + .await; + back( + cx, + "users", + if disabled { + "&ok=disabled" + } else { + "&ok=enabled" + }, + ) +} + +#[derive(Deserialize)] +struct SmtpForm { + host: String, + port: u16, + username: String, + password: Option, + from: String, +} + +#[route(POST "/admin/smtp")] +async fn smtp_save(cx: &Cx, Form(input): Form) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + let store = &app(cx).store; + let value = Smtp { + host: input.host.trim().to_string(), + port: input.port, + username: input.username.trim().to_string(), + from: input.from.trim().to_string(), + password: None, + }; + settings::set_smtp(store, &value, input.password.as_deref()).await?; + events::log(store, "smtp_updated", Some(&me.email), None).await; + back(cx, "mail", "&ok=smtp") +} + +#[route(POST "/admin/smtp_test")] +async fn smtp_test(cx: &Cx) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + match mailer::send_test(&app(cx).store, &me.email).await { + Ok(()) => { + events::log(&app(cx).store, "smtp_test_sent", Some(&me.email), None).await; + back(cx, "mail", "&ok=smtp_test") + } + Err(e) => { + events::log( + &app(cx).store, + "smtp_test_failed", + Some(&me.email), + Some(&e.to_string()), + ) + .await; + back(cx, "mail", "&error=smtp_test") + } + } +} diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index 0dedcd2..fd525bd 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -54,7 +54,8 @@ pub struct LoginForm { #[route(POST "/login")] async fn login(cx: &Cx, Form(input): Form) -> Redirect { let back = safe_back(input.back.as_deref().unwrap_or("/")).to_string(); - match accounts::verify_login(&server::app(cx).store, &input.email, &input.password).await { + let store = &server::app(cx).store; + match accounts::verify_login(store, &input.email, &input.password).await { Ok(user) if user.totp_confirmed => { let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Login, back); server::set_pending_cookie(cx, sealed); @@ -63,11 +64,17 @@ async fn login(cx: &Cx, Form(input): Form) -> Redirect { Ok(user) => { // Accounts enrol TOTP at invite time, so this is the path for one // created before that rule — sign it in, enrolment comes next. - let token = im_core::sessions::create_session(&server::app(cx).store, &user.id).await?; + let token = im_core::sessions::create_session(store, &user.id).await?; + im_core::events::log(store, "login_ok", Some(&user.email), None).await; server::set_session_cookie(cx, token.expose()); see(back) } - Err(_) => see(format!("/login?error=bad_login&back={}", urlencode(&back))), + Err(_) => { + // The failure is logged against the address tried, never the + // password — and never whether the address exists. + im_core::events::log(store, "login_fail", Some(&input.email), None).await; + see(format!("/login?error=bad_login&back={}", urlencode(&back))) + } } } @@ -101,9 +108,14 @@ async fn login_totp(cx: &Cx, Form(input): Form) -> Redirect { None => false, }; if !ok { + im_core::events::log(store, "totp_fail", None, Some("login")).await; return see("/login/totp?error=bad_code".to_string()); } let token = im_core::sessions::create_session(store, &user_id).await?; + let email = accounts::user_by_id(store, &user_id) + .await? + .map(|u| u.email); + im_core::events::log(store, "login_ok", email.as_deref(), Some("2fa")).await; server::clear_pending_cookie(cx); server::set_session_cookie(cx, token.expose()); see(pending.back) @@ -159,6 +171,7 @@ async fn invite(cx: &Cx, Form(input): Form) -> Redirect { im_core::totp::set_totp(store, &user.id, &secret).await?; let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, "/".to_string()); server::set_pending_cookie(cx, sealed); + im_core::events::log(store, "invite_accepted", Some(&user.email), None).await; see("/enroll".to_string()) } @@ -180,6 +193,10 @@ async fn enroll(cx: &Cx, Form(input): Form) -> Redirect { } im_core::totp::confirm_totp(store, &user_id).await?; let token = im_core::sessions::create_session(store, &user_id).await?; + let email = accounts::user_by_id(store, &user_id) + .await? + .map(|u| u.email); + im_core::events::log(store, "enrolled", email.as_deref(), None).await; server::clear_pending_cookie(cx); server::set_session_cookie(cx, token.expose()); see("/?ok=enrolled".to_string()) @@ -190,7 +207,11 @@ async fn enroll(cx: &Cx, Form(input): Form) -> Redirect { #[route(POST "/logout")] async fn logout(cx: &Cx) -> Redirect { if let Some(token) = server::presented_session(cx) { + let email = im_core::sessions::resolve_session(&server::app(cx).store, &token) + .await? + .map(|u| u.email); im_core::sessions::revoke_session(&server::app(cx).store, &token).await?; + im_core::events::log(&server::app(cx).store, "logout", email.as_deref(), None).await; } server::clear_session_cookie(cx); see("/".to_string()) diff --git a/crates/im-web/src/config.rs b/crates/im-web/src/config.rs index 38c3ef8..b47504d 100644 --- a/crates/im-web/src/config.rs +++ b/crates/im-web/src/config.rs @@ -1,6 +1,11 @@ //! `config/im.toml`: read before anything is opened, written with development //! defaults if it is not there yet — the same contract izlek-core's `Config` //! keeps. A broken key stops the boot with its name in the message. +//! +//! TOML holds deployment facts only — database, listen, issuer. Secrets an +//! admin rotates (the SMTP password) live sealed in the database under +//! `im.key`, set from the admin panel; nothing in this file is worth +//! stealing, which is what lets it stay in git. use std::path::{Path, PathBuf}; @@ -20,16 +25,6 @@ pub struct Config { /// The OIDC issuer — the public base URL every endpoint address and every /// `iss` claim derives from. pub issuer: String, - pub smtp: Option, -} - -#[derive(Clone, Deserialize)] -pub struct Smtp { - pub host: String, - pub port: u16, - pub username: String, - pub password: String, - pub from: String, } #[derive(Deserialize)] @@ -37,7 +32,6 @@ struct Raw { database: Option, listen: Option, issuer: Option, - smtp: Option, } impl Config { @@ -66,7 +60,6 @@ impl Config { .parse() .map_err(|e| format!("{PATH}: listen: {e}"))?, issuer: issuer.trim_end_matches('/').to_string(), - smtp: raw.smtp, }) } @@ -82,14 +75,6 @@ impl Config { format!("database {}", self.database.display()), format!("listen {}", self.listen), format!("issuer {}", self.issuer), - format!( - "mail {}", - if self.smtp.is_some() { - "smtp" - } else { - "stdout (dev)" - } - ), ] } } diff --git a/crates/im-web/src/mailer.rs b/crates/im-web/src/mailer.rs new file mode 100644 index 0000000..918e367 --- /dev/null +++ b/crates/im-web/src/mailer.rs @@ -0,0 +1,84 @@ +//! Sending mail with the sender the admin panel configured. The transport is +//! built per send: settings can change at any moment, and invites are rare — +//! the pool a long-lived transport would buy serves nothing here. + +use im_core::settings::{self, Smtp}; +use im_core::store::Store; + +#[derive(Debug, thiserror::Error)] +pub enum MailError { + #[error("no sender configured")] + NotConfigured, + #[error("mail: {0}")] + Backend(String), + #[error("settings: {0}")] + Settings(#[from] im_core::store::StoreError), +} + +pub type Result = std::result::Result; + +fn transport(smtp: &Smtp) -> Result> { + if !smtp.configured() { + return Err(MailError::NotConfigured); + } + let mut builder = lettre::AsyncSmtpTransport::::relay(&smtp.host) + .map_err(|e| MailError::Backend(e.to_string()))? + .port(smtp.port); + if !smtp.username.is_empty() { + builder = builder.credentials(lettre::transport::smtp::authentication::Credentials::new( + smtp.username.clone(), + smtp.password.clone().unwrap_or_default(), + )); + } + Ok(builder.build()) +} + +async fn send(store: &Store, to: &str, subject: &str, body: String) -> Result<()> { + let smtp = settings::smtp(store).await?; + let message = lettre::Message::builder() + .from( + smtp.from + .parse() + .map_err(|e| MailError::Backend(format!("smtp from: {e}")))?, + ) + .to(to + .parse() + .map_err(|e| MailError::Backend(format!("to: {e}")))?) + .subject(subject) + .body(body) + .map_err(|e| MailError::Backend(e.to_string()))?; + use lettre::AsyncTransport; + transport(&smtp)? + .send(message) + .await + .map_err(|e| MailError::Backend(e.to_string()))?; + Ok(()) +} + +/// The invite mail: the link is the whole payload. +pub async fn send_invite(store: &Store, issuer: &str, email: &str, token: &str) -> Result { + let link = format!("{issuer}/invite/{token}"); + send( + store, + email, + "You're invited", + format!( + "You've been invited. This link is yours for {} days:\n\n{link}\n", + im_core::accounts::INVITE_DAYS + ), + ) + .await?; + Ok(link) +} + +/// The panel's test button: proves the sender end to end, to the admin's own +/// address. +pub async fn send_test(store: &Store, to: &str) -> Result<()> { + send( + store, + to, + "im mail test", + "im can send mail from this sender.\n".into(), + ) + .await +} diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index 613a0a4..39f6510 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -1,5 +1,6 @@ -//! im — the IzlekLab SSO. Server by default; `invite` and `create-client` -//! are the admin surface until there is a settings screen. +//! im — the IzlekLab 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; @@ -9,9 +10,11 @@ use topcoat::asset::RouterBuilderAssetExt; use topcoat::cookie::RouterBuilderCookieExt; use topcoat::router::{Router, RouterBuilderDiscoverExt, route}; +mod admin; mod auth; mod config; mod layout; +mod mailer; mod oidc; mod pages; mod server; @@ -37,11 +40,31 @@ async fn main() { 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 invite "); + eprintln!("usage: im-web revoke "); std::process::exit(2); }; - invite(config, email).await; + revoke(config, email).await; } Some("create-client") => { let (Some(name), uris) = (args.get(2), args.get(3..).unwrap_or(&[])) else { @@ -56,7 +79,7 @@ async fn main() { } Some(other) => { eprintln!( - "im: unknown command {other:?} (expected: invite, create-client, or none to serve)" + "im: unknown command {other:?} (expected: invite, revoke, create-client, or none to serve)" ); std::process::exit(2); } @@ -71,44 +94,54 @@ async fn open_store(config: &Config) -> Arc { ) } -/// `im-web invite `: creates the invite, mails it when SMTP is -/// configured, prints the link otherwise (dev mode). -async fn invite(config: Config, email: &str) { +/// `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 = im_core::accounts::create_invite(&store, email, None) + let token = im_core::accounts::create_invite(&store, email, None, admin) .await .expect("failed to create the invite"); - let link = format!("{}/invite/{}", config.issuer, token.expose()); - match build_mailer(&config) { - Some(mailer) => { - let message = lettre::Message::builder() - .from( - config - .smtp - .as_ref() - .unwrap() - .from - .parse() - .expect("smtp.from"), - ) - .to(email.parse().expect("invite email")) - .subject("You're invited") - .body(format!( - "You've been invited. This link is yours for {} days:\n\n{link}\n", - im_core::accounts::INVITE_DAYS - )) - .expect("invite mail"); - use lettre::AsyncTransport; - mailer - .send(message) - .await - .expect("failed to send the invite"); - println!("im invite mailed to {email}"); - } - None => println!("im invite for {email}: {link}"), + 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]) { @@ -122,21 +155,6 @@ async fn create_client(config: Config, name: &str, uris: &[String]) { println!(" (the secret is shown once; its digest is all the database keeps)"); } -fn build_mailer(config: &Config) -> Option> { - let smtp = config.smtp.as_ref()?; - let creds = lettre::transport::smtp::authentication::Credentials::new( - smtp.username.clone(), - smtp.password.clone(), - ); - Some( - lettre::AsyncSmtpTransport::::relay(&smtp.host) - .expect("smtp relay") - .port(smtp.port) - .credentials(creds) - .build(), - ) -} - async fn serve(config: Config) { for line in config.report() { println!("im {line}"); diff --git a/crates/im-web/src/oidc.rs b/crates/im-web/src/oidc.rs index 902f2af..bd41993 100644 --- a/crates/im-web/src/oidc.rs +++ b/crates/im-web/src/oidc.rs @@ -81,7 +81,7 @@ fn bad_request(cx: &Cx) -> Result { /// Percent-encodes a value for a query pair — the `back` a login carries is /// a local `/authorize?...` URL, full of `?&=` of its own. -fn urlencode(raw: &str) -> String { +pub(crate) fn urlencode(raw: &str) -> String { let mut out = String::with_capacity(raw.len()); for byte in raw.bytes() { match byte { @@ -228,13 +228,22 @@ async fn mint_tokens( )) } -fn token_answer(cx: &Cx, access: String, id: String, refresh: String) -> Result { +fn token_answer( + cx: &Cx, + access: String, + id: String, + refresh: String, + app_session: Option, +) -> Result { Json(serde_json::json!({ "access_token": access, "token_type": "Bearer", "expires_in": oidc::TOKEN_SECONDS, "refresh_token": refresh, "id_token": id, + // Not OIDC — ours: the opaque, introspected session im-client holds. + // Standard clients ignore it; ours never leaves its ghost window. + "app_session": app_session, })) .into_response(cx) } @@ -286,7 +295,27 @@ async fn exchange(cx: &Cx, Form(input): Form) -> Result { &consumed.session_hash, ) .await?; - token_answer(cx, access, id, refresh.expose().to_string()) + let app_session = oidc::issue_app_session( + &app(cx).store, + &user.id, + &client.client_id, + &consumed.session_hash, + ) + .await?; + im_core::events::log( + &app(cx).store, + "code_exchanged", + Some(&user.email), + Some(&format!("via {}", client.name)), + ) + .await; + token_answer( + cx, + access, + id, + refresh.expose().to_string(), + Some(app_session.expose().to_string()), + ) } "refresh_token" => { let Some(presented) = input.refresh_token else { @@ -306,12 +335,43 @@ async fn exchange(cx: &Cx, Form(input): Form) -> Result { return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant"); } let (access, id) = mint_tokens(cx, &user, &client.client_id, None).await?; - token_answer(cx, access, id, fresh.expose().to_string()) + token_answer(cx, access, id, fresh.expose().to_string(), None) } _ => oidc_error(cx, StatusCode::BAD_REQUEST, "unsupported_grant_type"), } } +// --------------------------------------------------------------------------- +// /introspect (RFC 7662): the per-request liveness check im-client makes +// --------------------------------------------------------------------------- + +#[derive(Deserialize)] +struct IntrospectForm { + token: String, + client_id: Option, + client_secret: Option, +} + +/// The app asks, per request: is this session alive, and whose is it? The +/// answer is never cached server-side, so a revoked user is inactive on the +/// very next call. +#[route(POST "/introspect")] +async fn introspect(cx: &Cx, Form(input): Form) -> Result { + let (Some(client_id), Some(secret)) = (input.client_id, input.client_secret) else { + return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client"); + }; + let Some(client) = oidc::client_by_id(&app(cx).store, &client_id).await? else { + return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client"); + }; + if !oidc::verify_client_secret(&client, &secret) { + return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client"); + } + let answer = oidc::introspect_app_session(&app(cx).store, &input.token, &client_id) + .await? + .unwrap_or_else(|| serde_json::json!({ "active": false })); + Json(answer).into_response(cx) +} + // --------------------------------------------------------------------------- // /userinfo // --------------------------------------------------------------------------- diff --git a/crates/im-web/src/pages.rs b/crates/im-web/src/pages.rs index e760bb2..2b9c9ef 100644 --- a/crates/im-web/src/pages.rs +++ b/crates/im-web/src/pages.rs @@ -408,6 +408,9 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { "Sign out everywhere" + if user.admin { + "Admin panel" + } diff --git a/style/main.scss b/style/main.scss index 763d961..5fa4820 100644 --- a/style/main.scss +++ b/style/main.scss @@ -372,3 +372,149 @@ body:has(.auth-stage) { @media (max-width: 720px) { .auth-stage { padding: 0 16px 24px; } } + +// --- Admin panel ------------------------------------------------------------ +// Same skin, different posture: top-anchored and wider than the auth stage — +// a tool, not a gate. + +body:has(.admin-shell) { + min-height: 100vh; + min-height: 100dvh; +} + +.admin-shell { + display: flex; + justify-content: center; + padding: 24px 24px 48px; +} + +.admin-column { + width: 760px; + max-width: 100%; + display: flex; + flex-direction: column; + gap: 16px; +} + +.admin-bar { + display: flex; + align-items: center; + gap: 20px; + height: var(--control-h-lg); + + .wordmark-text { font-size: 15px; } +} + +.admin-tabs { + display: flex; + gap: 16px; +} + +.admin-nav { + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); + text-decoration: none; + padding-bottom: 2px; + + &:hover { color: var(--ink); } + + &-on { + color: var(--ink); + box-shadow: inset 0 -2px 0 var(--ink); + } +} + +.admin-bar .auth-alt { margin-left: auto; align-self: auto; } + +.admin-card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + padding: 24px; + display: flex; + flex-direction: column; + gap: 16px; +} + +.admin-table { + width: 100%; + border-collapse: collapse; + font-size: 13px; + + th { + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + color: var(--muted-soft); + text-align: left; + padding: 0 12px 6px 0; + } + + td { + padding: 8px 12px 8px 0; + border-top: 1px solid var(--border-soft); + vertical-align: middle; + } +} + +.mono { font-family: var(--font-mono); } +.muted { color: var(--muted); } + +.actions { + display: flex; + gap: 8px; + justify-content: flex-end; + + form { display: inline; } +} + +// A quiet row-level button, back on --surface like İzlek's `.quiet`. +.admin-action { + height: var(--control-h); + --control-h: 32px; + padding: 0 10px; + background: var(--surface); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + color: var(--ink); + font-size: 12px; + cursor: pointer; + + &:hover { background: var(--row-hover, var(--panel-sunken)); } +} + +.admin-action-wide { width: 100%; } + +.admin-invite { + display: flex; + gap: 8px; + align-items: center; + + .auth-input { flex: 1; } + .admin-action-wide { width: auto; padding: 0 20px; } +} + +.admin-check { + display: flex; + align-items: center; + gap: 6px; + font-size: 12px; + color: var(--muted); + white-space: nowrap; +} + +.admin-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +input[type="checkbox"] { accent-color: var(--accent); } + +@media (max-width: 720px) { + .admin-shell { padding: 16px 12px 32px; } + .admin-invite { flex-wrap: wrap; } +}