Sessions listed per device — IP, agent, last seen — revocable by their owner and by admin
Browse files at this commit5182e938445c6e36a68aa88a01156fee7afb3b9fParent: 04fdaa910 changed files +668 -25
- crates/im-core/src/accounts.rs +10 -2
- crates/im-core/src/oidc.rs +10 -4
- crates/im-core/src/sessions.rs +252 -9
- crates/im-core/src/store.rs +24 -6
- crates/im-migrate/src/main.rs +18 -2
- crates/im-web/assets/main.css +57 -0
- crates/im-web/src/admin.rs +86 -0
- crates/im-web/src/auth.rs +65 -2
- crates/im-web/src/pages.rs +83 -0
- style/main.scss +63 -0
crates/im-core/src/accounts.rsmodified+10 -2
| @@ -1028,7 +1028,11 @@ mod tests { | |||
| 1028 | let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") | 1028 | let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") |
| 1029 | .await | 1029 | .await |
| 1030 | .unwrap(); | 1030 | .unwrap(); |
| 1031 | - let session = crate::sessions::create_session(&store, &user.id) | 1031 | + let session = crate::sessions::create_session( |
| 1032 | + &store, | ||
| 1033 | + &user.id, | ||
| 1034 | + &crate::sessions::SessionMeta::default(), | ||
| 1035 | + ) | ||
| 1032 | .await | 1036 | .await |
| 1033 | .unwrap(); | 1037 | .unwrap(); |
| 1034 | 1038 | ||
| @@ -1057,7 +1061,11 @@ mod tests { | |||
| 1057 | let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") | 1061 | let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") |
| 1058 | .await | 1062 | .await |
| 1059 | .unwrap(); | 1063 | .unwrap(); |
| 1060 | - let session = crate::sessions::create_session(&store, &user.id) | 1064 | + let session = crate::sessions::create_session( |
| 1065 | + &store, | ||
| 1066 | + &user.id, | ||
| 1067 | + &crate::sessions::SessionMeta::default(), | ||
| 1068 | + ) | ||
| 1061 | .await | 1069 | .await |
| 1062 | .unwrap(); | 1070 | .unwrap(); |
| 1063 | 1071 | ||
crates/im-core/src/oidc.rsmodified+10 -4
| @@ -517,14 +517,16 @@ pub async fn introspect_app_session( | |||
| 517 | mod tests { | 517 | mod tests { |
| 518 | use super::*; | 518 | use super::*; |
| 519 | use crate::accounts::{create_invite, create_user_from_invite}; | 519 | use crate::accounts::{create_invite, create_user_from_invite}; |
| 520 | - use crate::sessions::create_session; | 520 | + use crate::sessions::{SessionMeta, create_session}; |
| 521 | use rsa::signature::Verifier; | 521 | use rsa::signature::Verifier; |
| 522 | use std::path::Path; | 522 | use std::path::Path; |
| 523 | 523 | ||
| 524 | #[tokio::test] | 524 | #[tokio::test] |
| 525 | async fn app_session_introspection_and_instant_revoke() { | 525 | async fn app_session_introspection_and_instant_revoke() { |
| 526 | let (store, client_id, user_id) = fixture().await; | 526 | let (store, client_id, user_id) = fixture().await; |
| 527 | - let session = create_session(&store, &user_id).await.unwrap(); | 527 | + let session = create_session(&store, &user_id, &SessionMeta::default()) |
| 528 | + .await | ||
| 529 | + .unwrap(); | ||
| 528 | let app_token = issue_app_session(&store, &user_id, &client_id, &session.hash()) | 530 | let app_token = issue_app_session(&store, &user_id, &client_id, &session.hash()) |
| 529 | .await | 531 | .await |
| 530 | .unwrap(); | 532 | .unwrap(); |
| @@ -632,7 +634,9 @@ mod tests { | |||
| 632 | #[tokio::test] | 634 | #[tokio::test] |
| 633 | async fn refresh_rotates_and_dies_with_session() { | 635 | async fn refresh_rotates_and_dies_with_session() { |
| 634 | let (store, client_id, user_id) = fixture().await; | 636 | let (store, client_id, user_id) = fixture().await; |
| 635 | - let session = create_session(&store, &user_id).await.unwrap(); | 637 | + let session = create_session(&store, &user_id, &SessionMeta::default()) |
| 638 | + .await | ||
| 639 | + .unwrap(); | ||
| 636 | let token = issue_refresh(&store, &user_id, &client_id, &session.hash()) | 640 | let token = issue_refresh(&store, &user_id, &client_id, &session.hash()) |
| 637 | .await | 641 | .await |
| 638 | .unwrap(); | 642 | .unwrap(); |
| @@ -658,7 +662,9 @@ mod tests { | |||
| 658 | ); | 662 | ); |
| 659 | 663 | ||
| 660 | // Revoking the central session retires the refresh chain. | 664 | // Revoking the central session retires the refresh chain. |
| 661 | - let session2 = create_session(&store, &user_id).await.unwrap(); | 665 | + let session2 = create_session(&store, &user_id, &SessionMeta::default()) |
| 666 | + .await | ||
| 667 | + .unwrap(); | ||
| 662 | let token2 = issue_refresh(&store, &user_id, &client_id, &session2.hash()) | 668 | let token2 = issue_refresh(&store, &user_id, &client_id, &session2.hash()) |
| 663 | .await | 669 | .await |
| 664 | .unwrap(); | 670 | .unwrap(); |
crates/im-core/src/sessions.rsmodified+252 -9
| @@ -3,7 +3,8 @@ | |||
| 3 | //! A session is what makes SSO single: once a browser holds one, every app's | 3 | //! A session is what makes SSO single: once a browser holds one, every app's |
| 4 | //! `/authorize` round-trip is a silent redirect. Revoking a session also | 4 | //! `/authorize` round-trip is a silent redirect. Revoking a session also |
| 5 | //! revokes every refresh token bound to it — that is what "log me out | 5 | //! revokes every refresh token bound to it — that is what "log me out |
| 6 | -//! everywhere" means here. | 6 | +//! everywhere" means here. Each session also remembers its browser (IP, |
| 7 | +//! agent, last seen) so the sessions list can show every device separately. | ||
| 7 | 8 | ||
| 8 | use crate::accounts::{Token, hash_token}; | 9 | use crate::accounts::{Token, hash_token}; |
| 9 | use crate::model::{User, UserId}; | 10 | use crate::model::{User, UserId}; |
| @@ -14,21 +15,42 @@ use crate::store::{self, Result, Store, backend}; | |||
| 14 | /// Max-Age (which is set before the store is in hand). | 15 | /// Max-Age (which is set before the store is in hand). |
| 15 | pub const SESSION_DAYS: i64 = 30; | 16 | pub const SESSION_DAYS: i64 = 30; |
| 16 | 17 | ||
| 18 | +/// Creation-time facts about the client holding the session. | ||
| 19 | +#[derive(Debug, Clone, Default)] | ||
| 20 | +pub struct SessionMeta { | ||
| 21 | + pub ip: Option<String>, | ||
| 22 | + pub agent: Option<String>, | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +/// One live central session, as the sessions list shows it. | ||
| 26 | +#[derive(Debug, Clone)] | ||
| 27 | +pub struct SessionInfo { | ||
| 28 | + pub token_hash: String, | ||
| 29 | + pub created_at: time::OffsetDateTime, | ||
| 30 | + pub expires_at: time::OffsetDateTime, | ||
| 31 | + pub seen_at: Option<time::OffsetDateTime>, | ||
| 32 | + pub ip: Option<String>, | ||
| 33 | + pub agent: Option<String>, | ||
| 34 | +} | ||
| 35 | + | ||
| 17 | /// Creates a session for `user`, returning the raw cookie token. The row | 36 | /// Creates a session for `user`, returning the raw cookie token. The row |
| 18 | -/// holds only its digest. | 37 | +/// holds only its digest, plus what `meta` says about the browser — and the |
| 19 | -pub async fn create_session(store: &Store, user: &UserId) -> Result<Token> { | 38 | +/// first sighting is creation itself, so `seen_at` starts at `created_at`. |
| 39 | +pub async fn create_session(store: &Store, user: &UserId, meta: &SessionMeta) -> Result<Token> { | ||
| 20 | let token = Token::mint(); | 40 | let token = Token::mint(); |
| 21 | let now = store::now(); | 41 | let now = store::now(); |
| 22 | let days = crate::settings::policy(store).await?.session_days; | 42 | let days = crate::settings::policy(store).await?.session_days; |
| 23 | let conn = store.conn.lock().await; | 43 | let conn = store.conn.lock().await; |
| 24 | conn.execute( | 44 | conn.execute( |
| 25 | - "INSERT INTO sessions (token_hash, user_id, created_at, expires_at) \ | 45 | + "INSERT INTO sessions (token_hash, user_id, created_at, expires_at, ip, agent, seen_at) \ |
| 26 | - VALUES (?1, ?2, ?3, ?4)", | 46 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?3)", |
| 27 | turso::params![ | 47 | turso::params![ |
| 28 | token.hash(), | 48 | token.hash(), |
| 29 | user.to_string(), | 49 | user.to_string(), |
| 30 | store::stamp(now)?, | 50 | store::stamp(now)?, |
| 31 | store::stamp(now + time::Duration::days(days))?, | 51 | store::stamp(now + time::Duration::days(days))?, |
| 52 | + meta.ip.clone(), | ||
| 53 | + meta.agent.clone(), | ||
| 32 | ], | 54 | ], |
| 33 | ) | 55 | ) |
| 34 | .await | 56 | .await |
| @@ -64,7 +86,25 @@ pub async fn resolve_session(store: &Store, token: &str) -> Result<Option<User>> | |||
| 64 | return Ok(None); | 86 | return Ok(None); |
| 65 | }; | 87 | }; |
| 66 | match crate::accounts::user_by_id(store, &user_id).await? { | 88 | match crate::accounts::user_by_id(store, &user_id).await? { |
| 67 | - Some(user) if !user.disabled => Ok(Some(user)), | 89 | + Some(user) if !user.disabled => { |
| 90 | + // The sighting lands after the fact, guard long dropped: one | ||
| 91 | + // UPDATE per call, and the throttle keeps it near one write per | ||
| 92 | + // five minutes per session no matter how chatty the browser is. | ||
| 93 | + let now = store::now(); | ||
| 94 | + let conn = store.conn.lock().await; | ||
| 95 | + conn.execute( | ||
| 96 | + "UPDATE sessions SET seen_at = ?1 WHERE token_hash = ?2 \ | ||
| 97 | + AND (seen_at IS NULL OR seen_at < ?3)", | ||
| 98 | + turso::params![ | ||
| 99 | + store::stamp(now)?, | ||
| 100 | + hash_token(token), | ||
| 101 | + store::stamp(now - time::Duration::minutes(5))?, | ||
| 102 | + ], | ||
| 103 | + ) | ||
| 104 | + .await | ||
| 105 | + .map_err(backend)?; | ||
| 106 | + Ok(Some(user)) | ||
| 107 | + } | ||
| 68 | _ => Ok(None), | 108 | _ => Ok(None), |
| 69 | } | 109 | } |
| 70 | } | 110 | } |
| @@ -102,6 +142,69 @@ pub(crate) async fn revoke_session_hash(store: &Store, hash: &str) -> Result<()> | |||
| 102 | Ok(()) | 142 | Ok(()) |
| 103 | } | 143 | } |
| 104 | 144 | ||
| 145 | +/// Active (not revoked, not expired) sessions of `user`, newest first. | ||
| 146 | +pub async fn list_sessions(store: &Store, user: &UserId) -> Result<Vec<SessionInfo>> { | ||
| 147 | + // Revocation filters in SQL; expiry is a stamp comparison, done beside | ||
| 148 | + // `resolve_session` in Rust where a corrupt stamp surfaces as an error. | ||
| 149 | + let now = store::now(); | ||
| 150 | + let conn = store.conn.lock().await; | ||
| 151 | + let mut rows = conn | ||
| 152 | + .query( | ||
| 153 | + "SELECT token_hash, created_at, expires_at, seen_at, ip, agent FROM sessions \ | ||
| 154 | + WHERE user_id = ?1 AND revoked_at IS NULL ORDER BY created_at DESC", | ||
| 155 | + turso::params![user.to_string()], | ||
| 156 | + ) | ||
| 157 | + .await | ||
| 158 | + .map_err(backend)?; | ||
| 159 | + let mut out = Vec::new(); | ||
| 160 | + while let Some(row) = rows.next().await.map_err(backend)? { | ||
| 161 | + let expires_at = store::parse_stamp(&store::text(&row, 2)?)?; | ||
| 162 | + if expires_at < now { | ||
| 163 | + continue; | ||
| 164 | + } | ||
| 165 | + let seen_at = match store::opt_text(&row, 3)? { | ||
| 166 | + Some(raw) => Some(store::parse_stamp(&raw)?), | ||
| 167 | + None => None, | ||
| 168 | + }; | ||
| 169 | + out.push(SessionInfo { | ||
| 170 | + token_hash: store::text(&row, 0)?, | ||
| 171 | + created_at: store::parse_stamp(&store::text(&row, 1)?)?, | ||
| 172 | + expires_at, | ||
| 173 | + seen_at, | ||
| 174 | + ip: store::opt_text(&row, 4)?, | ||
| 175 | + agent: store::opt_text(&row, 5)?, | ||
| 176 | + }); | ||
| 177 | + } | ||
| 178 | + Ok(out) | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +/// Revokes `hash` only if it names a session of `user`; true when it did. | ||
| 182 | +/// The cascade is [`revoke_session_hash`]'s, so a device gone from the list | ||
| 183 | +/// takes its app tokens down with it. | ||
| 184 | +pub async fn revoke_owned_session(store: &Store, user: &UserId, hash: &str) -> Result<bool> { | ||
| 185 | + // Ownership reads first: a hash naming someone else's session — or no | ||
| 186 | + // session at all — is a quiet false, never a revoke. | ||
| 187 | + let owned = { | ||
| 188 | + let conn = store.conn.lock().await; | ||
| 189 | + let mut rows = conn | ||
| 190 | + .query( | ||
| 191 | + "SELECT user_id FROM sessions WHERE token_hash = ?1 AND revoked_at IS NULL", | ||
| 192 | + turso::params![hash], | ||
| 193 | + ) | ||
| 194 | + .await | ||
| 195 | + .map_err(backend)?; | ||
| 196 | + match rows.next().await.map_err(backend)? { | ||
| 197 | + Some(row) => store::text(&row, 0)? == user.as_str(), | ||
| 198 | + None => false, | ||
| 199 | + } | ||
| 200 | + }; | ||
| 201 | + if !owned { | ||
| 202 | + return Ok(false); | ||
| 203 | + } | ||
| 204 | + revoke_session_hash(store, hash).await?; | ||
| 205 | + Ok(true) | ||
| 206 | +} | ||
| 207 | + | ||
| 105 | /// The admin's "log this person out everywhere": every central session of | 208 | /// The admin's "log this person out everywhere": every central session of |
| 106 | /// theirs dies, and the cascades above take every refresh token and every | 209 | /// theirs dies, and the cascades above take every refresh token and every |
| 107 | /// live app session down with them. Introspection is per-request, so the | 210 | /// live app session down with them. Introspection is per-request, so the |
| @@ -217,7 +320,9 @@ mod tests { | |||
| 217 | #[tokio::test] | 320 | #[tokio::test] |
| 218 | async fn session_roundtrip_and_revoke() { | 321 | async fn session_roundtrip_and_revoke() { |
| 219 | let (store, user_id) = fixture().await; | 322 | let (store, user_id) = fixture().await; |
| 220 | - let token = create_session(&store, &user_id).await.unwrap(); | 323 | + let token = create_session(&store, &user_id, &SessionMeta::default()) |
| 324 | + .await | ||
| 325 | + .unwrap(); | ||
| 221 | let user = resolve_session(&store, token.expose()) | 326 | let user = resolve_session(&store, token.expose()) |
| 222 | .await | 327 | .await |
| 223 | .unwrap() | 328 | .unwrap() |
| @@ -242,8 +347,12 @@ mod tests { | |||
| 242 | #[tokio::test] | 347 | #[tokio::test] |
| 243 | async fn revoke_except_keeps_the_asking_session() { | 348 | async fn revoke_except_keeps_the_asking_session() { |
| 244 | let (store, user_id) = fixture().await; | 349 | let (store, user_id) = fixture().await; |
| 245 | - let mine = create_session(&store, &user_id).await.unwrap(); | 350 | + let mine = create_session(&store, &user_id, &SessionMeta::default()) |
| 246 | - let other = create_session(&store, &user_id).await.unwrap(); | 351 | + .await |
| 352 | + .unwrap(); | ||
| 353 | + let other = create_session(&store, &user_id, &SessionMeta::default()) | ||
| 354 | + .await | ||
| 355 | + .unwrap(); | ||
| 247 | 356 | ||
| 248 | let count = revoke_user_sessions_except(&store, &user_id, mine.expose()) | 357 | let count = revoke_user_sessions_except(&store, &user_id, mine.expose()) |
| 249 | .await | 358 | .await |
| @@ -262,4 +371,138 @@ mod tests { | |||
| 262 | .is_none() | 371 | .is_none() |
| 263 | ); | 372 | ); |
| 264 | } | 373 | } |
| 374 | + | ||
| 375 | + #[tokio::test] | ||
| 376 | + async fn list_shows_only_active_newest_first_with_facts() { | ||
| 377 | + let (store, user_id) = fixture().await; | ||
| 378 | + let plain = create_session(&store, &user_id, &SessionMeta::default()) | ||
| 379 | + .await | ||
| 380 | + .unwrap(); | ||
| 381 | + let meta = SessionMeta { | ||
| 382 | + ip: Some("203.0.113.7".to_string()), | ||
| 383 | + agent: Some("TestBrowser/1.0".to_string()), | ||
| 384 | + }; | ||
| 385 | + let noted = create_session(&store, &user_id, &meta).await.unwrap(); | ||
| 386 | + | ||
| 387 | + let listed = list_sessions(&store, &user_id).await.unwrap(); | ||
| 388 | + assert_eq!(listed.len(), 2); | ||
| 389 | + // Newest first: the noted session was created second. | ||
| 390 | + assert_eq!(listed[0].token_hash, noted.hash()); | ||
| 391 | + assert_eq!(listed[0].ip.as_deref(), Some("203.0.113.7")); | ||
| 392 | + assert_eq!(listed[0].agent.as_deref(), Some("TestBrowser/1.0")); | ||
| 393 | + assert_eq!(listed[0].seen_at, Some(listed[0].created_at)); | ||
| 394 | + assert_eq!(listed[1].token_hash, plain.hash()); | ||
| 395 | + assert!(listed[1].ip.is_none()); | ||
| 396 | + assert!(listed[1].agent.is_none()); | ||
| 397 | + assert!(listed[1].created_at <= listed[0].created_at); | ||
| 398 | + | ||
| 399 | + // A revoked session leaves the list; an expired one never shows. | ||
| 400 | + revoke_session(&store, plain.expose()).await.unwrap(); | ||
| 401 | + let listed = list_sessions(&store, &user_id).await.unwrap(); | ||
| 402 | + assert_eq!(listed.len(), 1); | ||
| 403 | + assert_eq!(listed[0].token_hash, noted.hash()); | ||
| 404 | + | ||
| 405 | + let conn = store.conn.lock().await; | ||
| 406 | + conn.execute( | ||
| 407 | + "UPDATE sessions SET expires_at = ?1 WHERE token_hash = ?2", | ||
| 408 | + turso::params![ | ||
| 409 | + store::stamp(store::now() - time::Duration::days(1)).unwrap(), | ||
| 410 | + noted.hash(), | ||
| 411 | + ], | ||
| 412 | + ) | ||
| 413 | + .await | ||
| 414 | + .unwrap(); | ||
| 415 | + drop(conn); | ||
| 416 | + assert!(list_sessions(&store, &user_id).await.unwrap().is_empty()); | ||
| 417 | + } | ||
| 418 | + | ||
| 419 | + #[tokio::test] | ||
| 420 | + async fn revoke_owned_refuses_a_strangers_session() { | ||
| 421 | + let (store, user_id) = fixture().await; | ||
| 422 | + let invite = create_invite(&store, "bob@example.com", None, false) | ||
| 423 | + .await | ||
| 424 | + .unwrap(); | ||
| 425 | + let stranger = create_user_from_invite(&store, invite.expose(), "Bob", "tDLr9!mZQ2xvQ") | ||
| 426 | + .await | ||
| 427 | + .unwrap(); | ||
| 428 | + let mine = create_session(&store, &user_id, &SessionMeta::default()) | ||
| 429 | + .await | ||
| 430 | + .unwrap(); | ||
| 431 | + let theirs = create_session(&store, &stranger.id, &SessionMeta::default()) | ||
| 432 | + .await | ||
| 433 | + .unwrap(); | ||
| 434 | + | ||
| 435 | + // Someone else's hash is a quiet false, and their session survives it. | ||
| 436 | + assert!(!revoke_owned_session(&store, &user_id, &theirs.hash()) | ||
| 437 | + .await | ||
| 438 | + .unwrap()); | ||
| 439 | + assert!( | ||
| 440 | + resolve_session(&store, theirs.expose()) | ||
| 441 | + .await | ||
| 442 | + .unwrap() | ||
| 443 | + .is_some() | ||
| 444 | + ); | ||
| 445 | + assert!(!revoke_owned_session(&store, &user_id, "no-such-hash") | ||
| 446 | + .await | ||
| 447 | + .unwrap()); | ||
| 448 | + | ||
| 449 | + assert!(revoke_owned_session(&store, &user_id, &mine.hash()) | ||
| 450 | + .await | ||
| 451 | + .unwrap()); | ||
| 452 | + assert!( | ||
| 453 | + resolve_session(&store, mine.expose()) | ||
| 454 | + .await | ||
| 455 | + .unwrap() | ||
| 456 | + .is_none() | ||
| 457 | + ); | ||
| 458 | + // Revoking twice is a quiet false the second time. | ||
| 459 | + assert!(!revoke_owned_session(&store, &user_id, &mine.hash()) | ||
| 460 | + .await | ||
| 461 | + .unwrap()); | ||
| 462 | + } | ||
| 463 | + | ||
| 464 | + #[tokio::test] | ||
| 465 | + async fn resolve_touches_seen_at_past_the_throttle() { | ||
| 466 | + let (store, user_id) = fixture().await; | ||
| 467 | + let token = create_session(&store, &user_id, &SessionMeta::default()) | ||
| 468 | + .await | ||
| 469 | + .unwrap(); | ||
| 470 | + // Backdate the sighting past the throttle without sleeping. | ||
| 471 | + let conn = store.conn.lock().await; | ||
| 472 | + conn.execute( | ||
| 473 | + "UPDATE sessions SET seen_at = ?1 WHERE token_hash = ?2", | ||
| 474 | + turso::params![ | ||
| 475 | + store::stamp(store::now() - time::Duration::minutes(10)).unwrap(), | ||
| 476 | + token.hash(), | ||
| 477 | + ], | ||
| 478 | + ) | ||
| 479 | + .await | ||
| 480 | + .unwrap(); | ||
| 481 | + drop(conn); | ||
| 482 | + | ||
| 483 | + let before = list_sessions(&store, &user_id).await.unwrap(); | ||
| 484 | + assert_eq!(before.len(), 1); | ||
| 485 | + let stale = before[0].seen_at.unwrap(); | ||
| 486 | + | ||
| 487 | + assert!( | ||
| 488 | + resolve_session(&store, token.expose()) | ||
| 489 | + .await | ||
| 490 | + .unwrap() | ||
| 491 | + .is_some() | ||
| 492 | + ); | ||
| 493 | + let after = list_sessions(&store, &user_id).await.unwrap(); | ||
| 494 | + assert!(after[0].seen_at.unwrap() > stale); | ||
| 495 | + | ||
| 496 | + // A fresh sighting is inside the throttle: resolving again is a | ||
| 497 | + // no-op write, so seen_at stands still. | ||
| 498 | + let fresh = after[0].seen_at.unwrap(); | ||
| 499 | + assert!( | ||
| 500 | + resolve_session(&store, token.expose()) | ||
| 501 | + .await | ||
| 502 | + .unwrap() | ||
| 503 | + .is_some() | ||
| 504 | + ); | ||
| 505 | + let again = list_sessions(&store, &user_id).await.unwrap(); | ||
| 506 | + assert_eq!(again[0].seen_at, Some(fresh)); | ||
| 507 | + } | ||
| 265 | } | 508 | } |
crates/im-core/src/store.rsmodified+24 -6
| @@ -54,7 +54,10 @@ CREATE TABLE IF NOT EXISTS sessions ( | |||
| 54 | user_id TEXT NOT NULL REFERENCES users(id), | 54 | user_id TEXT NOT NULL REFERENCES users(id), |
| 55 | created_at TEXT NOT NULL, | 55 | created_at TEXT NOT NULL, |
| 56 | expires_at TEXT NOT NULL, | 56 | expires_at TEXT NOT NULL, |
| 57 | - revoked_at TEXT | 57 | + revoked_at TEXT, |
| 58 | + ip TEXT, | ||
| 59 | + agent TEXT, | ||
| 60 | + seen_at TEXT | ||
| 58 | ); | 61 | ); |
| 59 | CREATE TABLE IF NOT EXISTS oidc_clients ( | 62 | CREATE TABLE IF NOT EXISTS oidc_clients ( |
| 60 | client_id TEXT PRIMARY KEY, | 63 | client_id TEXT PRIMARY KEY, |
| @@ -179,16 +182,31 @@ impl Store { | |||
| 179 | let outcome = async { | 182 | let outcome = async { |
| 180 | conn.execute_batch(SCHEMA).await.map_err(backend)?; | 183 | conn.execute_batch(SCHEMA).await.map_err(backend)?; |
| 181 | // Columns born after databases already existed: the CREATE above | 184 | // Columns born after databases already existed: the CREATE above |
| 182 | - // is `IF NOT EXISTS`, so an old users table never sees them from | 185 | + // is `IF NOT EXISTS`, so an old table never sees them from it. |
| 183 | - // it. Each goes in with its own guarded ALTER — a boot either | 186 | + // Each goes in with its own guarded ALTER — a boot either adds |
| 184 | - // adds the column or finds it there, and re-boot is a no-op. | 187 | + // the column or finds it there, and re-boot is a no-op. |
| 185 | - // The photo's bytes are never a column: they live as files under | ||
| 186 | - // the storage tree (see `photos.rs`). | ||
| 187 | if !has_column(&conn, "users", "photo_mime").await? { | 188 | if !has_column(&conn, "users", "photo_mime").await? { |
| 188 | conn.execute("ALTER TABLE users ADD COLUMN photo_mime TEXT", ()) | 189 | conn.execute("ALTER TABLE users ADD COLUMN photo_mime TEXT", ()) |
| 189 | .await | 190 | .await |
| 190 | .map_err(backend)?; | 191 | .map_err(backend)?; |
| 191 | } | 192 | } |
| 193 | + // What a session remembers about its browser: the listing shows | ||
| 194 | + // these, so old databases grow them the same guarded way. | ||
| 195 | + if !has_column(&conn, "sessions", "ip").await? { | ||
| 196 | + conn.execute("ALTER TABLE sessions ADD COLUMN ip TEXT", ()) | ||
| 197 | + .await | ||
| 198 | + .map_err(backend)?; | ||
| 199 | + } | ||
| 200 | + if !has_column(&conn, "sessions", "agent").await? { | ||
| 201 | + conn.execute("ALTER TABLE sessions ADD COLUMN agent TEXT", ()) | ||
| 202 | + .await | ||
| 203 | + .map_err(backend)?; | ||
| 204 | + } | ||
| 205 | + if !has_column(&conn, "sessions", "seen_at").await? { | ||
| 206 | + conn.execute("ALTER TABLE sessions ADD COLUMN seen_at TEXT", ()) | ||
| 207 | + .await | ||
| 208 | + .map_err(backend)?; | ||
| 209 | + } | ||
| 192 | Ok(()) | 210 | Ok(()) |
| 193 | } | 211 | } |
| 194 | .await; | 212 | .await; |
crates/im-migrate/src/main.rsmodified+18 -2
| @@ -34,7 +34,8 @@ CREATE TABLE IF NOT EXISTS users ( | |||
| 34 | totp_confirmed INTEGER NOT NULL DEFAULT 0, | 34 | totp_confirmed INTEGER NOT NULL DEFAULT 0, |
| 35 | admin INTEGER NOT NULL DEFAULT 0, | 35 | admin INTEGER NOT NULL DEFAULT 0, |
| 36 | disabled INTEGER NOT NULL DEFAULT 0, | 36 | disabled INTEGER NOT NULL DEFAULT 0, |
| 37 | - created_at TEXT NOT NULL | 37 | + created_at TEXT NOT NULL, |
| 38 | + photo_mime TEXT | ||
| 38 | ); | 39 | ); |
| 39 | CREATE TABLE IF NOT EXISTS invites ( | 40 | CREATE TABLE IF NOT EXISTS invites ( |
| 40 | token TEXT PRIMARY KEY, | 41 | token TEXT PRIMARY KEY, |
| @@ -50,7 +51,10 @@ CREATE TABLE IF NOT EXISTS sessions ( | |||
| 50 | user_id TEXT NOT NULL REFERENCES users(id), | 51 | user_id TEXT NOT NULL REFERENCES users(id), |
| 51 | created_at TEXT NOT NULL, | 52 | created_at TEXT NOT NULL, |
| 52 | expires_at TEXT NOT NULL, | 53 | expires_at TEXT NOT NULL, |
| 53 | - revoked_at TEXT | 54 | + revoked_at TEXT, |
| 55 | + ip TEXT, | ||
| 56 | + agent TEXT, | ||
| 57 | + seen_at TEXT | ||
| 54 | ); | 58 | ); |
| 55 | CREATE TABLE IF NOT EXISTS oidc_clients ( | 59 | CREATE TABLE IF NOT EXISTS oidc_clients ( |
| 56 | client_id TEXT PRIMARY KEY, | 60 | client_id TEXT PRIMARY KEY, |
| @@ -101,6 +105,18 @@ CREATE TABLE IF NOT EXISTS events ( | |||
| 101 | actor TEXT, | 105 | actor TEXT, |
| 102 | detail TEXT | 106 | detail TEXT |
| 103 | ); | 107 | ); |
| 108 | +CREATE TABLE IF NOT EXISTS reset_links ( | ||
| 109 | + token TEXT PRIMARY KEY, | ||
| 110 | + user_id TEXT NOT NULL REFERENCES users(id), | ||
| 111 | + created_at TEXT NOT NULL, | ||
| 112 | + expires_at TEXT NOT NULL, | ||
| 113 | + used_at TEXT | ||
| 114 | +); | ||
| 115 | +CREATE TABLE IF NOT EXISTS login_attempts ( | ||
| 116 | + key TEXT NOT NULL, | ||
| 117 | + at TEXT NOT NULL | ||
| 118 | +); | ||
| 119 | +CREATE INDEX IF NOT EXISTS login_attempts_key ON login_attempts(key, at); | ||
| 104 | CREATE TABLE IF NOT EXISTS settings ( | 120 | CREATE TABLE IF NOT EXISTS settings ( |
| 105 | key TEXT PRIMARY KEY, | 121 | key TEXT PRIMARY KEY, |
| 106 | value TEXT NOT NULL | 122 | value TEXT NOT NULL |
crates/im-web/assets/main.cssmodified+57 -0
| @@ -523,6 +523,50 @@ body:has(.auth-stage) > .auth-stage::-webkit-scrollbar { | |||
| 523 | letter-spacing: -0.01em; | 523 | letter-spacing: -0.01em; |
| 524 | } | 524 | } |
| 525 | 525 | ||
| 526 | +.session-list { | ||
| 527 | + display: flex; | ||
| 528 | + flex-direction: column; | ||
| 529 | +} | ||
| 530 | + | ||
| 531 | +.session-row { | ||
| 532 | + display: flex; | ||
| 533 | + gap: 12px; | ||
| 534 | + align-items: flex-start; | ||
| 535 | + padding: 12px 0; | ||
| 536 | + border-top: 1px solid var(--border-soft); | ||
| 537 | +} | ||
| 538 | +.session-row:first-child { | ||
| 539 | + border-top: 0; | ||
| 540 | + padding-top: 0; | ||
| 541 | +} | ||
| 542 | +.session-row:last-child { | ||
| 543 | + padding-bottom: 0; | ||
| 544 | +} | ||
| 545 | +.session-row form { | ||
| 546 | + flex: none; | ||
| 547 | +} | ||
| 548 | + | ||
| 549 | +.session-main { | ||
| 550 | + flex: 1; | ||
| 551 | + display: flex; | ||
| 552 | + flex-direction: column; | ||
| 553 | + gap: 2px; | ||
| 554 | + min-width: 0; | ||
| 555 | +} | ||
| 556 | + | ||
| 557 | +.session-device { | ||
| 558 | + font-size: 13px; | ||
| 559 | + overflow-wrap: anywhere; | ||
| 560 | +} | ||
| 561 | +.session-device .chip { | ||
| 562 | + margin-left: 8px; | ||
| 563 | +} | ||
| 564 | + | ||
| 565 | +.session-meta { | ||
| 566 | + font-size: 12px; | ||
| 567 | + color: var(--muted); | ||
| 568 | +} | ||
| 569 | + | ||
| 526 | @media (max-width: 720px) { | 570 | @media (max-width: 720px) { |
| 527 | .auth-stage { | 571 | .auth-stage { |
| 528 | padding: 0 16px 24px; | 572 | padding: 0 16px 24px; |
| @@ -777,6 +821,19 @@ body:has(.admin-shell) { | |||
| 777 | color: var(--ink); | 821 | color: var(--ink); |
| 778 | } | 822 | } |
| 779 | 823 | ||
| 824 | +.admin-sessions summary { | ||
| 825 | + cursor: pointer; | ||
| 826 | + font-size: 12px; | ||
| 827 | + display: inline-block; | ||
| 828 | +} | ||
| 829 | +.admin-sessions[open] summary { | ||
| 830 | + margin-bottom: 8px; | ||
| 831 | +} | ||
| 832 | +.admin-sessions .admin-table td:first-child { | ||
| 833 | + overflow-wrap: anywhere; | ||
| 834 | + max-width: 280px; | ||
| 835 | +} | ||
| 836 | + | ||
| 780 | input[type=checkbox] { | 837 | input[type=checkbox] { |
| 781 | accent-color: var(--accent); | 838 | accent-color: var(--accent); |
| 782 | } | 839 | } |
crates/im-web/src/admin.rsmodified+86 -0
| @@ -162,6 +162,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> { | |||
| 162 | match code { | 162 | match code { |
| 163 | "invited" => "Invite created.", | 163 | "invited" => "Invite created.", |
| 164 | "revoked" => "Sessions revoked — every device is signed out.", | 164 | "revoked" => "Sessions revoked — every device is signed out.", |
| 165 | + "session_revoked" => "Session revoked.", | ||
| 165 | "disabled" => "Account disabled.", | 166 | "disabled" => "Account disabled.", |
| 166 | "enabled" => "Account enabled.", | 167 | "enabled" => "Account enabled.", |
| 167 | "smtp" => "Mail settings saved.", | 168 | "smtp" => "Mail settings saved.", |
| @@ -229,6 +230,67 @@ fn account_section(me: &User) -> String { | |||
| 229 | ) | 230 | ) |
| 230 | } | 231 | } |
| 231 | 232 | ||
| 233 | +/// One person's live sessions as the disclosure under their row: a small | ||
| 234 | +/// table with a per-session revoke, or the muted line when nothing is live. | ||
| 235 | +/// The admin's own row gets one too — "you" still signs in from somewhere. | ||
| 236 | +fn sessions_row(user: &User, sessions: &[im_core::sessions::SessionInfo]) -> String { | ||
| 237 | + let id = escape(&user.id.to_string()); | ||
| 238 | + let body = if sessions.is_empty() { | ||
| 239 | + r#"<div class="muted">No active sessions</div>"#.to_string() | ||
| 240 | + } else { | ||
| 241 | + let mut rows = String::new(); | ||
| 242 | + for session in sessions { | ||
| 243 | + let seen_at = session.seen_at.unwrap_or(session.created_at); | ||
| 244 | + let seen = seen_at | ||
| 245 | + .format(&time::macros::format_description!( | ||
| 246 | + "[year]-[month]-[day] [hour]:[minute]" | ||
| 247 | + )) | ||
| 248 | + .unwrap_or_else(|_| seen_at.date().to_string()); | ||
| 249 | + rows.push_str(&format!( | ||
| 250 | + concat!( | ||
| 251 | + r#"<tr><td>{}</td>"#, | ||
| 252 | + r#"<td class="mono">{}</td>"#, | ||
| 253 | + r#"<td class="muted">{}</td>"#, | ||
| 254 | + r#"<td class="muted">{}</td>"#, | ||
| 255 | + r#"<td class="actions">"#, | ||
| 256 | + r#"<form method="post" action="/admin/session_revoke">"#, | ||
| 257 | + r#"<input type="hidden" name="user" value="{id}">"#, | ||
| 258 | + r#"<input type="hidden" name="session" value="{}">"#, | ||
| 259 | + r#"<button class="admin-action" type="submit">Revoke</button>"#, | ||
| 260 | + r#"</form></td></tr>"# | ||
| 261 | + ), | ||
| 262 | + session | ||
| 263 | + .agent | ||
| 264 | + .as_deref() | ||
| 265 | + .filter(|agent| !agent.is_empty()) | ||
| 266 | + .map(escape) | ||
| 267 | + .unwrap_or_else(|| "Unknown device".to_string()), | ||
| 268 | + session | ||
| 269 | + .ip | ||
| 270 | + .as_deref() | ||
| 271 | + .map(escape) | ||
| 272 | + .unwrap_or_else(|| "—".to_string()), | ||
| 273 | + session.created_at.date(), | ||
| 274 | + seen, | ||
| 275 | + escape(&session.token_hash), | ||
| 276 | + id = id, | ||
| 277 | + )); | ||
| 278 | + } | ||
| 279 | + format!( | ||
| 280 | + concat!( | ||
| 281 | + r#"<table class="admin-table"><thead><tr>"#, | ||
| 282 | + r#"<th>Device</th><th>Address</th><th>Signed in</th><th>Last seen</th><th></th>"#, | ||
| 283 | + r#"</tr></thead><tbody>{rows}</tbody></table>"# | ||
| 284 | + ), | ||
| 285 | + rows = rows, | ||
| 286 | + ) | ||
| 287 | + }; | ||
| 288 | + format!( | ||
| 289 | + r#"<tr><td colspan="4"><details class="admin-sessions"><summary class="muted">Sessions ({})</summary>{body}</details></td></tr>"#, | ||
| 290 | + sessions.len() | ||
| 291 | + ) | ||
| 292 | +} | ||
| 293 | + | ||
| 232 | async fn users_section( | 294 | async fn users_section( |
| 233 | cx: &Cx, | 295 | cx: &Cx, |
| 234 | me: &User, | 296 | me: &User, |
| @@ -298,6 +360,8 @@ async fn users_section( | |||
| 298 | flags, | 360 | flags, |
| 299 | actions | 361 | actions |
| 300 | )); | 362 | )); |
| 363 | + let sessions = im_core::sessions::list_sessions(&app(cx).store, &user.id).await?; | ||
| 364 | + rows.push_str(&sessions_row(user, &sessions)); | ||
| 301 | } | 365 | } |
| 302 | // Invites still waiting on their person sit in the same table — "waiting" | 366 | // Invites still waiting on their person sit in the same table — "waiting" |
| 303 | // instead of a name, and the one action an outstanding link understands: | 367 | // instead of a name, and the one action an outstanding link understands: |
| @@ -673,6 +737,28 @@ async fn revoke(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> { | |||
| 673 | back(cx, "users", "&ok=revoked") | 737 | back(cx, "users", "&ok=revoked") |
| 674 | } | 738 | } |
| 675 | 739 | ||
| 740 | +#[derive(Deserialize)] | ||
| 741 | +struct SessionRevokeForm { | ||
| 742 | + user: String, | ||
| 743 | + session: String, | ||
| 744 | +} | ||
| 745 | + | ||
| 746 | +/// Revokes one session of one person — the per-row door beside the | ||
| 747 | +/// sign-them-out-everywhere one above. | ||
| 748 | +#[route(POST "/admin/session_revoke")] | ||
| 749 | +async fn session_revoke(cx: &Cx, Form(input): Form<SessionRevokeForm>) -> Result<Response> { | ||
| 750 | + let me = match require_admin(cx).await { | ||
| 751 | + Ok(me) => me, | ||
| 752 | + Err(redirect) => return Ok(redirect), | ||
| 753 | + }; | ||
| 754 | + let user_id = UserId::from(input.user.clone()); | ||
| 755 | + if !im_core::sessions::revoke_owned_session(&app(cx).store, &user_id, &input.session).await? { | ||
| 756 | + return back(cx, "users", "&error=session_unknown"); | ||
| 757 | + } | ||
| 758 | + server::log_event(cx, "session_revoked", Some(&me.email), Some(&input.user)).await; | ||
| 759 | + back(cx, "users", "&ok=session_revoked") | ||
| 760 | +} | ||
| 761 | + | ||
| 676 | #[route(POST "/admin/disable")] | 762 | #[route(POST "/admin/disable")] |
| 677 | async fn disable(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> { | 763 | async fn disable(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> { |
| 678 | set_disabled(cx, input, true).await | 764 | set_disabled(cx, input, true).await |
crates/im-web/src/auth.rsmodified+65 -2
| @@ -43,6 +43,34 @@ fn safe_back(raw: &str) -> &str { | |||
| 43 | } | 43 | } |
| 44 | } | 44 | } |
| 45 | 45 | ||
| 46 | +/// Creation-time facts for the session row: the address the browser came | ||
| 47 | +/// through and the agent it claims to be. The accept loop discards the peer | ||
| 48 | +/// address, so the proxy headers are the only source — the first | ||
| 49 | +/// `x-forwarded-for` hop, else `x-real-ip`, else nothing known. | ||
| 50 | +fn session_meta(cx: &Cx) -> im_core::sessions::SessionMeta { | ||
| 51 | + let headers = topcoat::router::request::headers(cx); | ||
| 52 | + let ip = headers | ||
| 53 | + .get("x-forwarded-for") | ||
| 54 | + .and_then(|value| value.to_str().ok()) | ||
| 55 | + .and_then(|value| value.split(',').next()) | ||
| 56 | + .map(str::trim) | ||
| 57 | + .filter(|hop| !hop.is_empty()) | ||
| 58 | + .map(str::to_string) | ||
| 59 | + .or_else(|| { | ||
| 60 | + headers | ||
| 61 | + .get("x-real-ip") | ||
| 62 | + .and_then(|value| value.to_str().ok()) | ||
| 63 | + .map(str::trim) | ||
| 64 | + .filter(|ip| !ip.is_empty()) | ||
| 65 | + .map(str::to_string) | ||
| 66 | + }); | ||
| 67 | + let agent = headers | ||
| 68 | + .get("user-agent") | ||
| 69 | + .and_then(|value| value.to_str().ok()) | ||
| 70 | + .map(|value| value.chars().take(255).collect::<String>()); | ||
| 71 | + im_core::sessions::SessionMeta { ip, agent } | ||
| 72 | +} | ||
| 73 | + | ||
| 46 | #[derive(Deserialize)] | 74 | #[derive(Deserialize)] |
| 47 | pub struct LoginForm { | 75 | pub struct LoginForm { |
| 48 | email: String, | 76 | email: String, |
| @@ -138,7 +166,7 @@ async fn login_totp(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect { | |||
| 138 | return see("/login/totp?error=bad_code".to_string()); | 166 | return see("/login/totp?error=bad_code".to_string()); |
| 139 | } | 167 | } |
| 140 | let _ = accounts::clear_login_failures(store, &totp_key).await; | 168 | let _ = accounts::clear_login_failures(store, &totp_key).await; |
| 141 | - let token = im_core::sessions::create_session(store, &user_id).await?; | 169 | + let token = im_core::sessions::create_session(store, &user_id, &session_meta(cx)).await?; |
| 142 | let email = accounts::user_by_id(store, &user_id) | 170 | let email = accounts::user_by_id(store, &user_id) |
| 143 | .await? | 171 | .await? |
| 144 | .map(|u| u.email); | 172 | .map(|u| u.email); |
| @@ -219,7 +247,7 @@ async fn enroll(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect { | |||
| 219 | return see("/enroll?error=bad_code".to_string()); | 247 | return see("/enroll?error=bad_code".to_string()); |
| 220 | } | 248 | } |
| 221 | im_core::totp::confirm_totp(store, &user_id).await?; | 249 | im_core::totp::confirm_totp(store, &user_id).await?; |
| 222 | - let token = im_core::sessions::create_session(store, &user_id).await?; | 250 | + let token = im_core::sessions::create_session(store, &user_id, &session_meta(cx)).await?; |
| 223 | let email = accounts::user_by_id(store, &user_id) | 251 | let email = accounts::user_by_id(store, &user_id) |
| 224 | .await? | 252 | .await? |
| 225 | .map(|u| u.email); | 253 | .map(|u| u.email); |
| @@ -307,3 +335,38 @@ async fn reset(cx: &Cx, Form(input): Form<ResetForm>) -> Redirect { | |||
| 307 | Err(e) => Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), | 335 | Err(e) => Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), |
| 308 | } | 336 | } |
| 309 | } | 337 | } |
| 338 | + | ||
| 339 | +#[derive(Deserialize)] | ||
| 340 | +struct SessionRevokeForm { | ||
| 341 | + session: String, | ||
| 342 | +} | ||
| 343 | + | ||
| 344 | +/// Revokes one of the signer's own sessions. The current one signs this | ||
| 345 | +/// browser out — the server row dies and the cookie is tidied; any other | ||
| 346 | +/// just dies where it lives. | ||
| 347 | +#[route(POST "/sessions/revoke")] | ||
| 348 | +async fn revoke_session(cx: &Cx, Form(input): Form<SessionRevokeForm>) -> Redirect { | ||
| 349 | + let Some(user) = server::current_user(cx).await else { | ||
| 350 | + return see("/".to_string()); | ||
| 351 | + }; | ||
| 352 | + let store = &server::app(cx).store; | ||
| 353 | + if let Some(presented) = server::presented_session(cx) { | ||
| 354 | + if im_core::accounts::hash_token(&presented) == input.session { | ||
| 355 | + im_core::sessions::revoke_session(store, &presented).await?; | ||
| 356 | + server::clear_session_cookie(cx); | ||
| 357 | + return see("/".to_string()); | ||
| 358 | + } | ||
| 359 | + } | ||
| 360 | + // The row's address, when it is still there, is the useful half of the | ||
| 361 | + // log line — which of their devices they just killed. | ||
| 362 | + let ip = im_core::sessions::list_sessions(store, &user.id) | ||
| 363 | + .await? | ||
| 364 | + .into_iter() | ||
| 365 | + .find(|s| s.token_hash == input.session) | ||
| 366 | + .and_then(|s| s.ip); | ||
| 367 | + if !im_core::sessions::revoke_owned_session(store, &user.id, &input.session).await? { | ||
| 368 | + return see("/?error=session_unknown".to_string()); | ||
| 369 | + } | ||
| 370 | + server::log_event(cx, "session_revoked", Some(&user.email), ip.as_deref()).await; | ||
| 371 | + see("/?ok=session_revoked".to_string()) | ||
| 372 | +} | ||
crates/im-web/src/pages.rsmodified+83 -0
| @@ -38,6 +38,7 @@ pub fn error_text(code: &str) -> &'static str { | |||
| 38 | "not_an_image" => "That file is not an image.", | 38 | "not_an_image" => "That file is not an image.", |
| 39 | "no_file" => "Choose an image first.", | 39 | "no_file" => "Choose an image first.", |
| 40 | "reset_invalid" => "This reset link is not valid — ask for a fresh one.", | 40 | "reset_invalid" => "This reset link is not valid — ask for a fresh one.", |
| 41 | + "session_unknown" => "That session is already gone.", | ||
| 41 | _ => "Something went wrong. Try again.", | 42 | _ => "Something went wrong. Try again.", |
| 42 | } | 43 | } |
| 43 | } | 44 | } |
| @@ -49,6 +50,7 @@ pub fn ok_text(code: &str) -> &'static str { | |||
| 49 | "enrolled" => "Two-factor sign-in is on. You're all set.", | 50 | "enrolled" => "Two-factor sign-in is on. You're all set.", |
| 50 | "photo_saved" => "Profile photo updated.", | 51 | "photo_saved" => "Profile photo updated.", |
| 51 | "photo_removed" => "Profile photo removed.", | 52 | "photo_removed" => "Profile photo removed.", |
| 53 | + "session_revoked" => "Session revoked.", | ||
| 52 | _ => "Done.", | 54 | _ => "Done.", |
| 53 | } | 55 | } |
| 54 | } | 56 | } |
| @@ -409,6 +411,79 @@ async fn enroll(cx: &Cx) -> Result<Response> { | |||
| 409 | .into_response(cx) | 411 | .into_response(cx) |
| 410 | } | 412 | } |
| 411 | 413 | ||
| 414 | +/// The sessions card builds its rows as a string — one per live session — | ||
| 415 | +/// so its interpolations never pass through `view!`'s escaping. The | ||
| 416 | +/// discipline matches admin.rs's `escape`: everything user-controlled | ||
| 417 | +/// (agent, address) crosses it before it reaches the markup. | ||
| 418 | +fn escape(raw: &str) -> String { | ||
| 419 | + raw.replace('&', "&") | ||
| 420 | + .replace('<', "<") | ||
| 421 | + .replace('>', ">") | ||
| 422 | + .replace('"', """) | ||
| 423 | +} | ||
| 424 | + | ||
| 425 | +/// The device line of a session row: the agent shortened to fit the row, or | ||
| 426 | +/// the honest fallback when the session predates agent capture. | ||
| 427 | +fn device_name(agent: Option<&str>) -> String { | ||
| 428 | + const MAX: usize = 80; | ||
| 429 | + match agent { | ||
| 430 | + None | Some("") => "Unknown device".to_string(), | ||
| 431 | + Some(agent) if agent.chars().count() > MAX => { | ||
| 432 | + format!("{}…", agent.chars().take(MAX).collect::<String>()) | ||
| 433 | + } | ||
| 434 | + Some(agent) => agent.to_string(), | ||
| 435 | + } | ||
| 436 | +} | ||
| 437 | + | ||
| 438 | +/// `2026-09-04 10:22`: the last-seen stamp. An unrenderable stamp falls back | ||
| 439 | +/// to the day — a stamp that cannot print must still say something true. | ||
| 440 | +fn stamp_min(when: time::OffsetDateTime) -> String { | ||
| 441 | + when.format(&time::macros::format_description!( | ||
| 442 | + "[year]-[month]-[day] [hour]:[minute]" | ||
| 443 | + )) | ||
| 444 | + .unwrap_or_else(|_| when.date().to_string()) | ||
| 445 | +} | ||
| 446 | + | ||
| 447 | +/// The sessions card's rows: device, address, stamps, and the per-session | ||
| 448 | +/// revoke. The current row wears the chip and its button reads as the way | ||
| 449 | +/// out of this browser; every other button names what it does instead. | ||
| 450 | +fn sessions_html(sessions: &[im_core::sessions::SessionInfo], current: Option<&str>) -> String { | ||
| 451 | + let mut rows = String::new(); | ||
| 452 | + for session in sessions { | ||
| 453 | + let mine = current == Some(session.token_hash.as_str()); | ||
| 454 | + let seen = session.seen_at.unwrap_or(session.created_at); | ||
| 455 | + let chip = if mine { | ||
| 456 | + r#" <span class="chip chip-connected">This session</span>"# | ||
| 457 | + } else { | ||
| 458 | + "" | ||
| 459 | + }; | ||
| 460 | + rows.push_str(&format!( | ||
| 461 | + concat!( | ||
| 462 | + r#"<div class="session-row"><div class="session-main">"#, | ||
| 463 | + r#"<div class="session-device">{}{}</div>"#, | ||
| 464 | + r#"<div class="session-meta mono">{}</div>"#, | ||
| 465 | + r#"<div class="session-meta">Signed in {} · Last seen {}</div>"#, | ||
| 466 | + r#"</div>"#, | ||
| 467 | + r#"<form method="post" action="/sessions/revoke">"#, | ||
| 468 | + r#"<input type="hidden" name="session" value="{}">"#, | ||
| 469 | + r#"<button class="admin-action" type="submit">{}</button></form></div>"# | ||
| 470 | + ), | ||
| 471 | + escape(&device_name(session.agent.as_deref())), | ||
| 472 | + chip, | ||
| 473 | + session | ||
| 474 | + .ip | ||
| 475 | + .as_deref() | ||
| 476 | + .map(escape) | ||
| 477 | + .unwrap_or_else(|| "—".to_string()), | ||
| 478 | + session.created_at.date(), | ||
| 479 | + stamp_min(seen), | ||
| 480 | + escape(&session.token_hash), | ||
| 481 | + if mine { "Sign out" } else { "Revoke" }, | ||
| 482 | + )); | ||
| 483 | + } | ||
| 484 | + rows | ||
| 485 | +} | ||
| 486 | + | ||
| 412 | /// The signed-in landing. im is an auth service, not an app: this page is | 487 | /// The signed-in landing. im is an auth service, not an app: this page is |
| 413 | /// the proof of session, the person's profile — photo and the counts their | 488 | /// the proof of session, the person's profile — photo and the counts their |
| 414 | /// identity has earned — and the way out. izlek gives a profile its own | 489 | /// identity has earned — and the way out. izlek gives a profile its own |
| @@ -420,6 +495,10 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { | |||
| 420 | let error = query_value(&query, "error"); | 495 | let error = query_value(&query, "error"); |
| 421 | let stats = im_core::stats::profile_stats(&server::app(cx).store, &user.id).await?; | 496 | let stats = im_core::stats::profile_stats(&server::app(cx).store, &user.id).await?; |
| 422 | let joined = user.created_at.date().to_string(); | 497 | let joined = user.created_at.date().to_string(); |
| 498 | + let sessions = im_core::sessions::list_sessions(&server::app(cx).store, &user.id).await?; | ||
| 499 | + let current = | ||
| 500 | + server::presented_session(cx).map(|token| im_core::accounts::hash_token(&token)); | ||
| 501 | + let sessions_html = sessions_html(&sessions, current.as_deref()); | ||
| 423 | let stage = view! { | 502 | let stage = view! { |
| 424 | cx => | 503 | cx => |
| 425 | <main class="auth-stage"> | 504 | <main class="auth-stage"> |
| @@ -536,6 +615,10 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { | |||
| 536 | </div> | 615 | </div> |
| 537 | </dl> | 616 | </dl> |
| 538 | </div> | 617 | </div> |
| 618 | + <div class="auth-card"> | ||
| 619 | + <div class="auth-title">"Sessions"</div> | ||
| 620 | + <div class="session-list">(topcoat::view::Unescaped::new_unchecked(sessions_html))</div> | ||
| 621 | + </div> | ||
| 539 | <div class="auth-card"> | 622 | <div class="auth-card"> |
| 540 | <form method="post" action="/logout"> | 623 | <form method="post" action="/logout"> |
| 541 | <button class="auth-submit" type="submit"> | 624 | <button class="auth-submit" type="submit"> |
style/main.scssmodified+63 -0
| @@ -586,6 +586,50 @@ body:has(.auth-stage) { | |||
| 586 | letter-spacing: -0.01em; | 586 | letter-spacing: -0.01em; |
| 587 | } | 587 | } |
| 588 | 588 | ||
| 589 | +// The sessions list: one row per live device, in the profile-fields idiom — | ||
| 590 | +// a device line, a quiet meta line, the revoke riding the row's end. | ||
| 591 | +.session-list { | ||
| 592 | + display: flex; | ||
| 593 | + flex-direction: column; | ||
| 594 | +} | ||
| 595 | + | ||
| 596 | +.session-row { | ||
| 597 | + display: flex; | ||
| 598 | + gap: 12px; | ||
| 599 | + align-items: flex-start; | ||
| 600 | + padding: 12px 0; | ||
| 601 | + border-top: 1px solid var(--border-soft); | ||
| 602 | + | ||
| 603 | + &:first-child { | ||
| 604 | + border-top: 0; | ||
| 605 | + padding-top: 0; | ||
| 606 | + } | ||
| 607 | + | ||
| 608 | + &:last-child { padding-bottom: 0; } | ||
| 609 | + | ||
| 610 | + form { flex: none; } | ||
| 611 | +} | ||
| 612 | + | ||
| 613 | +.session-main { | ||
| 614 | + flex: 1; | ||
| 615 | + display: flex; | ||
| 616 | + flex-direction: column; | ||
| 617 | + gap: 2px; | ||
| 618 | + min-width: 0; | ||
| 619 | +} | ||
| 620 | + | ||
| 621 | +.session-device { | ||
| 622 | + font-size: 13px; | ||
| 623 | + overflow-wrap: anywhere; | ||
| 624 | + | ||
| 625 | + .chip { margin-left: 8px; } | ||
| 626 | +} | ||
| 627 | + | ||
| 628 | +.session-meta { | ||
| 629 | + font-size: 12px; | ||
| 630 | + color: var(--muted); | ||
| 631 | +} | ||
| 632 | + | ||
| 589 | @media (max-width: 720px) { | 633 | @media (max-width: 720px) { |
| 590 | .auth-stage { padding: 0 16px 24px; } | 634 | .auth-stage { padding: 0 16px 24px; } |
| 591 | } | 635 | } |
| @@ -844,6 +888,25 @@ body:has(.admin-shell) { | |||
| 844 | 888 | ||
| 845 | .admin-confirm-title { font-weight: 600; color: var(--ink); } | 889 | .admin-confirm-title { font-weight: 600; color: var(--ink); } |
| 846 | 890 | ||
| 891 | +// One person's live sessions, folded under their row: the summary is the | ||
| 892 | +// count, the opened panel holds the small table — or the muted line. | ||
| 893 | +.admin-sessions { | ||
| 894 | + summary { | ||
| 895 | + cursor: pointer; | ||
| 896 | + font-size: 12px; | ||
| 897 | + display: inline-block; | ||
| 898 | + } | ||
| 899 | + | ||
| 900 | + &[open] summary { margin-bottom: 8px; } | ||
| 901 | + | ||
| 902 | + // The device cell carries whole user-agent strings; keep them inside the | ||
| 903 | + // column instead of stretching the panel. | ||
| 904 | + .admin-table td:first-child { | ||
| 905 | + overflow-wrap: anywhere; | ||
| 906 | + max-width: 280px; | ||
| 907 | + } | ||
| 908 | +} | ||
| 909 | + | ||
| 847 | input[type="checkbox"] { accent-color: var(--accent); } | 910 | input[type="checkbox"] { accent-color: var(--accent); } |
| 848 | 911 | ||
| 849 | @media (max-width: 720px) { | 912 | @media (max-width: 720px) { |