Server-side sessions with instant revocation, admin panel, sealed mail settings
Browse files at this commit963c897e7b4a04497b86197cd0f6fd038b2bf342Parent: d7200e0- feat
- server-side sessions with instant revocation, admin panel, sealed mail settings
20 changed files +1626 -173
- Cargo.toml +1 -0
- crates/im-client/src/lib.rs +62 -70
- crates/im-core/src/accounts.rs +82 -18
- crates/im-core/src/events.rs +82 -0
- crates/im-core/src/lib.rs +4 -0
- crates/im-core/src/model.rs +5 -0
- crates/im-core/src/oidc.rs +142 -1
- crates/im-core/src/sessions.rs +62 -4
- crates/im-core/src/settings.rs +172 -0
- crates/im-core/src/store.rs +22 -0
- crates/im-core/src/totp.rs +1 -1
- crates/im-web/assets/main.css +161 -0
- crates/im-web/src/admin.rs +434 -0
- crates/im-web/src/auth.rs +24 -3
- crates/im-web/src/config.rs +5 -20
- crates/im-web/src/mailer.rs +84 -0
- crates/im-web/src/main.rs +70 -52
- crates/im-web/src/oidc.rs +64 -4
- crates/im-web/src/pages.rs +3 -0
- style/main.scss +146 -0
Cargo.tomlmodified+1 -0
| @@ -10,6 +10,7 @@ members = [ | |||
| 10 | [workspace.package] | 10 | [workspace.package] |
| 11 | version = "0.1.0" | 11 | version = "0.1.0" |
| 12 | edition = "2024" | 12 | edition = "2024" |
| 13 | +license = "AGPL-3.0-or-later" | ||
| 13 | repository = "https://github.com/DizeyLab/im" | 14 | repository = "https://github.com/DizeyLab/im" |
| 14 | 15 | ||
| 15 | [workspace.dependencies] | 16 | [workspace.dependencies] |
crates/im-client/src/lib.rsmodified+62 -70
| @@ -91,27 +91,58 @@ fn client(cx: &Cx) -> &ImClient { | |||
| 91 | try_app_context::<ImClient>(cx).expect("im_client::mount was called on the router") | 91 | try_app_context::<ImClient>(cx).expect("im_client::mount was called on the router") |
| 92 | } | 92 | } |
| 93 | 93 | ||
| 94 | -/// The authenticated person, if this browser has one. Transparently refreshes | 94 | +/// The authenticated person, if this browser has one. Every call asks im: |
| 95 | -/// against im when the access token has aged out; `None` means signed out. | 95 | +/// the cookie holds an opaque session token, introspected per request, so an |
| 96 | +/// admin revoking the person signs them out of this app immediately — there | ||
| 97 | +/// is no token-validity window in which a ghost lives. | ||
| 96 | pub async fn current_user(cx: &Cx) -> Option<User> { | 98 | pub async fn current_user(cx: &Cx) -> Option<User> { |
| 97 | let state = client(cx); | 99 | let state = client(cx); |
| 98 | let sealed = cookies(cx).get(&state.config.cookie_name)?; | 100 | let sealed = cookies(cx).get(&state.config.cookie_name)?; |
| 99 | - let mut session: Session = open_json(&state.config.cookie_key, sealed.value())?; | 101 | + let session: Session = open_json(&state.config.cookie_key, sealed.value())?; |
| 100 | - if session.access_exp > OffsetDateTime::now_utc().unix_timestamp() { | 102 | + if session.exp <= OffsetDateTime::now_utc().unix_timestamp() { |
| 101 | - return Some(session.user()); | 103 | + clear_cookie(cx, &state.config.cookie_name); |
| 104 | + return None; | ||
| 102 | } | 105 | } |
| 103 | - match refresh(cx, state, &mut session).await { | 106 | + match introspect(state, &session.app_session).await { |
| 104 | - Ok(()) => { | 107 | + Some((user, _exp)) => Some(user), |
| 105 | - set_session_cookie(cx, state, &session); | 108 | + None => { |
| 106 | - Some(session.user()) | ||
| 107 | - } | ||
| 108 | - Err(_) => { | ||
| 109 | clear_cookie(cx, &state.config.cookie_name); | 109 | clear_cookie(cx, &state.config.cookie_name); |
| 110 | None | 110 | None |
| 111 | } | 111 | } |
| 112 | } | 112 | } |
| 113 | } | 113 | } |
| 114 | 114 | ||
| 115 | +/// POSTs the session token to im's `/introspect` with this app's credentials. | ||
| 116 | +/// Network failure reads as signed-out for this request — the cookie stays, | ||
| 117 | +/// so the next request tries again. | ||
| 118 | +async fn introspect(state: &ImClient, token: &str) -> Option<(User, i64)> { | ||
| 119 | + let answer: serde_json::Value = state | ||
| 120 | + .http | ||
| 121 | + .post(format!("{}/introspect", state.config.issuer)) | ||
| 122 | + .form(&[ | ||
| 123 | + ("token", token), | ||
| 124 | + ("client_id", &state.config.client_id), | ||
| 125 | + ("client_secret", &state.config.client_secret), | ||
| 126 | + ]) | ||
| 127 | + .send() | ||
| 128 | + .await | ||
| 129 | + .ok()? | ||
| 130 | + .json() | ||
| 131 | + .await | ||
| 132 | + .ok()?; | ||
| 133 | + if answer["active"] != true { | ||
| 134 | + return None; | ||
| 135 | + } | ||
| 136 | + Some(( | ||
| 137 | + User { | ||
| 138 | + sub: answer["sub"].as_str()?.to_string(), | ||
| 139 | + email: answer["email"].as_str()?.to_string(), | ||
| 140 | + name: answer["name"].as_str()?.to_string(), | ||
| 141 | + }, | ||
| 142 | + answer["exp"].as_i64()?, | ||
| 143 | + )) | ||
| 144 | +} | ||
| 145 | + | ||
| 115 | /// Who this browser is, from the claims. | 146 | /// Who this browser is, from the claims. |
| 116 | #[derive(Debug, Clone, Serialize, Deserialize)] | 147 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 117 | pub struct User { | 148 | pub struct User { |
| @@ -126,15 +157,10 @@ pub struct User { | |||
| 126 | 157 | ||
| 127 | #[derive(Serialize, Deserialize)] | 158 | #[derive(Serialize, Deserialize)] |
| 128 | struct Session { | 159 | struct Session { |
| 129 | - user: User, | 160 | + /// The opaque token im issued at the code exchange; introspected per |
| 130 | - refresh_token: String, | 161 | + /// request, never trusted on its own. |
| 131 | - access_exp: i64, | 162 | + app_session: String, |
| 132 | -} | 163 | + exp: i64, |
| 133 | - | ||
| 134 | -impl Session { | ||
| 135 | - fn user(&self) -> User { | ||
| 136 | - self.user.clone() | ||
| 137 | - } | ||
| 138 | } | 164 | } |
| 139 | 165 | ||
| 140 | /// The in-flight login: PKCE verifier, state, nonce, and where to land after. | 166 | /// The in-flight login: PKCE verifier, state, nonce, and where to land after. |
| @@ -394,13 +420,12 @@ fn urlencoded(raw: &str) -> String { | |||
| 394 | 420 | ||
| 395 | #[derive(Deserialize)] | 421 | #[derive(Deserialize)] |
| 396 | struct TokenAnswer { | 422 | struct TokenAnswer { |
| 397 | - /// Present on the wire; the app reads identity from the id_token and | 423 | + /// Validated for its nonce and signature; the identity the app serves |
| 398 | - /// never calls userinfo, so the access token is carried, not used. | 424 | + /// comes from introspection, not from these claims. |
| 399 | - #[serde(rename = "access_token")] | ||
| 400 | - _access_token: String, | ||
| 401 | - refresh_token: String, | ||
| 402 | id_token: String, | 425 | id_token: String, |
| 403 | - expires_in: i64, | 426 | + /// Not OIDC — im's own: the opaque session this crate introspects per |
| 427 | + /// request. Absent means the issuer is not a current im. | ||
| 428 | + app_session: Option<String>, | ||
| 404 | } | 429 | } |
| 405 | 430 | ||
| 406 | async fn exchange_code(state: &ImClient, code: &str, flight: &InFlight) -> Result<Session> { | 431 | async fn exchange_code(state: &ImClient, code: &str, flight: &InFlight) -> Result<Session> { |
| @@ -427,43 +452,15 @@ async fn exchange_code(state: &ImClient, code: &str, flight: &InFlight) -> Resul | |||
| 427 | if claims["nonce"].as_str() != Some(flight.nonce.as_str()) { | 452 | if claims["nonce"].as_str() != Some(flight.nonce.as_str()) { |
| 428 | return Err(Error::Token("nonce mismatch".into())); | 453 | return Err(Error::Token("nonce mismatch".into())); |
| 429 | } | 454 | } |
| 430 | - Ok(session_from(&answer, claims)) | 455 | + let app_session = answer |
| 431 | -} | 456 | + .app_session |
| 432 | - | 457 | + .ok_or_else(|| Error::Token("issuer gave no app session".into()))?; |
| 433 | -async fn refresh(cx: &Cx, state: &ImClient, session: &mut Session) -> Result<()> { | 458 | + // The session's expiry and identity come from a live introspection, not |
| 434 | - let _ = cx; | 459 | + // from the token answer — the same check every later request will make. |
| 435 | - let answer: TokenAnswer = state | 460 | + let (_user, exp) = introspect(state, &app_session) |
| 436 | - .http | ||
| 437 | - .post(format!("{}/token", state.config.issuer)) | ||
| 438 | - .form(&[ | ||
| 439 | - ("grant_type", "refresh_token"), | ||
| 440 | - ("refresh_token", &session.refresh_token), | ||
| 441 | - ("client_id", &state.config.client_id), | ||
| 442 | - ("client_secret", &state.config.client_secret), | ||
| 443 | - ]) | ||
| 444 | - .send() | ||
| 445 | - .await | ||
| 446 | - .map_err(|e| Error::Http(e.to_string()))? | ||
| 447 | - .error_for_status() | ||
| 448 | - .map_err(|e| Error::Refused(e.to_string()))? | ||
| 449 | - .json() | ||
| 450 | .await | 461 | .await |
| 451 | - .map_err(|e| Error::Http(e.to_string()))?; | 462 | + .ok_or_else(|| Error::Refused("fresh app session does not introspect".into()))?; |
| 452 | - let claims = validate_id_token(state, &answer.id_token).await?; | 463 | + Ok(Session { app_session, exp }) |
| 453 | - *session = session_from(&answer, claims); | ||
| 454 | - Ok(()) | ||
| 455 | -} | ||
| 456 | - | ||
| 457 | -fn session_from(answer: &TokenAnswer, claims: serde_json::Value) -> Session { | ||
| 458 | - Session { | ||
| 459 | - user: User { | ||
| 460 | - sub: claims["sub"].as_str().unwrap_or_default().to_string(), | ||
| 461 | - email: claims["email"].as_str().unwrap_or_default().to_string(), | ||
| 462 | - name: claims["name"].as_str().unwrap_or_default().to_string(), | ||
| 463 | - }, | ||
| 464 | - refresh_token: answer.refresh_token.clone(), | ||
| 465 | - access_exp: OffsetDateTime::now_utc().unix_timestamp() + answer.expires_in, | ||
| 466 | - } | ||
| 467 | } | 464 | } |
| 468 | 465 | ||
| 469 | /// Validates an id_token: RS256 against im's JWKS, issuer, audience, expiry. | 466 | /// Validates an id_token: RS256 against im's JWKS, issuer, audience, expiry. |
| @@ -693,17 +690,12 @@ mod tests { | |||
| 693 | fn cookie_seal_roundtrip() { | 690 | fn cookie_seal_roundtrip() { |
| 694 | let key = [7u8; 32]; | 691 | let key = [7u8; 32]; |
| 695 | let session = Session { | 692 | let session = Session { |
| 696 | - user: User { | 693 | + app_session: "opaque-token".into(), |
| 697 | - sub: "u".into(), | 694 | + exp: 1, |
| 698 | - email: "e".into(), | ||
| 699 | - name: "n".into(), | ||
| 700 | - }, | ||
| 701 | - refresh_token: "r".into(), | ||
| 702 | - access_exp: 1, | ||
| 703 | }; | 695 | }; |
| 704 | let sealed = seal_json(&key, &session); | 696 | let sealed = seal_json(&key, &session); |
| 705 | let back: Session = open_json(&key, &sealed).unwrap(); | 697 | let back: Session = open_json(&key, &sealed).unwrap(); |
| 706 | - assert_eq!(back.refresh_token, "r"); | 698 | + assert_eq!(back.app_session, "opaque-token"); |
| 707 | assert!(open_json::<Session>(&[8u8; 32], &sealed).is_none()); | 699 | assert!(open_json::<Session>(&[8u8; 32], &sealed).is_none()); |
| 708 | assert!(open_json::<Session>(&key, "garbage").is_none()); | 700 | assert!(open_json::<Session>(&key, "garbage").is_none()); |
| 709 | } | 701 | } |
crates/im-core/src/accounts.rsmodified+82 -18
| @@ -226,6 +226,7 @@ pub async fn create_invite( | |||
| 226 | store: &Store, | 226 | store: &Store, |
| 227 | email: &str, | 227 | email: &str, |
| 228 | invited_by: Option<UserId>, | 228 | invited_by: Option<UserId>, |
| 229 | + admin: bool, | ||
| 229 | ) -> std::result::Result<Token, AccountError> { | 230 | ) -> std::result::Result<Token, AccountError> { |
| 230 | let token = Token::mint(); | 231 | let token = Token::mint(); |
| 231 | let now = store::now(); | 232 | let now = store::now(); |
| @@ -233,12 +234,13 @@ pub async fn create_invite( | |||
| 233 | store | 234 | store |
| 234 | .conn | 235 | .conn |
| 235 | .execute( | 236 | .execute( |
| 236 | - "INSERT INTO invites (token, email, invited_by, created_at, expires_at) \ | 237 | + "INSERT INTO invites (token, email, invited_by, admin, created_at, expires_at) \ |
| 237 | - VALUES (?1, ?2, ?3, ?4, ?5)", | 238 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", |
| 238 | turso::params![ | 239 | turso::params![ |
| 239 | token.hash(), | 240 | token.hash(), |
| 240 | email, | 241 | email, |
| 241 | invited_by.map(|id| id.to_string()), | 242 | invited_by.map(|id| id.to_string()), |
| 243 | + admin as i64, | ||
| 242 | store::stamp(now)?, | 244 | store::stamp(now)?, |
| 243 | store::stamp(expires)?, | 245 | store::stamp(expires)?, |
| 244 | ], | 246 | ], |
| @@ -254,7 +256,7 @@ pub async fn invite_by_token(store: &Store, token: &str) -> Result<Option<Invite | |||
| 254 | let mut rows = store | 256 | let mut rows = store |
| 255 | .conn | 257 | .conn |
| 256 | .query( | 258 | .query( |
| 257 | - "SELECT email, invited_by, created_at, expires_at, accepted_at \ | 259 | + "SELECT email, invited_by, admin, created_at, expires_at, accepted_at \ |
| 258 | FROM invites WHERE token = ?1", | 260 | FROM invites WHERE token = ?1", |
| 259 | turso::params![hash_token(token)], | 261 | turso::params![hash_token(token)], |
| 260 | ) | 262 | ) |
| @@ -266,9 +268,10 @@ pub async fn invite_by_token(store: &Store, token: &str) -> Result<Option<Invite | |||
| 266 | Ok(Some(Invite { | 268 | Ok(Some(Invite { |
| 267 | email: store::text(&row, 0)?, | 269 | email: store::text(&row, 0)?, |
| 268 | invited_by: store::opt_text(&row, 1)?.map(UserId::from), | 270 | invited_by: store::opt_text(&row, 1)?.map(UserId::from), |
| 269 | - created_at: store::parse_stamp(&store::text(&row, 2)?)?, | 271 | + admin: store::int(&row, 2)? != 0, |
| 270 | - expires_at: store::parse_stamp(&store::text(&row, 3)?)?, | 272 | + created_at: store::parse_stamp(&store::text(&row, 3)?)?, |
| 271 | - accepted_at: match store::opt_text(&row, 4)? { | 273 | + expires_at: store::parse_stamp(&store::text(&row, 4)?)?, |
| 274 | + accepted_at: match store::opt_text(&row, 5)? { | ||
| 272 | Some(raw) => Some(store::parse_stamp(&raw)?), | 275 | Some(raw) => Some(store::parse_stamp(&raw)?), |
| 273 | None => None, | 276 | None => None, |
| 274 | }, | 277 | }, |
| @@ -299,6 +302,7 @@ pub async fn create_user_from_invite( | |||
| 299 | email: invite.email.clone(), | 302 | email: invite.email.clone(), |
| 300 | name: name.to_string(), | 303 | name: name.to_string(), |
| 301 | totp_confirmed: false, | 304 | totp_confirmed: false, |
| 305 | + admin: invite.admin, | ||
| 302 | disabled: false, | 306 | disabled: false, |
| 303 | created_at: store::now(), | 307 | created_at: store::now(), |
| 304 | }; | 308 | }; |
| @@ -313,13 +317,14 @@ pub async fn create_user_from_invite( | |||
| 313 | store | 317 | store |
| 314 | .conn | 318 | .conn |
| 315 | .execute( | 319 | .execute( |
| 316 | - "INSERT INTO users (id, email, name, password_hash, created_at) \ | 320 | + "INSERT INTO users (id, email, name, password_hash, admin, created_at) \ |
| 317 | - VALUES (?1, ?2, ?3, ?4, ?5)", | 321 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", |
| 318 | turso::params![ | 322 | turso::params![ |
| 319 | user.id.to_string(), | 323 | user.id.to_string(), |
| 320 | user.email.clone(), | 324 | user.email.clone(), |
| 321 | user.name.clone(), | 325 | user.name.clone(), |
| 322 | password_hash, | 326 | password_hash, |
| 327 | + user.admin as i64, | ||
| 323 | store::stamp(user.created_at)?, | 328 | store::stamp(user.created_at)?, |
| 324 | ], | 329 | ], |
| 325 | ) | 330 | ) |
| @@ -366,7 +371,7 @@ pub async fn verify_login( | |||
| 366 | let mut rows = store | 371 | let mut rows = store |
| 367 | .conn | 372 | .conn |
| 368 | .query( | 373 | .query( |
| 369 | - "SELECT id, email, name, password_hash, totp_confirmed, disabled, created_at \ | 374 | + "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at \ |
| 370 | FROM users WHERE email = ?1 COLLATE NOCASE", | 375 | FROM users WHERE email = ?1 COLLATE NOCASE", |
| 371 | turso::params![email], | 376 | turso::params![email], |
| 372 | ) | 377 | ) |
| @@ -381,8 +386,9 @@ pub async fn verify_login( | |||
| 381 | email: store::text(&row, 1)?, | 386 | email: store::text(&row, 1)?, |
| 382 | name: store::text(&row, 2)?, | 387 | name: store::text(&row, 2)?, |
| 383 | totp_confirmed: store::int(&row, 4)? != 0, | 388 | totp_confirmed: store::int(&row, 4)? != 0, |
| 384 | - disabled: store::int(&row, 5)? != 0, | 389 | + admin: store::int(&row, 5)? != 0, |
| 385 | - created_at: store::parse_stamp(&store::text(&row, 6)?)?, | 390 | + disabled: store::int(&row, 6)? != 0, |
| 391 | + created_at: store::parse_stamp(&store::text(&row, 7)?)?, | ||
| 386 | }; | 392 | }; |
| 387 | let phc = store::text(&row, 3)?; | 393 | let phc = store::text(&row, 3)?; |
| 388 | if !verify_password(password, &phc) || user.disabled { | 394 | if !verify_password(password, &phc) || user.disabled { |
| @@ -391,12 +397,28 @@ pub async fn verify_login( | |||
| 391 | Ok(user) | 397 | Ok(user) |
| 392 | } | 398 | } |
| 393 | 399 | ||
| 394 | -/// Looks a user up by id — what sessions and tokens resolve to. | 400 | +/// Looks a user up by email — the CLI's revoke path resolves names this way. |
| 401 | +pub async fn user_by_email(store: &Store, email: &str) -> Result<Option<User>> { | ||
| 402 | + let mut rows = store | ||
| 403 | + .conn | ||
| 404 | + .query( | ||
| 405 | + "SELECT id FROM users WHERE email = ?1 COLLATE NOCASE", | ||
| 406 | + turso::params![email], | ||
| 407 | + ) | ||
| 408 | + .await | ||
| 409 | + .map_err(backend)?; | ||
| 410 | + let Some(row) = rows.next().await.map_err(backend)? else { | ||
| 411 | + return Ok(None); | ||
| 412 | + }; | ||
| 413 | + let id = UserId::from(store::text(&row, 0)?); | ||
| 414 | + user_by_id(store, &id).await | ||
| 415 | +} | ||
| 416 | + | ||
| 395 | pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> { | 417 | pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> { |
| 396 | let mut rows = store | 418 | let mut rows = store |
| 397 | .conn | 419 | .conn |
| 398 | .query( | 420 | .query( |
| 399 | - "SELECT id, email, name, totp_confirmed, disabled, created_at \ | 421 | + "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \ |
| 400 | FROM users WHERE id = ?1", | 422 | FROM users WHERE id = ?1", |
| 401 | turso::params![id.to_string()], | 423 | turso::params![id.to_string()], |
| 402 | ) | 424 | ) |
| @@ -410,11 +432,53 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> { | |||
| 410 | email: store::text(&row, 1)?, | 432 | email: store::text(&row, 1)?, |
| 411 | name: store::text(&row, 2)?, | 433 | name: store::text(&row, 2)?, |
| 412 | totp_confirmed: store::int(&row, 3)? != 0, | 434 | totp_confirmed: store::int(&row, 3)? != 0, |
| 413 | - disabled: store::int(&row, 4)? != 0, | 435 | + admin: store::int(&row, 4)? != 0, |
| 414 | - created_at: store::parse_stamp(&store::text(&row, 5)?)?, | 436 | + disabled: store::int(&row, 5)? != 0, |
| 437 | + created_at: store::parse_stamp(&store::text(&row, 6)?)?, | ||
| 415 | })) | 438 | })) |
| 416 | } | 439 | } |
| 417 | 440 | ||
| 441 | +/// Every user, oldest first — the admin panel's roster. | ||
| 442 | +pub async fn list_users(store: &Store) -> Result<Vec<User>> { | ||
| 443 | + let mut rows = store | ||
| 444 | + .conn | ||
| 445 | + .query( | ||
| 446 | + "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \ | ||
| 447 | + FROM users ORDER BY created_at", | ||
| 448 | + (), | ||
| 449 | + ) | ||
| 450 | + .await | ||
| 451 | + .map_err(backend)?; | ||
| 452 | + let mut users = Vec::new(); | ||
| 453 | + while let Some(row) = rows.next().await.map_err(backend)? { | ||
| 454 | + users.push(User { | ||
| 455 | + id: UserId::from(store::text(&row, 0)?), | ||
| 456 | + email: store::text(&row, 1)?, | ||
| 457 | + name: store::text(&row, 2)?, | ||
| 458 | + totp_confirmed: store::int(&row, 3)? != 0, | ||
| 459 | + admin: store::int(&row, 4)? != 0, | ||
| 460 | + disabled: store::int(&row, 5)? != 0, | ||
| 461 | + created_at: store::parse_stamp(&store::text(&row, 6)?)?, | ||
| 462 | + }); | ||
| 463 | + } | ||
| 464 | + Ok(users) | ||
| 465 | +} | ||
| 466 | + | ||
| 467 | +/// Enables or disables an account. A disabled account cannot log in, its | ||
| 468 | +/// sessions resolve to nobody, and introspection says inactive — every door | ||
| 469 | +/// closes on the same flag. | ||
| 470 | +pub async fn set_disabled(store: &Store, user: &UserId, disabled: bool) -> Result<()> { | ||
| 471 | + store | ||
| 472 | + .conn | ||
| 473 | + .execute( | ||
| 474 | + "UPDATE users SET disabled = ?1 WHERE id = ?2", | ||
| 475 | + turso::params![disabled as i64, user.to_string()], | ||
| 476 | + ) | ||
| 477 | + .await | ||
| 478 | + .map_err(backend)?; | ||
| 479 | + Ok(()) | ||
| 480 | +} | ||
| 481 | + | ||
| 418 | #[cfg(test)] | 482 | #[cfg(test)] |
| 419 | mod tests { | 483 | mod tests { |
| 420 | use super::*; | 484 | use super::*; |
| @@ -455,7 +519,7 @@ mod tests { | |||
| 455 | #[tokio::test] | 519 | #[tokio::test] |
| 456 | async fn invite_to_user_to_login() { | 520 | async fn invite_to_user_to_login() { |
| 457 | let store = fixture().await; | 521 | let store = fixture().await; |
| 458 | - let token = create_invite(&store, "ann@example.com", None) | 522 | + let token = create_invite(&store, "ann@example.com", None, false) |
| 459 | .await | 523 | .await |
| 460 | .unwrap(); | 524 | .unwrap(); |
| 461 | let invite = invite_by_token(&store, token.expose()) | 525 | let invite = invite_by_token(&store, token.expose()) |
| @@ -493,13 +557,13 @@ mod tests { | |||
| 493 | #[tokio::test] | 557 | #[tokio::test] |
| 494 | async fn duplicate_email_is_refused() { | 558 | async fn duplicate_email_is_refused() { |
| 495 | let store = fixture().await; | 559 | let store = fixture().await; |
| 496 | - let first = create_invite(&store, "ann@example.com", None) | 560 | + let first = create_invite(&store, "ann@example.com", None, false) |
| 497 | .await | 561 | .await |
| 498 | .unwrap(); | 562 | .unwrap(); |
| 499 | create_user_from_invite(&store, first.expose(), "Ann", "tDLr9!mZQ2xv") | 563 | create_user_from_invite(&store, first.expose(), "Ann", "tDLr9!mZQ2xv") |
| 500 | .await | 564 | .await |
| 501 | .unwrap(); | 565 | .unwrap(); |
| 502 | - let second = create_invite(&store, "ann@example.com", None) | 566 | + let second = create_invite(&store, "ann@example.com", None, false) |
| 503 | .await | 567 | .await |
| 504 | .unwrap(); | 568 | .unwrap(); |
| 505 | assert!(matches!( | 569 | assert!(matches!( |
crates/im-core/src/events.rsadded+82 -0
| @@ -0,0 +1,82 @@ | |||
| 1 | +//! The audit log: one row per thing that happened to identity — logins, | ||
| 2 | +//! refusals, invites, enrolments, revocations. The admin panel's Logs | ||
| 3 | +//! section reads it; nothing here is a hot path (introspection is | ||
| 4 | +//! deliberately NOT logged — it runs per request and would drown the rest). | ||
| 5 | + | ||
| 6 | +use crate::store::{self, Result, Store, backend}; | ||
| 7 | + | ||
| 8 | +#[derive(Debug, Clone)] | ||
| 9 | +pub struct Event { | ||
| 10 | + pub id: String, | ||
| 11 | + pub at: time::OffsetDateTime, | ||
| 12 | + pub kind: String, | ||
| 13 | + pub actor: Option<String>, | ||
| 14 | + pub detail: Option<String>, | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +/// Appends an event. Never fails the caller's operation: a log that cannot | ||
| 18 | +/// be written is printed, not propagated. | ||
| 19 | +pub async fn log(store: &Store, kind: &str, actor: Option<&str>, detail: Option<&str>) { | ||
| 20 | + let outcome = store | ||
| 21 | + .conn | ||
| 22 | + .execute( | ||
| 23 | + "INSERT INTO events (id, at, kind, actor, detail) VALUES (?1, ?2, ?3, ?4, ?5)", | ||
| 24 | + turso::params![ | ||
| 25 | + ulid::Ulid::new().to_string(), | ||
| 26 | + store::stamp(store::now()).expect("rfc3339 of now"), | ||
| 27 | + kind, | ||
| 28 | + actor, | ||
| 29 | + detail, | ||
| 30 | + ], | ||
| 31 | + ) | ||
| 32 | + .await; | ||
| 33 | + if let Err(e) = outcome { | ||
| 34 | + eprintln!("im event {kind} ({actor:?}): could not be logged: {e}"); | ||
| 35 | + } | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// Newest-first page of the log for the admin panel. | ||
| 39 | +pub async fn list(store: &Store, limit: i64) -> Result<Vec<Event>> { | ||
| 40 | + let mut rows = store | ||
| 41 | + .conn | ||
| 42 | + .query( | ||
| 43 | + "SELECT id, at, kind, actor, detail FROM events ORDER BY at DESC, id DESC LIMIT ?1", | ||
| 44 | + turso::params![limit], | ||
| 45 | + ) | ||
| 46 | + .await | ||
| 47 | + .map_err(backend)?; | ||
| 48 | + let mut events = Vec::new(); | ||
| 49 | + while let Some(row) = rows.next().await.map_err(backend)? { | ||
| 50 | + events.push(Event { | ||
| 51 | + id: store::text(&row, 0)?, | ||
| 52 | + at: store::parse_stamp(&store::text(&row, 1)?)?, | ||
| 53 | + kind: store::text(&row, 2)?, | ||
| 54 | + actor: store::opt_text(&row, 3)?, | ||
| 55 | + detail: store::opt_text(&row, 4)?, | ||
| 56 | + }); | ||
| 57 | + } | ||
| 58 | + Ok(events) | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +#[cfg(test)] | ||
| 62 | +mod tests { | ||
| 63 | + use super::*; | ||
| 64 | + use std::path::Path; | ||
| 65 | + | ||
| 66 | + #[tokio::test] | ||
| 67 | + async fn log_and_list_newest_first() { | ||
| 68 | + let store = Store::open(Path::new(":memory:")).await.unwrap(); | ||
| 69 | + log(&store, "login_ok", Some("ann@example.com"), None).await; | ||
| 70 | + log( | ||
| 71 | + &store, | ||
| 72 | + "login_fail", | ||
| 73 | + Some("bob@example.com"), | ||
| 74 | + Some("wrong password"), | ||
| 75 | + ) | ||
| 76 | + .await; | ||
| 77 | + let events = list(&store, 10).await.unwrap(); | ||
| 78 | + assert_eq!(events.len(), 2); | ||
| 79 | + assert_eq!(events[0].kind, "login_fail"); | ||
| 80 | + assert_eq!(events[1].actor.as_deref(), Some("ann@example.com")); | ||
| 81 | + } | ||
| 82 | +} | ||
crates/im-core/src/lib.rsmodified+4 -0
| @@ -8,6 +8,8 @@ | |||
| 8 | #[cfg(feature = "server")] | 8 | #[cfg(feature = "server")] |
| 9 | pub mod accounts; | 9 | pub mod accounts; |
| 10 | #[cfg(feature = "server")] | 10 | #[cfg(feature = "server")] |
| 11 | +pub mod events; | ||
| 12 | +#[cfg(feature = "server")] | ||
| 11 | pub mod keys; | 13 | pub mod keys; |
| 12 | #[cfg(feature = "server")] | 14 | #[cfg(feature = "server")] |
| 13 | pub mod oidc; | 15 | pub mod oidc; |
| @@ -16,6 +18,8 @@ mod secret; | |||
| 16 | #[cfg(feature = "server")] | 18 | #[cfg(feature = "server")] |
| 17 | pub mod sessions; | 19 | pub mod sessions; |
| 18 | #[cfg(feature = "server")] | 20 | #[cfg(feature = "server")] |
| 21 | +pub mod settings; | ||
| 22 | +#[cfg(feature = "server")] | ||
| 19 | pub mod store; | 23 | pub mod store; |
| 20 | #[cfg(feature = "server")] | 24 | #[cfg(feature = "server")] |
| 21 | pub mod totp; | 25 | pub mod totp; |
crates/im-core/src/model.rsmodified+5 -0
| @@ -51,6 +51,9 @@ pub struct User { | |||
| 51 | pub email: String, | 51 | pub email: String, |
| 52 | pub name: String, | 52 | pub name: String, |
| 53 | pub totp_confirmed: bool, | 53 | pub totp_confirmed: bool, |
| 54 | + /// im's own admin flag — never crosses a token; AuthN stays the only | ||
| 55 | + /// thing apps receive. | ||
| 56 | + pub admin: bool, | ||
| 54 | pub disabled: bool, | 57 | pub disabled: bool, |
| 55 | pub created_at: OffsetDateTime, | 58 | pub created_at: OffsetDateTime, |
| 56 | } | 59 | } |
| @@ -61,6 +64,8 @@ pub struct User { | |||
| 61 | pub struct Invite { | 64 | pub struct Invite { |
| 62 | pub email: String, | 65 | pub email: String, |
| 63 | pub invited_by: Option<UserId>, | 66 | pub invited_by: Option<UserId>, |
| 67 | + /// An admin invite mints an admin. | ||
| 68 | + pub admin: bool, | ||
| 64 | pub created_at: OffsetDateTime, | 69 | pub created_at: OffsetDateTime, |
| 65 | pub expires_at: OffsetDateTime, | 70 | pub expires_at: OffsetDateTime, |
| 66 | pub accepted_at: Option<OffsetDateTime>, | 71 | pub accepted_at: Option<OffsetDateTime>, |
crates/im-core/src/oidc.rsmodified+142 -1
| @@ -411,6 +411,111 @@ pub async fn verify_jwt( | |||
| 411 | Ok(Some(claims)) | 411 | Ok(Some(claims)) |
| 412 | } | 412 | } |
| 413 | 413 | ||
| 414 | +// --------------------------------------------------------------------------- | ||
| 415 | +// App sessions: the opaque, introspected session an app actually holds | ||
| 416 | +// --------------------------------------------------------------------------- | ||
| 417 | + | ||
| 418 | +/// How long an app session may live when nothing revokes it first. | ||
| 419 | +pub const APP_SESSION_DAYS: i64 = 30; | ||
| 420 | + | ||
| 421 | +/// Mints an opaque app session bound to the central session that authorized | ||
| 422 | +/// it. The app stores only this token; every request it serves introspects | ||
| 423 | +/// the token against im, so revocation is immediate rather than | ||
| 424 | +/// token-TTL-bounded. | ||
| 425 | +pub async fn issue_app_session( | ||
| 426 | + store: &Store, | ||
| 427 | + user: &UserId, | ||
| 428 | + client_id: &ClientId, | ||
| 429 | + session_hash: &str, | ||
| 430 | +) -> Result<Token> { | ||
| 431 | + let token = Token::mint(); | ||
| 432 | + let now = store::now(); | ||
| 433 | + store | ||
| 434 | + .conn | ||
| 435 | + .execute( | ||
| 436 | + "INSERT INTO app_sessions \ | ||
| 437 | + (token_hash, user_id, client_id, session_hash, created_at, expires_at) \ | ||
| 438 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | ||
| 439 | + turso::params![ | ||
| 440 | + token.hash(), | ||
| 441 | + user.to_string(), | ||
| 442 | + client_id.to_string(), | ||
| 443 | + session_hash, | ||
| 444 | + store::stamp(now)?, | ||
| 445 | + store::stamp(now + time::Duration::days(APP_SESSION_DAYS))?, | ||
| 446 | + ], | ||
| 447 | + ) | ||
| 448 | + .await | ||
| 449 | + .map_err(backend)?; | ||
| 450 | + Ok(token) | ||
| 451 | +} | ||
| 452 | + | ||
| 453 | +/// RFC 7662's answer shape: who this token is, or inactive. Inactive covers | ||
| 454 | +/// unknown, expired, revoked, a revoked central session, a disabled user, or | ||
| 455 | +/// a token presented by a client it was never issued to. | ||
| 456 | +pub async fn introspect_app_session( | ||
| 457 | + store: &Store, | ||
| 458 | + token: &str, | ||
| 459 | + client_id: &str, | ||
| 460 | +) -> Result<Option<serde_json::Value>> { | ||
| 461 | + let mut rows = store | ||
| 462 | + .conn | ||
| 463 | + .query( | ||
| 464 | + "SELECT user_id, client_id, session_hash, expires_at, revoked_at \ | ||
| 465 | + FROM app_sessions WHERE token_hash = ?1", | ||
| 466 | + turso::params![hash_token(token)], | ||
| 467 | + ) | ||
| 468 | + .await | ||
| 469 | + .map_err(backend)?; | ||
| 470 | + let Some(row) = rows.next().await.map_err(backend)? else { | ||
| 471 | + return Ok(None); | ||
| 472 | + }; | ||
| 473 | + if store::opt_text(&row, 4)?.is_some() { | ||
| 474 | + return Ok(None); | ||
| 475 | + } | ||
| 476 | + let expires = store::parse_stamp(&store::text(&row, 3)?)?; | ||
| 477 | + if expires < store::now() { | ||
| 478 | + return Ok(None); | ||
| 479 | + } | ||
| 480 | + if store::text(&row, 1)? != client_id { | ||
| 481 | + return Ok(None); | ||
| 482 | + } | ||
| 483 | + // The central session must still be alive — this is what makes admin | ||
| 484 | + // revocation immediate. | ||
| 485 | + let session_hash = store::text(&row, 2)?; | ||
| 486 | + let mut sessions = store | ||
| 487 | + .conn | ||
| 488 | + .query( | ||
| 489 | + "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1", | ||
| 490 | + turso::params![session_hash], | ||
| 491 | + ) | ||
| 492 | + .await | ||
| 493 | + .map_err(backend)?; | ||
| 494 | + let Some(session) = sessions.next().await.map_err(backend)? else { | ||
| 495 | + return Ok(None); | ||
| 496 | + }; | ||
| 497 | + if store::opt_text(&session, 1)?.is_some() { | ||
| 498 | + return Ok(None); | ||
| 499 | + } | ||
| 500 | + if store::parse_stamp(&store::text(&session, 0)?)? < store::now() { | ||
| 501 | + return Ok(None); | ||
| 502 | + } | ||
| 503 | + let user_id = UserId::from(store::text(&row, 0)?); | ||
| 504 | + let Some(user) = crate::accounts::user_by_id(store, &user_id).await? else { | ||
| 505 | + return Ok(None); | ||
| 506 | + }; | ||
| 507 | + if user.disabled { | ||
| 508 | + return Ok(None); | ||
| 509 | + } | ||
| 510 | + Ok(Some(serde_json::json!({ | ||
| 511 | + "active": true, | ||
| 512 | + "sub": user.id.as_str(), | ||
| 513 | + "email": user.email, | ||
| 514 | + "name": user.name, | ||
| 515 | + "exp": expires.unix_timestamp(), | ||
| 516 | + }))) | ||
| 517 | +} | ||
| 518 | + | ||
| 414 | #[cfg(test)] | 519 | #[cfg(test)] |
| 415 | mod tests { | 520 | mod tests { |
| 416 | use super::*; | 521 | use super::*; |
| @@ -419,13 +524,49 @@ mod tests { | |||
| 419 | use rsa::signature::Verifier; | 524 | use rsa::signature::Verifier; |
| 420 | use std::path::Path; | 525 | use std::path::Path; |
| 421 | 526 | ||
| 527 | + #[tokio::test] | ||
| 528 | + async fn app_session_introspection_and_instant_revoke() { | ||
| 529 | + let (store, client_id, user_id) = fixture().await; | ||
| 530 | + let session = create_session(&store, &user_id).await.unwrap(); | ||
| 531 | + let app_token = issue_app_session(&store, &user_id, &client_id, &session.hash()) | ||
| 532 | + .await | ||
| 533 | + .unwrap(); | ||
| 534 | + | ||
| 535 | + let active = introspect_app_session(&store, app_token.expose(), client_id.as_str()) | ||
| 536 | + .await | ||
| 537 | + .unwrap() | ||
| 538 | + .unwrap(); | ||
| 539 | + assert_eq!(active["active"], true); | ||
| 540 | + assert_eq!(active["sub"], user_id.as_str()); | ||
| 541 | + | ||
| 542 | + // Another client cannot spend the token. | ||
| 543 | + assert!( | ||
| 544 | + introspect_app_session(&store, app_token.expose(), "someone-else") | ||
| 545 | + .await | ||
| 546 | + .unwrap() | ||
| 547 | + .is_none() | ||
| 548 | + ); | ||
| 549 | + | ||
| 550 | + // Admin revokes the person: the very next introspection is inactive. | ||
| 551 | + crate::sessions::revoke_user_sessions(&store, &user_id) | ||
| 552 | + .await | ||
| 553 | + .unwrap(); | ||
| 554 | + assert!( | ||
| 555 | + introspect_app_session(&store, app_token.expose(), client_id.as_str()) | ||
| 556 | + .await | ||
| 557 | + .unwrap() | ||
| 558 | + .is_none(), | ||
| 559 | + "no ghost after admin revocation" | ||
| 560 | + ); | ||
| 561 | + } | ||
| 562 | + | ||
| 422 | async fn fixture() -> (Store, ClientId, UserId) { | 563 | async fn fixture() -> (Store, ClientId, UserId) { |
| 423 | let store = Store::open(Path::new(":memory:")).await.unwrap(); | 564 | let store = Store::open(Path::new(":memory:")).await.unwrap(); |
| 424 | let (client_id, _secret) = | 565 | let (client_id, _secret) = |
| 425 | create_client(&store, "demo", vec!["http://app/callback".into()]) | 566 | create_client(&store, "demo", vec!["http://app/callback".into()]) |
| 426 | .await | 567 | .await |
| 427 | .unwrap(); | 568 | .unwrap(); |
| 428 | - let invite = create_invite(&store, "ann@example.com", None) | 569 | + let invite = create_invite(&store, "ann@example.com", None, false) |
| 429 | .await | 570 | .await |
| 430 | .unwrap(); | 571 | .unwrap(); |
| 431 | let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") | 572 | let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") |
crates/im-core/src/sessions.rsmodified+62 -4
| @@ -61,15 +61,22 @@ pub async fn resolve_session(store: &Store, token: &str) -> Result<Option<User>> | |||
| 61 | } | 61 | } |
| 62 | } | 62 | } |
| 63 | 63 | ||
| 64 | -/// Revokes a session and every refresh token bound to it. | 64 | +/// Revokes a session and everything bound to it: refresh tokens and the |
| 65 | +/// opaque app sessions introspection answers for. | ||
| 65 | pub async fn revoke_session(store: &Store, token: &str) -> Result<()> { | 66 | pub async fn revoke_session(store: &Store, token: &str) -> Result<()> { |
| 66 | - let now = store::stamp(store::now())?; | ||
| 67 | let hash = hash_token(token); | 67 | let hash = hash_token(token); |
| 68 | + revoke_session_hash(store, &hash).await | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// The hash-level half of [`revoke_session`], shared with the admin's | ||
| 72 | +/// revoke-everything below. | ||
| 73 | +pub(crate) async fn revoke_session_hash(store: &Store, hash: &str) -> Result<()> { | ||
| 74 | + let now = store::stamp(store::now())?; | ||
| 68 | store | 75 | store |
| 69 | .conn | 76 | .conn |
| 70 | .execute( | 77 | .execute( |
| 71 | "UPDATE sessions SET revoked_at = ?1 WHERE token_hash = ?2 AND revoked_at IS NULL", | 78 | "UPDATE sessions SET revoked_at = ?1 WHERE token_hash = ?2 AND revoked_at IS NULL", |
| 72 | - turso::params![now.clone(), hash.clone()], | 79 | + turso::params![now.clone(), hash], |
| 73 | ) | 80 | ) |
| 74 | .await | 81 | .await |
| 75 | .map_err(backend)?; | 82 | .map_err(backend)?; |
| @@ -77,6 +84,14 @@ pub async fn revoke_session(store: &Store, token: &str) -> Result<()> { | |||
| 77 | .conn | 84 | .conn |
| 78 | .execute( | 85 | .execute( |
| 79 | "UPDATE refresh_tokens SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL", | 86 | "UPDATE refresh_tokens SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL", |
| 87 | + turso::params![now.clone(), hash], | ||
| 88 | + ) | ||
| 89 | + .await | ||
| 90 | + .map_err(backend)?; | ||
| 91 | + store | ||
| 92 | + .conn | ||
| 93 | + .execute( | ||
| 94 | + "UPDATE app_sessions SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL", | ||
| 80 | turso::params![now, hash], | 95 | turso::params![now, hash], |
| 81 | ) | 96 | ) |
| 82 | .await | 97 | .await |
| @@ -84,6 +99,49 @@ pub async fn revoke_session(store: &Store, token: &str) -> Result<()> { | |||
| 84 | Ok(()) | 99 | Ok(()) |
| 85 | } | 100 | } |
| 86 | 101 | ||
| 102 | +/// The admin's "log this person out everywhere": every central session of | ||
| 103 | +/// theirs dies, and the cascades above take every refresh token and every | ||
| 104 | +/// live app session down with them. Introspection is per-request, so the | ||
| 105 | +/// next call any app makes on their behalf comes back inactive — no ghost. | ||
| 106 | +pub async fn revoke_user_sessions(store: &Store, user: &UserId) -> Result<u64> { | ||
| 107 | + let mut rows = store | ||
| 108 | + .conn | ||
| 109 | + .query( | ||
| 110 | + "SELECT token_hash FROM sessions WHERE user_id = ?1 AND revoked_at IS NULL", | ||
| 111 | + turso::params![user.to_string()], | ||
| 112 | + ) | ||
| 113 | + .await | ||
| 114 | + .map_err(backend)?; | ||
| 115 | + let mut hashes = Vec::new(); | ||
| 116 | + while let Some(row) = rows.next().await.map_err(backend)? { | ||
| 117 | + hashes.push(store::text(&row, 0)?); | ||
| 118 | + } | ||
| 119 | + let count = hashes.len() as u64; | ||
| 120 | + for hash in hashes { | ||
| 121 | + revoke_session_hash(store, &hash).await?; | ||
| 122 | + } | ||
| 123 | + // Sessions already revoked earlier still own live app sessions; sweep | ||
| 124 | + // those too so nothing outlives the person being signed out. | ||
| 125 | + let now = store::stamp(store::now())?; | ||
| 126 | + store | ||
| 127 | + .conn | ||
| 128 | + .execute( | ||
| 129 | + "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", | ||
| 130 | + turso::params![now.clone(), user.to_string()], | ||
| 131 | + ) | ||
| 132 | + .await | ||
| 133 | + .map_err(backend)?; | ||
| 134 | + store | ||
| 135 | + .conn | ||
| 136 | + .execute( | ||
| 137 | + "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", | ||
| 138 | + turso::params![now, user.to_string()], | ||
| 139 | + ) | ||
| 140 | + .await | ||
| 141 | + .map_err(backend)?; | ||
| 142 | + Ok(count) | ||
| 143 | +} | ||
| 144 | + | ||
| 87 | #[cfg(test)] | 145 | #[cfg(test)] |
| 88 | mod tests { | 146 | mod tests { |
| 89 | use super::*; | 147 | use super::*; |
| @@ -92,7 +150,7 @@ mod tests { | |||
| 92 | 150 | ||
| 93 | async fn fixture() -> (Store, UserId) { | 151 | async fn fixture() -> (Store, UserId) { |
| 94 | let store = Store::open(Path::new(":memory:")).await.unwrap(); | 152 | let store = Store::open(Path::new(":memory:")).await.unwrap(); |
| 95 | - let invite = create_invite(&store, "ann@example.com", None) | 153 | + let invite = create_invite(&store, "ann@example.com", None, false) |
| 96 | .await | 154 | .await |
| 97 | .unwrap(); | 155 | .unwrap(); |
| 98 | let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") | 156 | let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") |
crates/im-core/src/settings.rsadded+172 -0
| @@ -0,0 +1,172 @@ | |||
| 1 | +//! Admin-managed settings in the database, sealed where they are secrets — | ||
| 2 | +//! the same contract izlek-core's `store/secret.rs` keeps for SMTP. The TOML | ||
| 3 | +//! config holds deployment facts (paths, listen, issuer); the settings table | ||
| 4 | +//! holds what an admin rotates from the panel. | ||
| 5 | + | ||
| 6 | +use crate::secret; | ||
| 7 | +use crate::store::{self, Result, Store, backend}; | ||
| 8 | + | ||
| 9 | +/// The SMTP sender, as the panel sets it. `password` only ever comes back | ||
| 10 | +/// opened; the row holds the sealed envelope. | ||
| 11 | +#[derive(Debug, Clone, Default)] | ||
| 12 | +pub struct Smtp { | ||
| 13 | + pub host: String, | ||
| 14 | + pub port: u16, | ||
| 15 | + pub username: String, | ||
| 16 | + pub from: String, | ||
| 17 | + pub password: Option<String>, | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +impl Smtp { | ||
| 21 | + pub fn configured(&self) -> bool { | ||
| 22 | + !self.host.is_empty() && self.port > 0 && !self.from.is_empty() | ||
| 23 | + } | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +async fn get(store: &Store, key: &str) -> Result<Option<String>> { | ||
| 27 | + let mut rows = store | ||
| 28 | + .conn | ||
| 29 | + .query( | ||
| 30 | + "SELECT value FROM settings WHERE key = ?1", | ||
| 31 | + turso::params![key], | ||
| 32 | + ) | ||
| 33 | + .await | ||
| 34 | + .map_err(backend)?; | ||
| 35 | + let Some(row) = rows.next().await.map_err(backend)? else { | ||
| 36 | + return Ok(None); | ||
| 37 | + }; | ||
| 38 | + store::opt_text(&row, 0) | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +async fn set(store: &Store, key: &str, value: &str) -> Result<()> { | ||
| 42 | + store | ||
| 43 | + .conn | ||
| 44 | + .execute( | ||
| 45 | + "INSERT INTO settings (key, value) VALUES (?1, ?2) \ | ||
| 46 | + ON CONFLICT(key) DO UPDATE SET value = excluded.value", | ||
| 47 | + turso::params![key, value], | ||
| 48 | + ) | ||
| 49 | + .await | ||
| 50 | + .map_err(backend)?; | ||
| 51 | + Ok(()) | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// Reads the SMTP settings; a sealed password that no longer opens reads as | ||
| 55 | +/// absent (wrong im.key, restored backup) — the same degradation izlek-core | ||
| 56 | +/// chose. | ||
| 57 | +pub async fn smtp(store: &Store) -> Result<Smtp> { | ||
| 58 | + let host = get(store, "smtp_host").await?.unwrap_or_default(); | ||
| 59 | + let port = get(store, "smtp_port") | ||
| 60 | + .await? | ||
| 61 | + .and_then(|raw| raw.parse().ok()) | ||
| 62 | + .unwrap_or(465); | ||
| 63 | + let username = get(store, "smtp_username").await?.unwrap_or_default(); | ||
| 64 | + let from = get(store, "smtp_from").await?.unwrap_or_default(); | ||
| 65 | + let password = get(store, "smtp_password") | ||
| 66 | + .await? | ||
| 67 | + .and_then(|sealed| secret::open(store.key(), &sealed)) | ||
| 68 | + .and_then(|bytes| String::from_utf8(bytes).ok()); | ||
| 69 | + Ok(Smtp { | ||
| 70 | + host, | ||
| 71 | + port, | ||
| 72 | + username, | ||
| 73 | + from, | ||
| 74 | + password, | ||
| 75 | + }) | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// Writes the SMTP settings. `password: None` keeps the stored one — the | ||
| 79 | +/// panel's password field is write-only, like izlek's. | ||
| 80 | +pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Result<()> { | ||
| 81 | + if smtp.host.is_empty() { | ||
| 82 | + for key in [ | ||
| 83 | + "smtp_host", | ||
| 84 | + "smtp_port", | ||
| 85 | + "smtp_username", | ||
| 86 | + "smtp_from", | ||
| 87 | + "smtp_password", | ||
| 88 | + ] { | ||
| 89 | + store | ||
| 90 | + .conn | ||
| 91 | + .execute("DELETE FROM settings WHERE key = ?1", turso::params![key]) | ||
| 92 | + .await | ||
| 93 | + .map_err(backend)?; | ||
| 94 | + } | ||
| 95 | + return Ok(()); | ||
| 96 | + } | ||
| 97 | + set(store, "smtp_host", &smtp.host).await?; | ||
| 98 | + set(store, "smtp_port", &smtp.port.to_string()).await?; | ||
| 99 | + set(store, "smtp_username", &smtp.username).await?; | ||
| 100 | + set(store, "smtp_from", &smtp.from).await?; | ||
| 101 | + if let Some(password) = password { | ||
| 102 | + if !password.is_empty() { | ||
| 103 | + set( | ||
| 104 | + store, | ||
| 105 | + "smtp_password", | ||
| 106 | + &secret::seal(store.key(), password.as_bytes()), | ||
| 107 | + ) | ||
| 108 | + .await?; | ||
| 109 | + } | ||
| 110 | + } | ||
| 111 | + Ok(()) | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +#[cfg(test)] | ||
| 115 | +mod tests { | ||
| 116 | + use super::*; | ||
| 117 | + use std::path::Path; | ||
| 118 | + | ||
| 119 | + #[tokio::test] | ||
| 120 | + async fn smtp_roundtrip_with_sealed_password() { | ||
| 121 | + let store = Store::open(Path::new(":memory:")).await.unwrap(); | ||
| 122 | + assert!(!smtp(&store).await.unwrap().configured()); | ||
| 123 | + | ||
| 124 | + let value = Smtp { | ||
| 125 | + host: "smtp.example.com".into(), | ||
| 126 | + port: 465, | ||
| 127 | + username: "im".into(), | ||
| 128 | + from: "im <auth@example.com>".into(), | ||
| 129 | + password: None, | ||
| 130 | + }; | ||
| 131 | + set_smtp(&store, &value, Some("s3cret")).await.unwrap(); | ||
| 132 | + let read = smtp(&store).await.unwrap(); | ||
| 133 | + assert!(read.configured()); | ||
| 134 | + assert_eq!(read.password.as_deref(), Some("s3cret")); | ||
| 135 | + | ||
| 136 | + // A write without a password keeps the stored one. | ||
| 137 | + set_smtp(&store, &value, None).await.unwrap(); | ||
| 138 | + assert_eq!( | ||
| 139 | + smtp(&store).await.unwrap().password.as_deref(), | ||
| 140 | + Some("s3cret") | ||
| 141 | + ); | ||
| 142 | + | ||
| 143 | + // An empty host clears the sender. | ||
| 144 | + set_smtp(&store, &Smtp::default(), None).await.unwrap(); | ||
| 145 | + assert!(!smtp(&store).await.unwrap().configured()); | ||
| 146 | + } | ||
| 147 | + | ||
| 148 | + #[tokio::test] | ||
| 149 | + async fn sealed_password_needs_the_key() { | ||
| 150 | + let dir = tempfile::tempdir().unwrap(); | ||
| 151 | + let path = dir.path().join("im.db"); | ||
| 152 | + { | ||
| 153 | + let store = Store::open(&path).await.unwrap(); | ||
| 154 | + let value = Smtp { | ||
| 155 | + host: "smtp.example.com".into(), | ||
| 156 | + port: 465, | ||
| 157 | + username: String::new(), | ||
| 158 | + from: "a@b.c".into(), | ||
| 159 | + password: None, | ||
| 160 | + }; | ||
| 161 | + set_smtp(&store, &value, Some("s3cret")).await.unwrap(); | ||
| 162 | + } | ||
| 163 | + // A different key cannot open it. | ||
| 164 | + let sealed = { | ||
| 165 | + let store = Store::open(&path).await.unwrap(); | ||
| 166 | + super::get(&store, "smtp_password").await.unwrap().unwrap() | ||
| 167 | + }; | ||
| 168 | + assert!(secret::is_sealed(&sealed)); | ||
| 169 | + let wrong_key = [9u8; 32]; | ||
| 170 | + assert!(secret::open(&wrong_key, &sealed).is_none()); | ||
| 171 | + } | ||
| 172 | +} | ||
crates/im-core/src/store.rsmodified+22 -0
| @@ -35,6 +35,7 @@ CREATE TABLE IF NOT EXISTS users ( | |||
| 35 | password_hash TEXT NOT NULL, | 35 | password_hash TEXT NOT NULL, |
| 36 | totp_secret BLOB, | 36 | totp_secret BLOB, |
| 37 | totp_confirmed INTEGER NOT NULL DEFAULT 0, | 37 | totp_confirmed INTEGER NOT NULL DEFAULT 0, |
| 38 | + admin INTEGER NOT NULL DEFAULT 0, | ||
| 38 | disabled INTEGER NOT NULL DEFAULT 0, | 39 | disabled INTEGER NOT NULL DEFAULT 0, |
| 39 | created_at TEXT NOT NULL | 40 | created_at TEXT NOT NULL |
| 40 | ); | 41 | ); |
| @@ -42,6 +43,7 @@ CREATE TABLE IF NOT EXISTS invites ( | |||
| 42 | token TEXT PRIMARY KEY, | 43 | token TEXT PRIMARY KEY, |
| 43 | email TEXT NOT NULL, | 44 | email TEXT NOT NULL, |
| 44 | invited_by TEXT, | 45 | invited_by TEXT, |
| 46 | + admin INTEGER NOT NULL DEFAULT 0, | ||
| 45 | created_at TEXT NOT NULL, | 47 | created_at TEXT NOT NULL, |
| 46 | expires_at TEXT NOT NULL, | 48 | expires_at TEXT NOT NULL, |
| 47 | accepted_at TEXT | 49 | accepted_at TEXT |
| @@ -86,6 +88,26 @@ CREATE TABLE IF NOT EXISTS signing_keys ( | |||
| 86 | created_at TEXT NOT NULL, | 88 | created_at TEXT NOT NULL, |
| 87 | active INTEGER NOT NULL DEFAULT 1 | 89 | active INTEGER NOT NULL DEFAULT 1 |
| 88 | ); | 90 | ); |
| 91 | +CREATE TABLE IF NOT EXISTS app_sessions ( | ||
| 92 | + token_hash TEXT PRIMARY KEY, | ||
| 93 | + user_id TEXT NOT NULL REFERENCES users(id), | ||
| 94 | + client_id TEXT NOT NULL REFERENCES oidc_clients(client_id), | ||
| 95 | + session_hash TEXT NOT NULL REFERENCES sessions(token_hash), | ||
| 96 | + created_at TEXT NOT NULL, | ||
| 97 | + expires_at TEXT NOT NULL, | ||
| 98 | + revoked_at TEXT | ||
| 99 | +); | ||
| 100 | +CREATE TABLE IF NOT EXISTS events ( | ||
| 101 | + id TEXT PRIMARY KEY, | ||
| 102 | + at TEXT NOT NULL, | ||
| 103 | + kind TEXT NOT NULL, | ||
| 104 | + actor TEXT, | ||
| 105 | + detail TEXT | ||
| 106 | +); | ||
| 107 | +CREATE TABLE IF NOT EXISTS settings ( | ||
| 108 | + key TEXT PRIMARY KEY, | ||
| 109 | + value TEXT NOT NULL | ||
| 110 | +); | ||
| 89 | "; | 111 | "; |
| 90 | 112 | ||
| 91 | /// One database handle with the at-rest key beside it. Turso is a | 113 | /// One database handle with the at-rest key beside it. Turso is a |
crates/im-core/src/totp.rsmodified+1 -1
| @@ -179,7 +179,7 @@ mod tests { | |||
| 179 | #[tokio::test] | 179 | #[tokio::test] |
| 180 | async fn store_roundtrip_and_confirm() { | 180 | async fn store_roundtrip_and_confirm() { |
| 181 | let store = Store::open(Path::new(":memory:")).await.unwrap(); | 181 | let store = Store::open(Path::new(":memory:")).await.unwrap(); |
| 182 | - let invite = create_invite(&store, "ann@example.com", None) | 182 | + let invite = create_invite(&store, "ann@example.com", None, false) |
| 183 | .await | 183 | .await |
| 184 | .unwrap(); | 184 | .unwrap(); |
| 185 | let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") | 185 | let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") |
crates/im-web/assets/main.cssmodified+161 -0
| @@ -339,3 +339,164 @@ body:has(.auth-stage) > .auth-stage::-webkit-scrollbar { | |||
| 339 | padding: 0 16px 24px; | 339 | padding: 0 16px 24px; |
| 340 | } | 340 | } |
| 341 | } | 341 | } |
| 342 | +body:has(.admin-shell) { | ||
| 343 | + min-height: 100vh; | ||
| 344 | + min-height: 100dvh; | ||
| 345 | +} | ||
| 346 | + | ||
| 347 | +.admin-shell { | ||
| 348 | + display: flex; | ||
| 349 | + justify-content: center; | ||
| 350 | + padding: 24px 24px 48px; | ||
| 351 | +} | ||
| 352 | + | ||
| 353 | +.admin-column { | ||
| 354 | + width: 760px; | ||
| 355 | + max-width: 100%; | ||
| 356 | + display: flex; | ||
| 357 | + flex-direction: column; | ||
| 358 | + gap: 16px; | ||
| 359 | +} | ||
| 360 | + | ||
| 361 | +.admin-bar { | ||
| 362 | + display: flex; | ||
| 363 | + align-items: center; | ||
| 364 | + gap: 20px; | ||
| 365 | + height: var(--control-h-lg); | ||
| 366 | +} | ||
| 367 | +.admin-bar .wordmark-text { | ||
| 368 | + font-size: 15px; | ||
| 369 | +} | ||
| 370 | + | ||
| 371 | +.admin-tabs { | ||
| 372 | + display: flex; | ||
| 373 | + gap: 16px; | ||
| 374 | +} | ||
| 375 | + | ||
| 376 | +.admin-nav { | ||
| 377 | + font-family: var(--font-mono); | ||
| 378 | + font-size: 10px; | ||
| 379 | + letter-spacing: 0.08em; | ||
| 380 | + text-transform: uppercase; | ||
| 381 | + color: var(--muted); | ||
| 382 | + text-decoration: none; | ||
| 383 | + padding-bottom: 2px; | ||
| 384 | +} | ||
| 385 | +.admin-nav:hover { | ||
| 386 | + color: var(--ink); | ||
| 387 | +} | ||
| 388 | +.admin-nav-on { | ||
| 389 | + color: var(--ink); | ||
| 390 | + box-shadow: inset 0 -2px 0 var(--ink); | ||
| 391 | +} | ||
| 392 | + | ||
| 393 | +.admin-bar .auth-alt { | ||
| 394 | + margin-left: auto; | ||
| 395 | + align-self: auto; | ||
| 396 | +} | ||
| 397 | + | ||
| 398 | +.admin-card { | ||
| 399 | + background: var(--surface); | ||
| 400 | + border: 1px solid var(--border); | ||
| 401 | + border-radius: var(--radius-lg); | ||
| 402 | + padding: 24px; | ||
| 403 | + display: flex; | ||
| 404 | + flex-direction: column; | ||
| 405 | + gap: 16px; | ||
| 406 | +} | ||
| 407 | + | ||
| 408 | +.admin-table { | ||
| 409 | + width: 100%; | ||
| 410 | + border-collapse: collapse; | ||
| 411 | + font-size: 13px; | ||
| 412 | +} | ||
| 413 | +.admin-table th { | ||
| 414 | + font-family: var(--font-mono); | ||
| 415 | + font-size: 10px; | ||
| 416 | + letter-spacing: 0.08em; | ||
| 417 | + color: var(--muted-soft); | ||
| 418 | + text-align: left; | ||
| 419 | + padding: 0 12px 6px 0; | ||
| 420 | +} | ||
| 421 | +.admin-table td { | ||
| 422 | + padding: 8px 12px 8px 0; | ||
| 423 | + border-top: 1px solid var(--border-soft); | ||
| 424 | + vertical-align: middle; | ||
| 425 | +} | ||
| 426 | + | ||
| 427 | +.mono { | ||
| 428 | + font-family: var(--font-mono); | ||
| 429 | +} | ||
| 430 | + | ||
| 431 | +.muted { | ||
| 432 | + color: var(--muted); | ||
| 433 | +} | ||
| 434 | + | ||
| 435 | +.actions { | ||
| 436 | + display: flex; | ||
| 437 | + gap: 8px; | ||
| 438 | + justify-content: flex-end; | ||
| 439 | +} | ||
| 440 | +.actions form { | ||
| 441 | + display: inline; | ||
| 442 | +} | ||
| 443 | + | ||
| 444 | +.admin-action { | ||
| 445 | + height: var(--control-h); | ||
| 446 | + --control-h: 32px; | ||
| 447 | + padding: 0 10px; | ||
| 448 | + background: var(--surface); | ||
| 449 | + border: 1px solid var(--border-strong); | ||
| 450 | + border-radius: var(--radius); | ||
| 451 | + color: var(--ink); | ||
| 452 | + font-size: 12px; | ||
| 453 | + cursor: pointer; | ||
| 454 | +} | ||
| 455 | +.admin-action:hover { | ||
| 456 | + background: var(--row-hover, var(--panel-sunken)); | ||
| 457 | +} | ||
| 458 | + | ||
| 459 | +.admin-action-wide { | ||
| 460 | + width: 100%; | ||
| 461 | +} | ||
| 462 | + | ||
| 463 | +.admin-invite { | ||
| 464 | + display: flex; | ||
| 465 | + gap: 8px; | ||
| 466 | + align-items: center; | ||
| 467 | +} | ||
| 468 | +.admin-invite .auth-input { | ||
| 469 | + flex: 1; | ||
| 470 | +} | ||
| 471 | +.admin-invite .admin-action-wide { | ||
| 472 | + width: auto; | ||
| 473 | + padding: 0 20px; | ||
| 474 | +} | ||
| 475 | + | ||
| 476 | +.admin-check { | ||
| 477 | + display: flex; | ||
| 478 | + align-items: center; | ||
| 479 | + gap: 6px; | ||
| 480 | + font-size: 12px; | ||
| 481 | + color: var(--muted); | ||
| 482 | + white-space: nowrap; | ||
| 483 | +} | ||
| 484 | + | ||
| 485 | +.admin-form { | ||
| 486 | + display: flex; | ||
| 487 | + flex-direction: column; | ||
| 488 | + gap: 12px; | ||
| 489 | +} | ||
| 490 | + | ||
| 491 | +input[type=checkbox] { | ||
| 492 | + accent-color: var(--accent); | ||
| 493 | +} | ||
| 494 | + | ||
| 495 | +@media (max-width: 720px) { | ||
| 496 | + .admin-shell { | ||
| 497 | + padding: 16px 12px 32px; | ||
| 498 | + } | ||
| 499 | + .admin-invite { | ||
| 500 | + flex-wrap: wrap; | ||
| 501 | + } | ||
| 502 | +} | ||
crates/im-web/src/admin.rsadded+434 -0
| @@ -0,0 +1,434 @@ | |||
| 1 | +//! The admin panel: users, mail, logs. One page, three sections, every | ||
| 2 | +//! action a plain form post answering a 303 back to its section — the same | ||
| 3 | +//! idiom as izlek-web's settings.rs/logs.rs, minus the client script. | ||
| 4 | + | ||
| 5 | +use im_core::accounts; | ||
| 6 | +use im_core::events; | ||
| 7 | +use im_core::model::{User, UserId}; | ||
| 8 | +use im_core::settings::{self, Smtp}; | ||
| 9 | +use serde::Deserialize; | ||
| 10 | +use topcoat::Result; | ||
| 11 | +use topcoat::context::Cx; | ||
| 12 | +use topcoat::router::content::Form; | ||
| 13 | +use topcoat::router::response::{IntoResponse, Response}; | ||
| 14 | +use topcoat::router::{HeaderValue, StatusCode, header, route}; | ||
| 15 | +use topcoat::view::view; | ||
| 16 | + | ||
| 17 | +use crate::layout::shell; | ||
| 18 | +use crate::mailer; | ||
| 19 | +use crate::pages::{error_text, query_value}; | ||
| 20 | +use crate::server::{self, App}; | ||
| 21 | + | ||
| 22 | +fn app(cx: &Cx) -> &App { | ||
| 23 | + server::app(cx) | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +/// The admin behind this request, or the redirect the request gets instead. | ||
| 27 | +async fn require_admin(cx: &Cx) -> std::result::Result<User, Response> { | ||
| 28 | + match server::current_user(cx).await { | ||
| 29 | + Some(user) if user.admin => Ok(user), | ||
| 30 | + _ => Err(( | ||
| 31 | + StatusCode::SEE_OTHER, | ||
| 32 | + [(header::LOCATION, HeaderValue::from_static("/"))], | ||
| 33 | + ) | ||
| 34 | + .into_response(cx) | ||
| 35 | + .expect("a redirect can always be built")), | ||
| 36 | + } | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/// Everything user-controlled crosses the panel escaped — a display name is | ||
| 40 | +/// free text and the panel renders raw HTML. | ||
| 41 | +fn escape(raw: &str) -> String { | ||
| 42 | + raw.replace('&', "&") | ||
| 43 | + .replace('<', "<") | ||
| 44 | + .replace('>', ">") | ||
| 45 | + .replace('"', """) | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +fn back(cx: &Cx, section: &str, extra: &str) -> Result<Response> { | ||
| 49 | + ( | ||
| 50 | + StatusCode::SEE_OTHER, | ||
| 51 | + [( | ||
| 52 | + header::LOCATION, | ||
| 53 | + HeaderValue::from_str(&format!("/admin?section={section}{extra}")) | ||
| 54 | + .unwrap_or_else(|_| HeaderValue::from_static("/admin")), | ||
| 55 | + )], | ||
| 56 | + ) | ||
| 57 | + .into_response(cx) | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +#[route(GET "/admin")] | ||
| 61 | +async fn admin_page(cx: &Cx) -> Result<Response> { | ||
| 62 | + let me = match require_admin(cx).await { | ||
| 63 | + Ok(me) => me, | ||
| 64 | + Err(redirect) => return Ok(redirect), | ||
| 65 | + }; | ||
| 66 | + let query = topcoat::router::request::uri(cx) | ||
| 67 | + .query() | ||
| 68 | + .unwrap_or("") | ||
| 69 | + .to_string(); | ||
| 70 | + let section = query_value(&query, "section").unwrap_or_else(|| "users".to_string()); | ||
| 71 | + let error = query_value(&query, "error"); | ||
| 72 | + let ok = query_value(&query, "ok"); | ||
| 73 | + let invited = query_value(&query, "invited"); | ||
| 74 | + | ||
| 75 | + let nav = |current: &str| { | ||
| 76 | + [("users", "Users"), ("mail", "Mail"), ("logs", "Logs")] | ||
| 77 | + .into_iter() | ||
| 78 | + .map(|(id, label)| { | ||
| 79 | + format!( | ||
| 80 | + r#"<a class="admin-nav{}" href="/admin?section={id}">{label}</a>"#, | ||
| 81 | + if id == current { " admin-nav-on" } else { "" } | ||
| 82 | + ) | ||
| 83 | + }) | ||
| 84 | + .collect::<String>() | ||
| 85 | + }; | ||
| 86 | + | ||
| 87 | + let section_html = match section.as_str() { | ||
| 88 | + "mail" => mail_section(cx).await?, | ||
| 89 | + "logs" => logs_section(cx).await?, | ||
| 90 | + _ => users_section(cx, &me, invited.as_deref()).await?, | ||
| 91 | + }; | ||
| 92 | + | ||
| 93 | + let banner = match (ok.as_deref(), error.as_deref()) { | ||
| 94 | + (Some(code), _) => Some(format!( | ||
| 95 | + r#"<div class="auth-ok">{}</div>"#, | ||
| 96 | + match code { | ||
| 97 | + "invited" => "Invite created.", | ||
| 98 | + "revoked" => "Sessions revoked — every device is signed out.", | ||
| 99 | + "disabled" => "Account disabled.", | ||
| 100 | + "enabled" => "Account enabled.", | ||
| 101 | + "smtp" => "Mail settings saved.", | ||
| 102 | + "smtp_test" => "Test mail sent.", | ||
| 103 | + _ => "Done.", | ||
| 104 | + } | ||
| 105 | + )), | ||
| 106 | + (_, Some(code)) => Some(format!( | ||
| 107 | + r#"<div class="auth-problem">{}</div>"#, | ||
| 108 | + error_text(code) | ||
| 109 | + )), | ||
| 110 | + _ => None, | ||
| 111 | + }; | ||
| 112 | + | ||
| 113 | + let stage = view! { | ||
| 114 | + cx => | ||
| 115 | + <main class="admin-shell"> | ||
| 116 | + <div class="admin-column"> | ||
| 117 | + <div class="admin-bar"> | ||
| 118 | + <span class="wordmark-text">"im"</span> | ||
| 119 | + <nav class="admin-tabs">(topcoat::view::Unescaped::new_unchecked(nav(§ion)))</nav> | ||
| 120 | + <a class="auth-alt" href="/">(escape(&me.email))</a> | ||
| 121 | + </div> | ||
| 122 | + if let Some(banner) = banner { | ||
| 123 | + (topcoat::view::Unescaped::new_unchecked(banner)) | ||
| 124 | + } | ||
| 125 | + (topcoat::view::Unescaped::new_unchecked(section_html)) | ||
| 126 | + </div> | ||
| 127 | + </main> | ||
| 128 | + }; | ||
| 129 | + shell(cx, "Admin · im", stage).await?.into_response(cx) | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +async fn users_section( | ||
| 133 | + cx: &Cx, | ||
| 134 | + me: &User, | ||
| 135 | + invited: Option<&str>, | ||
| 136 | +) -> Result<String, topcoat::Error> { | ||
| 137 | + let users = accounts::list_users(&app(cx).store).await?; | ||
| 138 | + let mut rows = String::new(); | ||
| 139 | + for user in &users { | ||
| 140 | + let flags = [ | ||
| 141 | + user.admin.then_some("admin"), | ||
| 142 | + user.disabled.then_some("disabled"), | ||
| 143 | + (!user.totp_confirmed).then_some("no 2fa"), | ||
| 144 | + ] | ||
| 145 | + .into_iter() | ||
| 146 | + .flatten() | ||
| 147 | + .collect::<Vec<_>>() | ||
| 148 | + .join(" · "); | ||
| 149 | + let actions = if user.id == me.id { | ||
| 150 | + // Never let the only admin lock themselves out by reflex. | ||
| 151 | + r#"<span class="muted">you</span>"#.to_string() | ||
| 152 | + } else { | ||
| 153 | + let id = escape(&user.id.to_string()); | ||
| 154 | + let toggle = if user.disabled { | ||
| 155 | + format!( | ||
| 156 | + r#"<form method="post" action="/admin/enable"><input type="hidden" name="user" value="{id}"><button class="admin-action" type="submit">Enable</button></form>"# | ||
| 157 | + ) | ||
| 158 | + } else { | ||
| 159 | + format!( | ||
| 160 | + r#"<form method="post" action="/admin/disable"><input type="hidden" name="user" value="{id}"><button class="admin-action" type="submit">Disable</button></form>"# | ||
| 161 | + ) | ||
| 162 | + }; | ||
| 163 | + format!( | ||
| 164 | + r#"{toggle}<form method="post" action="/admin/revoke"><input type="hidden" name="user" value="{id}"><button class="admin-action" type="submit">Sign out everywhere</button></form>"# | ||
| 165 | + ) | ||
| 166 | + }; | ||
| 167 | + rows.push_str(&format!( | ||
| 168 | + "<tr><td class=\"mono\">{}</td><td>{}</td><td class=\"muted\">{}</td><td class=\"actions\">{}</td></tr>", | ||
| 169 | + escape(&user.email), | ||
| 170 | + escape(&user.name), | ||
| 171 | + flags, | ||
| 172 | + actions | ||
| 173 | + )); | ||
| 174 | + } | ||
| 175 | + let invited_html = invited | ||
| 176 | + .map(|link| { | ||
| 177 | + format!( | ||
| 178 | + r#"<div class="auth-note">The link exists once. It is shown once:<br><span class="mono">{}</span></div>"#, | ||
| 179 | + escape(link) | ||
| 180 | + ) | ||
| 181 | + }) | ||
| 182 | + .unwrap_or_default(); | ||
| 183 | + Ok(format!( | ||
| 184 | + r#"<div class="admin-card"> | ||
| 185 | + <div class="auth-title">People</div> | ||
| 186 | + {invited_html} | ||
| 187 | + <table class="admin-table"> | ||
| 188 | + <thead><tr><th>Email</th><th>Name</th><th></th><th></th></tr></thead> | ||
| 189 | + <tbody>{rows}</tbody> | ||
| 190 | + </table> | ||
| 191 | + <form method="post" action="/admin/invite" class="admin-invite"> | ||
| 192 | + <input class="auth-input auth-input-mono" type="email" name="email" placeholder="person@example.com" required> | ||
| 193 | + <label class="admin-check"><input type="checkbox" name="admin" value="yes"> admin</label> | ||
| 194 | + <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">Invite</span></button> | ||
| 195 | + </form> | ||
| 196 | +</div>"# | ||
| 197 | + )) | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +async fn mail_section(cx: &Cx) -> Result<String, topcoat::Error> { | ||
| 201 | + let smtp = settings::smtp(&app(cx).store).await?; | ||
| 202 | + let password_note = if smtp.password.is_some() { | ||
| 203 | + "password is set — fill to replace, leave empty to keep" | ||
| 204 | + } else { | ||
| 205 | + "no password set" | ||
| 206 | + }; | ||
| 207 | + Ok(format!( | ||
| 208 | + r#"<div class="admin-card"> | ||
| 209 | + <div class="auth-title">Mail</div> | ||
| 210 | + <div class="auth-sub">Invites go out through this sender. The password is sealed under <span class="mono">im.key</span>; without a sender, invite links are shown here instead of mailed.</div> | ||
| 211 | + <form method="post" action="/admin/smtp" class="admin-form"> | ||
| 212 | + <label class="auth-field"><span class="auth-label">Host</span> | ||
| 213 | + <input class="auth-input auth-input-mono" type="text" name="host" value="{}" placeholder="smtp.example.com"></label> | ||
| 214 | + <label class="auth-field"><span class="auth-label">Port</span> | ||
| 215 | + <input class="auth-input auth-input-mono" type="number" name="port" value="{}"></label> | ||
| 216 | + <label class="auth-field"><span class="auth-label">Username</span> | ||
| 217 | + <input class="auth-input auth-input-mono" type="text" name="username" value="{}"></label> | ||
| 218 | + <label class="auth-field"><span class="auth-label">Password</span> | ||
| 219 | + <input class="auth-input auth-input-mono" type="password" name="password" placeholder="{password_note}" autocomplete="off"></label> | ||
| 220 | + <label class="auth-field"><span class="auth-label">From</span> | ||
| 221 | + <input class="auth-input auth-input-mono" type="text" name="from" value="{}" placeholder="im <auth@example.com>"></label> | ||
| 222 | + <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">Save</span></button> | ||
| 223 | + </form> | ||
| 224 | + <form method="post" action="/admin/smtp_test" class="admin-form"> | ||
| 225 | + <button class="admin-action" type="submit">Send a test mail to myself</button> | ||
| 226 | + </form> | ||
| 227 | +</div>"#, | ||
| 228 | + escape(&smtp.host), | ||
| 229 | + smtp.port, | ||
| 230 | + escape(&smtp.username), | ||
| 231 | + escape(&smtp.from) | ||
| 232 | + )) | ||
| 233 | +} | ||
| 234 | + | ||
| 235 | +async fn logs_section(cx: &Cx) -> Result<String, topcoat::Error> { | ||
| 236 | + let entries = events::list(&app(cx).store, 200).await?; | ||
| 237 | + let mut rows = String::new(); | ||
| 238 | + for event in &entries { | ||
| 239 | + rows.push_str(&format!( | ||
| 240 | + "<tr><td class=\"mono muted\">{}</td><td class=\"mono\">{}</td><td>{}</td><td class=\"muted\">{}</td></tr>", | ||
| 241 | + escape(&event.at.format(&time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]:[second]")).unwrap_or_default()), | ||
| 242 | + escape(&event.kind), | ||
| 243 | + escape(event.actor.as_deref().unwrap_or("")), | ||
| 244 | + escape(event.detail.as_deref().unwrap_or("")), | ||
| 245 | + )); | ||
| 246 | + } | ||
| 247 | + Ok(format!( | ||
| 248 | + r#"<div class="admin-card"> | ||
| 249 | + <div class="auth-title">Logs</div> | ||
| 250 | + <div class="auth-sub">Everything identity did, newest first. Introspection is not logged — it runs per request and would drown the rest.</div> | ||
| 251 | + <table class="admin-table"> | ||
| 252 | + <thead><tr><th>When</th><th>What</th><th>Who</th><th>Detail</th></tr></thead> | ||
| 253 | + <tbody>{rows}</tbody> | ||
| 254 | + </table> | ||
| 255 | +</div>"# | ||
| 256 | + )) | ||
| 257 | +} | ||
| 258 | + | ||
| 259 | +// --------------------------------------------------------------------------- | ||
| 260 | +// Handlers | ||
| 261 | +// --------------------------------------------------------------------------- | ||
| 262 | + | ||
| 263 | +#[derive(Deserialize)] | ||
| 264 | +struct InviteForm { | ||
| 265 | + email: String, | ||
| 266 | + admin: Option<String>, | ||
| 267 | +} | ||
| 268 | + | ||
| 269 | +#[route(POST "/admin/invite")] | ||
| 270 | +async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Result<Response> { | ||
| 271 | + let me = match require_admin(cx).await { | ||
| 272 | + Ok(me) => me, | ||
| 273 | + Err(redirect) => return Ok(redirect), | ||
| 274 | + }; | ||
| 275 | + let store = &app(cx).store; | ||
| 276 | + let email = input.email.trim().to_string(); | ||
| 277 | + let admin = input.admin.as_deref() == Some("yes"); | ||
| 278 | + let token = accounts::create_invite(store, &email, Some(me.id.clone()), admin) | ||
| 279 | + .await | ||
| 280 | + .map_err(|e| topcoat::Error::from(std::io::Error::other(e.to_string())))?; | ||
| 281 | + // Mailed when a sender is configured; shown once on the page otherwise. | ||
| 282 | + let mailed = mailer::send_invite(store, &app(cx).config.issuer, &email, token.expose()) | ||
| 283 | + .await | ||
| 284 | + .is_ok(); | ||
| 285 | + events::log( | ||
| 286 | + store, | ||
| 287 | + "invite_created", | ||
| 288 | + Some(&me.email), | ||
| 289 | + Some(&format!( | ||
| 290 | + "for {email}{}", | ||
| 291 | + if admin { " (admin)" } else { "" } | ||
| 292 | + )), | ||
| 293 | + ) | ||
| 294 | + .await; | ||
| 295 | + if mailed { | ||
| 296 | + back(cx, "users", "&ok=invited") | ||
| 297 | + } else { | ||
| 298 | + let link = format!("{}/invite/{}", app(cx).config.issuer, token.expose()); | ||
| 299 | + back( | ||
| 300 | + cx, | ||
| 301 | + "users", | ||
| 302 | + &format!("&ok=invited&invited={}", crate::oidc::urlencode(&link)), | ||
| 303 | + ) | ||
| 304 | + } | ||
| 305 | +} | ||
| 306 | + | ||
| 307 | +#[derive(Deserialize)] | ||
| 308 | +struct UserAction { | ||
| 309 | + user: String, | ||
| 310 | +} | ||
| 311 | + | ||
| 312 | +#[route(POST "/admin/revoke")] | ||
| 313 | +async fn revoke(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> { | ||
| 314 | + let me = match require_admin(cx).await { | ||
| 315 | + Ok(me) => me, | ||
| 316 | + Err(redirect) => return Ok(redirect), | ||
| 317 | + }; | ||
| 318 | + let store = &app(cx).store; | ||
| 319 | + let user_id = UserId::from(input.user); | ||
| 320 | + let sessions = im_core::sessions::revoke_user_sessions(store, &user_id).await?; | ||
| 321 | + let email = accounts::user_by_id(store, &user_id) | ||
| 322 | + .await? | ||
| 323 | + .map(|u| u.email); | ||
| 324 | + events::log( | ||
| 325 | + store, | ||
| 326 | + "sessions_revoked", | ||
| 327 | + Some(&me.email), | ||
| 328 | + Some(&format!( | ||
| 329 | + "{}: {sessions} session(s)", | ||
| 330 | + email.as_deref().unwrap_or("unknown") | ||
| 331 | + )), | ||
| 332 | + ) | ||
| 333 | + .await; | ||
| 334 | + back(cx, "users", "&ok=revoked") | ||
| 335 | +} | ||
| 336 | + | ||
| 337 | +#[route(POST "/admin/disable")] | ||
| 338 | +async fn disable(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> { | ||
| 339 | + set_disabled(cx, input, true).await | ||
| 340 | +} | ||
| 341 | + | ||
| 342 | +#[route(POST "/admin/enable")] | ||
| 343 | +async fn enable(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> { | ||
| 344 | + set_disabled(cx, input, false).await | ||
| 345 | +} | ||
| 346 | + | ||
| 347 | +async fn set_disabled(cx: &Cx, input: UserAction, disabled: bool) -> Result<Response> { | ||
| 348 | + let me = match require_admin(cx).await { | ||
| 349 | + Ok(me) => me, | ||
| 350 | + Err(redirect) => return Ok(redirect), | ||
| 351 | + }; | ||
| 352 | + let store = &app(cx).store; | ||
| 353 | + let user_id = UserId::from(input.user); | ||
| 354 | + accounts::set_disabled(store, &user_id, disabled).await?; | ||
| 355 | + if disabled { | ||
| 356 | + // A disabled account keeps no sessions either. | ||
| 357 | + im_core::sessions::revoke_user_sessions(store, &user_id).await?; | ||
| 358 | + } | ||
| 359 | + let email = accounts::user_by_id(store, &user_id) | ||
| 360 | + .await? | ||
| 361 | + .map(|u| u.email); | ||
| 362 | + events::log( | ||
| 363 | + store, | ||
| 364 | + if disabled { | ||
| 365 | + "user_disabled" | ||
| 366 | + } else { | ||
| 367 | + "user_enabled" | ||
| 368 | + }, | ||
| 369 | + Some(&me.email), | ||
| 370 | + email.as_deref(), | ||
| 371 | + ) | ||
| 372 | + .await; | ||
| 373 | + back( | ||
| 374 | + cx, | ||
| 375 | + "users", | ||
| 376 | + if disabled { | ||
| 377 | + "&ok=disabled" | ||
| 378 | + } else { | ||
| 379 | + "&ok=enabled" | ||
| 380 | + }, | ||
| 381 | + ) | ||
| 382 | +} | ||
| 383 | + | ||
| 384 | +#[derive(Deserialize)] | ||
| 385 | +struct SmtpForm { | ||
| 386 | + host: String, | ||
| 387 | + port: u16, | ||
| 388 | + username: String, | ||
| 389 | + password: Option<String>, | ||
| 390 | + from: String, | ||
| 391 | +} | ||
| 392 | + | ||
| 393 | +#[route(POST "/admin/smtp")] | ||
| 394 | +async fn smtp_save(cx: &Cx, Form(input): Form<SmtpForm>) -> Result<Response> { | ||
| 395 | + let me = match require_admin(cx).await { | ||
| 396 | + Ok(me) => me, | ||
| 397 | + Err(redirect) => return Ok(redirect), | ||
| 398 | + }; | ||
| 399 | + let store = &app(cx).store; | ||
| 400 | + let value = Smtp { | ||
| 401 | + host: input.host.trim().to_string(), | ||
| 402 | + port: input.port, | ||
| 403 | + username: input.username.trim().to_string(), | ||
| 404 | + from: input.from.trim().to_string(), | ||
| 405 | + password: None, | ||
| 406 | + }; | ||
| 407 | + settings::set_smtp(store, &value, input.password.as_deref()).await?; | ||
| 408 | + events::log(store, "smtp_updated", Some(&me.email), None).await; | ||
| 409 | + back(cx, "mail", "&ok=smtp") | ||
| 410 | +} | ||
| 411 | + | ||
| 412 | +#[route(POST "/admin/smtp_test")] | ||
| 413 | +async fn smtp_test(cx: &Cx) -> Result<Response> { | ||
| 414 | + let me = match require_admin(cx).await { | ||
| 415 | + Ok(me) => me, | ||
| 416 | + Err(redirect) => return Ok(redirect), | ||
| 417 | + }; | ||
| 418 | + match mailer::send_test(&app(cx).store, &me.email).await { | ||
| 419 | + Ok(()) => { | ||
| 420 | + events::log(&app(cx).store, "smtp_test_sent", Some(&me.email), None).await; | ||
| 421 | + back(cx, "mail", "&ok=smtp_test") | ||
| 422 | + } | ||
| 423 | + Err(e) => { | ||
| 424 | + events::log( | ||
| 425 | + &app(cx).store, | ||
| 426 | + "smtp_test_failed", | ||
| 427 | + Some(&me.email), | ||
| 428 | + Some(&e.to_string()), | ||
| 429 | + ) | ||
| 430 | + .await; | ||
| 431 | + back(cx, "mail", "&error=smtp_test") | ||
| 432 | + } | ||
| 433 | + } | ||
| 434 | +} | ||
crates/im-web/src/auth.rsmodified+24 -3
| @@ -54,7 +54,8 @@ pub struct LoginForm { | |||
| 54 | #[route(POST "/login")] | 54 | #[route(POST "/login")] |
| 55 | async fn login(cx: &Cx, Form(input): Form<LoginForm>) -> Redirect { | 55 | async fn login(cx: &Cx, Form(input): Form<LoginForm>) -> Redirect { |
| 56 | let back = safe_back(input.back.as_deref().unwrap_or("/")).to_string(); | 56 | let back = safe_back(input.back.as_deref().unwrap_or("/")).to_string(); |
| 57 | - match accounts::verify_login(&server::app(cx).store, &input.email, &input.password).await { | 57 | + let store = &server::app(cx).store; |
| 58 | + match accounts::verify_login(store, &input.email, &input.password).await { | ||
| 58 | Ok(user) if user.totp_confirmed => { | 59 | Ok(user) if user.totp_confirmed => { |
| 59 | let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Login, back); | 60 | let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Login, back); |
| 60 | server::set_pending_cookie(cx, sealed); | 61 | server::set_pending_cookie(cx, sealed); |
| @@ -63,11 +64,17 @@ async fn login(cx: &Cx, Form(input): Form<LoginForm>) -> Redirect { | |||
| 63 | Ok(user) => { | 64 | Ok(user) => { |
| 64 | // Accounts enrol TOTP at invite time, so this is the path for one | 65 | // Accounts enrol TOTP at invite time, so this is the path for one |
| 65 | // created before that rule — sign it in, enrolment comes next. | 66 | // created before that rule — sign it in, enrolment comes next. |
| 66 | - let token = im_core::sessions::create_session(&server::app(cx).store, &user.id).await?; | 67 | + let token = im_core::sessions::create_session(store, &user.id).await?; |
| 68 | + im_core::events::log(store, "login_ok", Some(&user.email), None).await; | ||
| 67 | server::set_session_cookie(cx, token.expose()); | 69 | server::set_session_cookie(cx, token.expose()); |
| 68 | see(back) | 70 | see(back) |
| 69 | } | 71 | } |
| 70 | - Err(_) => see(format!("/login?error=bad_login&back={}", urlencode(&back))), | 72 | + Err(_) => { |
| 73 | + // The failure is logged against the address tried, never the | ||
| 74 | + // password — and never whether the address exists. | ||
| 75 | + im_core::events::log(store, "login_fail", Some(&input.email), None).await; | ||
| 76 | + see(format!("/login?error=bad_login&back={}", urlencode(&back))) | ||
| 77 | + } | ||
| 71 | } | 78 | } |
| 72 | } | 79 | } |
| 73 | 80 | ||
| @@ -101,9 +108,14 @@ async fn login_totp(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect { | |||
| 101 | None => false, | 108 | None => false, |
| 102 | }; | 109 | }; |
| 103 | if !ok { | 110 | if !ok { |
| 111 | + im_core::events::log(store, "totp_fail", None, Some("login")).await; | ||
| 104 | return see("/login/totp?error=bad_code".to_string()); | 112 | return see("/login/totp?error=bad_code".to_string()); |
| 105 | } | 113 | } |
| 106 | let token = im_core::sessions::create_session(store, &user_id).await?; | 114 | let token = im_core::sessions::create_session(store, &user_id).await?; |
| 115 | + let email = accounts::user_by_id(store, &user_id) | ||
| 116 | + .await? | ||
| 117 | + .map(|u| u.email); | ||
| 118 | + im_core::events::log(store, "login_ok", email.as_deref(), Some("2fa")).await; | ||
| 107 | server::clear_pending_cookie(cx); | 119 | server::clear_pending_cookie(cx); |
| 108 | server::set_session_cookie(cx, token.expose()); | 120 | server::set_session_cookie(cx, token.expose()); |
| 109 | see(pending.back) | 121 | see(pending.back) |
| @@ -159,6 +171,7 @@ async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Redirect { | |||
| 159 | im_core::totp::set_totp(store, &user.id, &secret).await?; | 171 | im_core::totp::set_totp(store, &user.id, &secret).await?; |
| 160 | let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, "/".to_string()); | 172 | let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, "/".to_string()); |
| 161 | server::set_pending_cookie(cx, sealed); | 173 | server::set_pending_cookie(cx, sealed); |
| 174 | + im_core::events::log(store, "invite_accepted", Some(&user.email), None).await; | ||
| 162 | see("/enroll".to_string()) | 175 | see("/enroll".to_string()) |
| 163 | } | 176 | } |
| 164 | 177 | ||
| @@ -180,6 +193,10 @@ async fn enroll(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect { | |||
| 180 | } | 193 | } |
| 181 | im_core::totp::confirm_totp(store, &user_id).await?; | 194 | im_core::totp::confirm_totp(store, &user_id).await?; |
| 182 | let token = im_core::sessions::create_session(store, &user_id).await?; | 195 | let token = im_core::sessions::create_session(store, &user_id).await?; |
| 196 | + let email = accounts::user_by_id(store, &user_id) | ||
| 197 | + .await? | ||
| 198 | + .map(|u| u.email); | ||
| 199 | + im_core::events::log(store, "enrolled", email.as_deref(), None).await; | ||
| 183 | server::clear_pending_cookie(cx); | 200 | server::clear_pending_cookie(cx); |
| 184 | server::set_session_cookie(cx, token.expose()); | 201 | server::set_session_cookie(cx, token.expose()); |
| 185 | see("/?ok=enrolled".to_string()) | 202 | see("/?ok=enrolled".to_string()) |
| @@ -190,7 +207,11 @@ async fn enroll(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect { | |||
| 190 | #[route(POST "/logout")] | 207 | #[route(POST "/logout")] |
| 191 | async fn logout(cx: &Cx) -> Redirect { | 208 | async fn logout(cx: &Cx) -> Redirect { |
| 192 | if let Some(token) = server::presented_session(cx) { | 209 | if let Some(token) = server::presented_session(cx) { |
| 210 | + let email = im_core::sessions::resolve_session(&server::app(cx).store, &token) | ||
| 211 | + .await? | ||
| 212 | + .map(|u| u.email); | ||
| 193 | im_core::sessions::revoke_session(&server::app(cx).store, &token).await?; | 213 | im_core::sessions::revoke_session(&server::app(cx).store, &token).await?; |
| 214 | + im_core::events::log(&server::app(cx).store, "logout", email.as_deref(), None).await; | ||
| 194 | } | 215 | } |
| 195 | server::clear_session_cookie(cx); | 216 | server::clear_session_cookie(cx); |
| 196 | see("/".to_string()) | 217 | see("/".to_string()) |
crates/im-web/src/config.rsmodified+5 -20
| @@ -1,6 +1,11 @@ | |||
| 1 | //! `config/im.toml`: read before anything is opened, written with development | 1 | //! `config/im.toml`: read before anything is opened, written with development |
| 2 | //! defaults if it is not there yet — the same contract izlek-core's `Config` | 2 | //! defaults if it is not there yet — the same contract izlek-core's `Config` |
| 3 | //! keeps. A broken key stops the boot with its name in the message. | 3 | //! keeps. A broken key stops the boot with its name in the message. |
| 4 | +//! | ||
| 5 | +//! TOML holds deployment facts only — database, listen, issuer. Secrets an | ||
| 6 | +//! admin rotates (the SMTP password) live sealed in the database under | ||
| 7 | +//! `im.key`, set from the admin panel; nothing in this file is worth | ||
| 8 | +//! stealing, which is what lets it stay in git. | ||
| 4 | 9 | ||
| 5 | use std::path::{Path, PathBuf}; | 10 | use std::path::{Path, PathBuf}; |
| 6 | 11 | ||
| @@ -20,16 +25,6 @@ pub struct Config { | |||
| 20 | /// The OIDC issuer — the public base URL every endpoint address and every | 25 | /// The OIDC issuer — the public base URL every endpoint address and every |
| 21 | /// `iss` claim derives from. | 26 | /// `iss` claim derives from. |
| 22 | pub issuer: String, | 27 | pub issuer: String, |
| 23 | - pub smtp: Option<Smtp>, | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | -#[derive(Clone, Deserialize)] | ||
| 27 | -pub struct Smtp { | ||
| 28 | - pub host: String, | ||
| 29 | - pub port: u16, | ||
| 30 | - pub username: String, | ||
| 31 | - pub password: String, | ||
| 32 | - pub from: String, | ||
| 33 | } | 28 | } |
| 34 | 29 | ||
| 35 | #[derive(Deserialize)] | 30 | #[derive(Deserialize)] |
| @@ -37,7 +32,6 @@ struct Raw { | |||
| 37 | database: Option<String>, | 32 | database: Option<String>, |
| 38 | listen: Option<String>, | 33 | listen: Option<String>, |
| 39 | issuer: Option<String>, | 34 | issuer: Option<String>, |
| 40 | - smtp: Option<Smtp>, | ||
| 41 | } | 35 | } |
| 42 | 36 | ||
| 43 | impl Config { | 37 | impl Config { |
| @@ -66,7 +60,6 @@ impl Config { | |||
| 66 | .parse() | 60 | .parse() |
| 67 | .map_err(|e| format!("{PATH}: listen: {e}"))?, | 61 | .map_err(|e| format!("{PATH}: listen: {e}"))?, |
| 68 | issuer: issuer.trim_end_matches('/').to_string(), | 62 | issuer: issuer.trim_end_matches('/').to_string(), |
| 69 | - smtp: raw.smtp, | ||
| 70 | }) | 63 | }) |
| 71 | } | 64 | } |
| 72 | 65 | ||
| @@ -82,14 +75,6 @@ impl Config { | |||
| 82 | format!("database {}", self.database.display()), | 75 | format!("database {}", self.database.display()), |
| 83 | format!("listen {}", self.listen), | 76 | format!("listen {}", self.listen), |
| 84 | format!("issuer {}", self.issuer), | 77 | format!("issuer {}", self.issuer), |
| 85 | - format!( | ||
| 86 | - "mail {}", | ||
| 87 | - if self.smtp.is_some() { | ||
| 88 | - "smtp" | ||
| 89 | - } else { | ||
| 90 | - "stdout (dev)" | ||
| 91 | - } | ||
| 92 | - ), | ||
| 93 | ] | 78 | ] |
| 94 | } | 79 | } |
| 95 | } | 80 | } |
crates/im-web/src/mailer.rsadded+84 -0
| @@ -0,0 +1,84 @@ | |||
| 1 | +//! Sending mail with the sender the admin panel configured. The transport is | ||
| 2 | +//! built per send: settings can change at any moment, and invites are rare — | ||
| 3 | +//! the pool a long-lived transport would buy serves nothing here. | ||
| 4 | + | ||
| 5 | +use im_core::settings::{self, Smtp}; | ||
| 6 | +use im_core::store::Store; | ||
| 7 | + | ||
| 8 | +#[derive(Debug, thiserror::Error)] | ||
| 9 | +pub enum MailError { | ||
| 10 | + #[error("no sender configured")] | ||
| 11 | + NotConfigured, | ||
| 12 | + #[error("mail: {0}")] | ||
| 13 | + Backend(String), | ||
| 14 | + #[error("settings: {0}")] | ||
| 15 | + Settings(#[from] im_core::store::StoreError), | ||
| 16 | +} | ||
| 17 | + | ||
| 18 | +pub type Result<T, E = MailError> = std::result::Result<T, E>; | ||
| 19 | + | ||
| 20 | +fn transport(smtp: &Smtp) -> Result<lettre::AsyncSmtpTransport<lettre::Tokio1Executor>> { | ||
| 21 | + if !smtp.configured() { | ||
| 22 | + return Err(MailError::NotConfigured); | ||
| 23 | + } | ||
| 24 | + let mut builder = lettre::AsyncSmtpTransport::<lettre::Tokio1Executor>::relay(&smtp.host) | ||
| 25 | + .map_err(|e| MailError::Backend(e.to_string()))? | ||
| 26 | + .port(smtp.port); | ||
| 27 | + if !smtp.username.is_empty() { | ||
| 28 | + builder = builder.credentials(lettre::transport::smtp::authentication::Credentials::new( | ||
| 29 | + smtp.username.clone(), | ||
| 30 | + smtp.password.clone().unwrap_or_default(), | ||
| 31 | + )); | ||
| 32 | + } | ||
| 33 | + Ok(builder.build()) | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +async fn send(store: &Store, to: &str, subject: &str, body: String) -> Result<()> { | ||
| 37 | + let smtp = settings::smtp(store).await?; | ||
| 38 | + let message = lettre::Message::builder() | ||
| 39 | + .from( | ||
| 40 | + smtp.from | ||
| 41 | + .parse() | ||
| 42 | + .map_err(|e| MailError::Backend(format!("smtp from: {e}")))?, | ||
| 43 | + ) | ||
| 44 | + .to(to | ||
| 45 | + .parse() | ||
| 46 | + .map_err(|e| MailError::Backend(format!("to: {e}")))?) | ||
| 47 | + .subject(subject) | ||
| 48 | + .body(body) | ||
| 49 | + .map_err(|e| MailError::Backend(e.to_string()))?; | ||
| 50 | + use lettre::AsyncTransport; | ||
| 51 | + transport(&smtp)? | ||
| 52 | + .send(message) | ||
| 53 | + .await | ||
| 54 | + .map_err(|e| MailError::Backend(e.to_string()))?; | ||
| 55 | + Ok(()) | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +/// The invite mail: the link is the whole payload. | ||
| 59 | +pub async fn send_invite(store: &Store, issuer: &str, email: &str, token: &str) -> Result<String> { | ||
| 60 | + let link = format!("{issuer}/invite/{token}"); | ||
| 61 | + send( | ||
| 62 | + store, | ||
| 63 | + email, | ||
| 64 | + "You're invited", | ||
| 65 | + format!( | ||
| 66 | + "You've been invited. This link is yours for {} days:\n\n{link}\n", | ||
| 67 | + im_core::accounts::INVITE_DAYS | ||
| 68 | + ), | ||
| 69 | + ) | ||
| 70 | + .await?; | ||
| 71 | + Ok(link) | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// The panel's test button: proves the sender end to end, to the admin's own | ||
| 75 | +/// address. | ||
| 76 | +pub async fn send_test(store: &Store, to: &str) -> Result<()> { | ||
| 77 | + send( | ||
| 78 | + store, | ||
| 79 | + to, | ||
| 80 | + "im mail test", | ||
| 81 | + "im can send mail from this sender.\n".into(), | ||
| 82 | + ) | ||
| 83 | + .await | ||
| 84 | +} | ||
crates/im-web/src/main.rsmodified+70 -52
| @@ -1,5 +1,6 @@ | |||
| 1 | -//! im — the IzlekLab SSO. Server by default; `invite` and `create-client` | 1 | +//! im — the IzlekLab SSO. Server by default; the CLI covers bootstrapping |
| 2 | -//! are the admin surface until there is a settings screen. | 2 | +//! (the first admin invite) and the two admin actions that must work even |
| 3 | +//! when the panel cannot be reached. Everything else lives in /admin. | ||
| 3 | 4 | ||
| 4 | use std::sync::Arc; | 5 | use std::sync::Arc; |
| 5 | 6 | ||
| @@ -9,9 +10,11 @@ use topcoat::asset::RouterBuilderAssetExt; | |||
| 9 | use topcoat::cookie::RouterBuilderCookieExt; | 10 | use topcoat::cookie::RouterBuilderCookieExt; |
| 10 | use topcoat::router::{Router, RouterBuilderDiscoverExt, route}; | 11 | use topcoat::router::{Router, RouterBuilderDiscoverExt, route}; |
| 11 | 12 | ||
| 13 | +mod admin; | ||
| 12 | mod auth; | 14 | mod auth; |
| 13 | mod config; | 15 | mod config; |
| 14 | mod layout; | 16 | mod layout; |
| 17 | +mod mailer; | ||
| 15 | mod oidc; | 18 | mod oidc; |
| 16 | mod pages; | 19 | mod pages; |
| 17 | mod server; | 20 | mod server; |
| @@ -37,11 +40,31 @@ async fn main() { | |||
| 37 | match args.get(1).map(String::as_str) { | 40 | match args.get(1).map(String::as_str) { |
| 38 | None => serve(config).await, | 41 | None => serve(config).await, |
| 39 | Some("invite") => { | 42 | Some("invite") => { |
| 43 | + let mut email = None; | ||
| 44 | + let mut admin = false; | ||
| 45 | + for arg in &args[2..] { | ||
| 46 | + match arg.as_str() { | ||
| 47 | + "--admin" => admin = true, | ||
| 48 | + other if email.is_none() => email = Some(other.to_string()), | ||
| 49 | + other => { | ||
| 50 | + eprintln!("usage: im-web invite <email> [--admin]"); | ||
| 51 | + eprintln!("im: unexpected argument {other}"); | ||
| 52 | + std::process::exit(2); | ||
| 53 | + } | ||
| 54 | + } | ||
| 55 | + } | ||
| 56 | + let Some(email) = email else { | ||
| 57 | + eprintln!("usage: im-web invite <email> [--admin]"); | ||
| 58 | + std::process::exit(2); | ||
| 59 | + }; | ||
| 60 | + invite(config, &email, admin).await; | ||
| 61 | + } | ||
| 62 | + Some("revoke") => { | ||
| 40 | let Some(email) = args.get(2) else { | 63 | let Some(email) = args.get(2) else { |
| 41 | - eprintln!("usage: im-web invite <email>"); | 64 | + eprintln!("usage: im-web revoke <email>"); |
| 42 | std::process::exit(2); | 65 | std::process::exit(2); |
| 43 | }; | 66 | }; |
| 44 | - invite(config, email).await; | 67 | + revoke(config, email).await; |
| 45 | } | 68 | } |
| 46 | Some("create-client") => { | 69 | Some("create-client") => { |
| 47 | let (Some(name), uris) = (args.get(2), args.get(3..).unwrap_or(&[])) else { | 70 | let (Some(name), uris) = (args.get(2), args.get(3..).unwrap_or(&[])) else { |
| @@ -56,7 +79,7 @@ async fn main() { | |||
| 56 | } | 79 | } |
| 57 | Some(other) => { | 80 | Some(other) => { |
| 58 | eprintln!( | 81 | eprintln!( |
| 59 | - "im: unknown command {other:?} (expected: invite, create-client, or none to serve)" | 82 | + "im: unknown command {other:?} (expected: invite, revoke, create-client, or none to serve)" |
| 60 | ); | 83 | ); |
| 61 | std::process::exit(2); | 84 | std::process::exit(2); |
| 62 | } | 85 | } |
| @@ -71,44 +94,54 @@ async fn open_store(config: &Config) -> Arc<Store> { | |||
| 71 | ) | 94 | ) |
| 72 | } | 95 | } |
| 73 | 96 | ||
| 74 | -/// `im-web invite <email>`: creates the invite, mails it when SMTP is | 97 | +/// `im-web invite <email> [--admin]`: creates the invite, mails it when the |
| 75 | -/// configured, prints the link otherwise (dev mode). | 98 | +/// panel has configured a sender, prints the link otherwise (dev mode). |
| 76 | -async fn invite(config: Config, email: &str) { | 99 | +/// |
| 100 | +/// Needs the server stopped: Turso is a single-writer engine, and this | ||
| 101 | +/// process would hold the same file. | ||
| 102 | +async fn invite(config: Config, email: &str, admin: bool) { | ||
| 77 | let store = open_store(&config).await; | 103 | let store = open_store(&config).await; |
| 78 | - let token = im_core::accounts::create_invite(&store, email, None) | 104 | + let token = im_core::accounts::create_invite(&store, email, None, admin) |
| 79 | .await | 105 | .await |
| 80 | .expect("failed to create the invite"); | 106 | .expect("failed to create the invite"); |
| 81 | - let link = format!("{}/invite/{}", config.issuer, token.expose()); | 107 | + im_core::events::log( |
| 82 | - match build_mailer(&config) { | 108 | + &store, |
| 83 | - Some(mailer) => { | 109 | + "invite_created", |
| 84 | - let message = lettre::Message::builder() | 110 | + Some("cli"), |
| 85 | - .from( | 111 | + Some(&format!( |
| 86 | - config | 112 | + "for {email}{}", |
| 87 | - .smtp | 113 | + if admin { " (admin)" } else { "" } |
| 88 | - .as_ref() | 114 | + )), |
| 89 | - .unwrap() | 115 | + ) |
| 90 | - .from | 116 | + .await; |
| 91 | - .parse() | 117 | + match mailer::send_invite(&store, &config.issuer, email, token.expose()).await { |
| 92 | - .expect("smtp.from"), | 118 | + Ok(link) => println!("im invite mailed to {email}\nim {link}"), |
| 93 | - ) | 119 | + Err(_) => println!( |
| 94 | - .to(email.parse().expect("invite email")) | 120 | + "im invite for {email}: {}/invite/{}", |
| 95 | - .subject("You're invited") | 121 | + config.issuer, |
| 96 | - .body(format!( | 122 | + token.expose() |
| 97 | - "You've been invited. This link is yours for {} days:\n\n{link}\n", | 123 | + ), |
| 98 | - im_core::accounts::INVITE_DAYS | ||
| 99 | - )) | ||
| 100 | - .expect("invite mail"); | ||
| 101 | - use lettre::AsyncTransport; | ||
| 102 | - mailer | ||
| 103 | - .send(message) | ||
| 104 | - .await | ||
| 105 | - .expect("failed to send the invite"); | ||
| 106 | - println!("im invite mailed to {email}"); | ||
| 107 | - } | ||
| 108 | - None => println!("im invite for {email}: {link}"), | ||
| 109 | } | 124 | } |
| 110 | } | 125 | } |
| 111 | 126 | ||
| 127 | +/// `im-web revoke <email>`: signs the person out everywhere — central | ||
| 128 | +/// sessions, refresh tokens, and the app sessions introspection answers for. | ||
| 129 | +async fn revoke(config: Config, email: &str) { | ||
| 130 | + let store = open_store(&config).await; | ||
| 131 | + let Some(user) = im_core::accounts::user_by_email(&store, email) | ||
| 132 | + .await | ||
| 133 | + .expect("failed to read users") | ||
| 134 | + else { | ||
| 135 | + eprintln!("im: no account for {email}"); | ||
| 136 | + std::process::exit(1); | ||
| 137 | + }; | ||
| 138 | + let count = im_core::sessions::revoke_user_sessions(&store, &user.id) | ||
| 139 | + .await | ||
| 140 | + .expect("failed to revoke"); | ||
| 141 | + im_core::events::log(&store, "sessions_revoked", Some("cli"), Some(email)).await; | ||
| 142 | + println!("im {email}: {count} session(s) revoked, everywhere, now"); | ||
| 143 | +} | ||
| 144 | + | ||
| 112 | /// `im-web create-client <name> <uris...>`: registers a relying party and | 145 | /// `im-web create-client <name> <uris...>`: registers a relying party and |
| 113 | /// prints the secret exactly once. | 146 | /// prints the secret exactly once. |
| 114 | async fn create_client(config: Config, name: &str, uris: &[String]) { | 147 | async fn create_client(config: Config, name: &str, uris: &[String]) { |
| @@ -122,21 +155,6 @@ async fn create_client(config: Config, name: &str, uris: &[String]) { | |||
| 122 | println!(" (the secret is shown once; its digest is all the database keeps)"); | 155 | println!(" (the secret is shown once; its digest is all the database keeps)"); |
| 123 | } | 156 | } |
| 124 | 157 | ||
| 125 | -fn build_mailer(config: &Config) -> Option<lettre::AsyncSmtpTransport<lettre::Tokio1Executor>> { | ||
| 126 | - let smtp = config.smtp.as_ref()?; | ||
| 127 | - let creds = lettre::transport::smtp::authentication::Credentials::new( | ||
| 128 | - smtp.username.clone(), | ||
| 129 | - smtp.password.clone(), | ||
| 130 | - ); | ||
| 131 | - Some( | ||
| 132 | - lettre::AsyncSmtpTransport::<lettre::Tokio1Executor>::relay(&smtp.host) | ||
| 133 | - .expect("smtp relay") | ||
| 134 | - .port(smtp.port) | ||
| 135 | - .credentials(creds) | ||
| 136 | - .build(), | ||
| 137 | - ) | ||
| 138 | -} | ||
| 139 | - | ||
| 140 | async fn serve(config: Config) { | 158 | async fn serve(config: Config) { |
| 141 | for line in config.report() { | 159 | for line in config.report() { |
| 142 | println!("im {line}"); | 160 | println!("im {line}"); |
crates/im-web/src/oidc.rsmodified+64 -4
| @@ -81,7 +81,7 @@ fn bad_request(cx: &Cx) -> Result<Response> { | |||
| 81 | 81 | ||
| 82 | /// Percent-encodes a value for a query pair — the `back` a login carries is | 82 | /// Percent-encodes a value for a query pair — the `back` a login carries is |
| 83 | /// a local `/authorize?...` URL, full of `?&=` of its own. | 83 | /// a local `/authorize?...` URL, full of `?&=` of its own. |
| 84 | -fn urlencode(raw: &str) -> String { | 84 | +pub(crate) fn urlencode(raw: &str) -> String { |
| 85 | let mut out = String::with_capacity(raw.len()); | 85 | let mut out = String::with_capacity(raw.len()); |
| 86 | for byte in raw.bytes() { | 86 | for byte in raw.bytes() { |
| 87 | match byte { | 87 | match byte { |
| @@ -228,13 +228,22 @@ async fn mint_tokens( | |||
| 228 | )) | 228 | )) |
| 229 | } | 229 | } |
| 230 | 230 | ||
| 231 | -fn token_answer(cx: &Cx, access: String, id: String, refresh: String) -> Result<Response> { | 231 | +fn token_answer( |
| 232 | + cx: &Cx, | ||
| 233 | + access: String, | ||
| 234 | + id: String, | ||
| 235 | + refresh: String, | ||
| 236 | + app_session: Option<String>, | ||
| 237 | +) -> Result<Response> { | ||
| 232 | Json(serde_json::json!({ | 238 | Json(serde_json::json!({ |
| 233 | "access_token": access, | 239 | "access_token": access, |
| 234 | "token_type": "Bearer", | 240 | "token_type": "Bearer", |
| 235 | "expires_in": oidc::TOKEN_SECONDS, | 241 | "expires_in": oidc::TOKEN_SECONDS, |
| 236 | "refresh_token": refresh, | 242 | "refresh_token": refresh, |
| 237 | "id_token": id, | 243 | "id_token": id, |
| 244 | + // Not OIDC — ours: the opaque, introspected session im-client holds. | ||
| 245 | + // Standard clients ignore it; ours never leaves its ghost window. | ||
| 246 | + "app_session": app_session, | ||
| 238 | })) | 247 | })) |
| 239 | .into_response(cx) | 248 | .into_response(cx) |
| 240 | } | 249 | } |
| @@ -286,7 +295,27 @@ async fn exchange(cx: &Cx, Form(input): Form<TokenForm>) -> Result<Response> { | |||
| 286 | &consumed.session_hash, | 295 | &consumed.session_hash, |
| 287 | ) | 296 | ) |
| 288 | .await?; | 297 | .await?; |
| 289 | - token_answer(cx, access, id, refresh.expose().to_string()) | 298 | + let app_session = oidc::issue_app_session( |
| 299 | + &app(cx).store, | ||
| 300 | + &user.id, | ||
| 301 | + &client.client_id, | ||
| 302 | + &consumed.session_hash, | ||
| 303 | + ) | ||
| 304 | + .await?; | ||
| 305 | + im_core::events::log( | ||
| 306 | + &app(cx).store, | ||
| 307 | + "code_exchanged", | ||
| 308 | + Some(&user.email), | ||
| 309 | + Some(&format!("via {}", client.name)), | ||
| 310 | + ) | ||
| 311 | + .await; | ||
| 312 | + token_answer( | ||
| 313 | + cx, | ||
| 314 | + access, | ||
| 315 | + id, | ||
| 316 | + refresh.expose().to_string(), | ||
| 317 | + Some(app_session.expose().to_string()), | ||
| 318 | + ) | ||
| 290 | } | 319 | } |
| 291 | "refresh_token" => { | 320 | "refresh_token" => { |
| 292 | let Some(presented) = input.refresh_token else { | 321 | let Some(presented) = input.refresh_token else { |
| @@ -306,12 +335,43 @@ async fn exchange(cx: &Cx, Form(input): Form<TokenForm>) -> Result<Response> { | |||
| 306 | return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant"); | 335 | return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant"); |
| 307 | } | 336 | } |
| 308 | let (access, id) = mint_tokens(cx, &user, &client.client_id, None).await?; | 337 | let (access, id) = mint_tokens(cx, &user, &client.client_id, None).await?; |
| 309 | - token_answer(cx, access, id, fresh.expose().to_string()) | 338 | + token_answer(cx, access, id, fresh.expose().to_string(), None) |
| 310 | } | 339 | } |
| 311 | _ => oidc_error(cx, StatusCode::BAD_REQUEST, "unsupported_grant_type"), | 340 | _ => oidc_error(cx, StatusCode::BAD_REQUEST, "unsupported_grant_type"), |
| 312 | } | 341 | } |
| 313 | } | 342 | } |
| 314 | 343 | ||
| 344 | +// --------------------------------------------------------------------------- | ||
| 345 | +// /introspect (RFC 7662): the per-request liveness check im-client makes | ||
| 346 | +// --------------------------------------------------------------------------- | ||
| 347 | + | ||
| 348 | +#[derive(Deserialize)] | ||
| 349 | +struct IntrospectForm { | ||
| 350 | + token: String, | ||
| 351 | + client_id: Option<String>, | ||
| 352 | + client_secret: Option<String>, | ||
| 353 | +} | ||
| 354 | + | ||
| 355 | +/// The app asks, per request: is this session alive, and whose is it? The | ||
| 356 | +/// answer is never cached server-side, so a revoked user is inactive on the | ||
| 357 | +/// very next call. | ||
| 358 | +#[route(POST "/introspect")] | ||
| 359 | +async fn introspect(cx: &Cx, Form(input): Form<IntrospectForm>) -> Result<Response> { | ||
| 360 | + let (Some(client_id), Some(secret)) = (input.client_id, input.client_secret) else { | ||
| 361 | + return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client"); | ||
| 362 | + }; | ||
| 363 | + let Some(client) = oidc::client_by_id(&app(cx).store, &client_id).await? else { | ||
| 364 | + return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client"); | ||
| 365 | + }; | ||
| 366 | + if !oidc::verify_client_secret(&client, &secret) { | ||
| 367 | + return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client"); | ||
| 368 | + } | ||
| 369 | + let answer = oidc::introspect_app_session(&app(cx).store, &input.token, &client_id) | ||
| 370 | + .await? | ||
| 371 | + .unwrap_or_else(|| serde_json::json!({ "active": false })); | ||
| 372 | + Json(answer).into_response(cx) | ||
| 373 | +} | ||
| 374 | + | ||
| 315 | // --------------------------------------------------------------------------- | 375 | // --------------------------------------------------------------------------- |
| 316 | // /userinfo | 376 | // /userinfo |
| 317 | // --------------------------------------------------------------------------- | 377 | // --------------------------------------------------------------------------- |
crates/im-web/src/pages.rsmodified+3 -0
| @@ -408,6 +408,9 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { | |||
| 408 | <span class="auth-submit-text">"Sign out everywhere"</span> | 408 | <span class="auth-submit-text">"Sign out everywhere"</span> |
| 409 | </button> | 409 | </button> |
| 410 | </form> | 410 | </form> |
| 411 | + if user.admin { | ||
| 412 | + <a class="auth-alt" href="/admin">"Admin panel"</a> | ||
| 413 | + } | ||
| 411 | </div> | 414 | </div> |
| 412 | <div class="auth-footer">"im · IzlekLab SSO"</div> | 415 | <div class="auth-footer">"im · IzlekLab SSO"</div> |
| 413 | </div> | 416 | </div> |
style/main.scssmodified+146 -0
| @@ -372,3 +372,149 @@ body:has(.auth-stage) { | |||
| 372 | @media (max-width: 720px) { | 372 | @media (max-width: 720px) { |
| 373 | .auth-stage { padding: 0 16px 24px; } | 373 | .auth-stage { padding: 0 16px 24px; } |
| 374 | } | 374 | } |
| 375 | + | ||
| 376 | +// --- Admin panel ------------------------------------------------------------ | ||
| 377 | +// Same skin, different posture: top-anchored and wider than the auth stage — | ||
| 378 | +// a tool, not a gate. | ||
| 379 | + | ||
| 380 | +body:has(.admin-shell) { | ||
| 381 | + min-height: 100vh; | ||
| 382 | + min-height: 100dvh; | ||
| 383 | +} | ||
| 384 | + | ||
| 385 | +.admin-shell { | ||
| 386 | + display: flex; | ||
| 387 | + justify-content: center; | ||
| 388 | + padding: 24px 24px 48px; | ||
| 389 | +} | ||
| 390 | + | ||
| 391 | +.admin-column { | ||
| 392 | + width: 760px; | ||
| 393 | + max-width: 100%; | ||
| 394 | + display: flex; | ||
| 395 | + flex-direction: column; | ||
| 396 | + gap: 16px; | ||
| 397 | +} | ||
| 398 | + | ||
| 399 | +.admin-bar { | ||
| 400 | + display: flex; | ||
| 401 | + align-items: center; | ||
| 402 | + gap: 20px; | ||
| 403 | + height: var(--control-h-lg); | ||
| 404 | + | ||
| 405 | + .wordmark-text { font-size: 15px; } | ||
| 406 | +} | ||
| 407 | + | ||
| 408 | +.admin-tabs { | ||
| 409 | + display: flex; | ||
| 410 | + gap: 16px; | ||
| 411 | +} | ||
| 412 | + | ||
| 413 | +.admin-nav { | ||
| 414 | + font-family: var(--font-mono); | ||
| 415 | + font-size: 10px; | ||
| 416 | + letter-spacing: 0.08em; | ||
| 417 | + text-transform: uppercase; | ||
| 418 | + color: var(--muted); | ||
| 419 | + text-decoration: none; | ||
| 420 | + padding-bottom: 2px; | ||
| 421 | + | ||
| 422 | + &:hover { color: var(--ink); } | ||
| 423 | + | ||
| 424 | + &-on { | ||
| 425 | + color: var(--ink); | ||
| 426 | + box-shadow: inset 0 -2px 0 var(--ink); | ||
| 427 | + } | ||
| 428 | +} | ||
| 429 | + | ||
| 430 | +.admin-bar .auth-alt { margin-left: auto; align-self: auto; } | ||
| 431 | + | ||
| 432 | +.admin-card { | ||
| 433 | + background: var(--surface); | ||
| 434 | + border: 1px solid var(--border); | ||
| 435 | + border-radius: var(--radius-lg); | ||
| 436 | + padding: 24px; | ||
| 437 | + display: flex; | ||
| 438 | + flex-direction: column; | ||
| 439 | + gap: 16px; | ||
| 440 | +} | ||
| 441 | + | ||
| 442 | +.admin-table { | ||
| 443 | + width: 100%; | ||
| 444 | + border-collapse: collapse; | ||
| 445 | + font-size: 13px; | ||
| 446 | + | ||
| 447 | + th { | ||
| 448 | + font-family: var(--font-mono); | ||
| 449 | + font-size: 10px; | ||
| 450 | + letter-spacing: 0.08em; | ||
| 451 | + color: var(--muted-soft); | ||
| 452 | + text-align: left; | ||
| 453 | + padding: 0 12px 6px 0; | ||
| 454 | + } | ||
| 455 | + | ||
| 456 | + td { | ||
| 457 | + padding: 8px 12px 8px 0; | ||
| 458 | + border-top: 1px solid var(--border-soft); | ||
| 459 | + vertical-align: middle; | ||
| 460 | + } | ||
| 461 | +} | ||
| 462 | + | ||
| 463 | +.mono { font-family: var(--font-mono); } | ||
| 464 | +.muted { color: var(--muted); } | ||
| 465 | + | ||
| 466 | +.actions { | ||
| 467 | + display: flex; | ||
| 468 | + gap: 8px; | ||
| 469 | + justify-content: flex-end; | ||
| 470 | + | ||
| 471 | + form { display: inline; } | ||
| 472 | +} | ||
| 473 | + | ||
| 474 | +// A quiet row-level button, back on --surface like İzlek's `.quiet`. | ||
| 475 | +.admin-action { | ||
| 476 | + height: var(--control-h); | ||
| 477 | + --control-h: 32px; | ||
| 478 | + padding: 0 10px; | ||
| 479 | + background: var(--surface); | ||
| 480 | + border: 1px solid var(--border-strong); | ||
| 481 | + border-radius: var(--radius); | ||
| 482 | + color: var(--ink); | ||
| 483 | + font-size: 12px; | ||
| 484 | + cursor: pointer; | ||
| 485 | + | ||
| 486 | + &:hover { background: var(--row-hover, var(--panel-sunken)); } | ||
| 487 | +} | ||
| 488 | + | ||
| 489 | +.admin-action-wide { width: 100%; } | ||
| 490 | + | ||
| 491 | +.admin-invite { | ||
| 492 | + display: flex; | ||
| 493 | + gap: 8px; | ||
| 494 | + align-items: center; | ||
| 495 | + | ||
| 496 | + .auth-input { flex: 1; } | ||
| 497 | + .admin-action-wide { width: auto; padding: 0 20px; } | ||
| 498 | +} | ||
| 499 | + | ||
| 500 | +.admin-check { | ||
| 501 | + display: flex; | ||
| 502 | + align-items: center; | ||
| 503 | + gap: 6px; | ||
| 504 | + font-size: 12px; | ||
| 505 | + color: var(--muted); | ||
| 506 | + white-space: nowrap; | ||
| 507 | +} | ||
| 508 | + | ||
| 509 | +.admin-form { | ||
| 510 | + display: flex; | ||
| 511 | + flex-direction: column; | ||
| 512 | + gap: 12px; | ||
| 513 | +} | ||
| 514 | + | ||
| 515 | +input[type="checkbox"] { accent-color: var(--accent); } | ||
| 516 | + | ||
| 517 | +@media (max-width: 720px) { | ||
| 518 | + .admin-shell { padding: 16px 12px 32px; } | ||
| 519 | + .admin-invite { flex-wrap: wrap; } | ||
| 520 | +} | ||