From 5182e938445c6e36a68aa88a01156fee7afb3b9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 4 Sep 2026 15:31:28 +0300 Subject: [PATCH] =?UTF-8?q?Sessions=20listed=20per=20device=20=E2=80=94=20?= =?UTF-8?q?IP,=20agent,=20last=20seen=20=E2=80=94=20revocable=20by=20their?= =?UTF-8?q?=20owner=20and=20by=20admin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/im-core/src/accounts.rs | 12 +- crates/im-core/src/oidc.rs | 14 +- crates/im-core/src/sessions.rs | 261 +++++++++++++++++++++++++++++++-- crates/im-core/src/store.rs | 30 +++- crates/im-migrate/src/main.rs | 20 ++- crates/im-web/assets/main.css | 57 +++++++ crates/im-web/src/admin.rs | 86 +++++++++++ crates/im-web/src/auth.rs | 67 ++++++++- crates/im-web/src/pages.rs | 83 +++++++++++ style/main.scss | 63 ++++++++ 10 files changed, 668 insertions(+), 25 deletions(-) diff --git a/crates/im-core/src/accounts.rs b/crates/im-core/src/accounts.rs index 7e82ee0..0bc48c8 100644 --- a/crates/im-core/src/accounts.rs +++ b/crates/im-core/src/accounts.rs @@ -1028,7 +1028,11 @@ mod tests { let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") .await .unwrap(); - let session = crate::sessions::create_session(&store, &user.id) + let session = crate::sessions::create_session( + &store, + &user.id, + &crate::sessions::SessionMeta::default(), + ) .await .unwrap(); @@ -1057,7 +1061,11 @@ mod tests { let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") .await .unwrap(); - let session = crate::sessions::create_session(&store, &user.id) + let session = crate::sessions::create_session( + &store, + &user.id, + &crate::sessions::SessionMeta::default(), + ) .await .unwrap(); diff --git a/crates/im-core/src/oidc.rs b/crates/im-core/src/oidc.rs index 4030c4e..da3a0b2 100644 --- a/crates/im-core/src/oidc.rs +++ b/crates/im-core/src/oidc.rs @@ -517,14 +517,16 @@ pub async fn introspect_app_session( mod tests { use super::*; use crate::accounts::{create_invite, create_user_from_invite}; - use crate::sessions::create_session; + use crate::sessions::{SessionMeta, create_session}; use rsa::signature::Verifier; use std::path::Path; #[tokio::test] async fn app_session_introspection_and_instant_revoke() { let (store, client_id, user_id) = fixture().await; - let session = create_session(&store, &user_id).await.unwrap(); + let session = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); let app_token = issue_app_session(&store, &user_id, &client_id, &session.hash()) .await .unwrap(); @@ -632,7 +634,9 @@ mod tests { #[tokio::test] async fn refresh_rotates_and_dies_with_session() { let (store, client_id, user_id) = fixture().await; - let session = create_session(&store, &user_id).await.unwrap(); + let session = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); let token = issue_refresh(&store, &user_id, &client_id, &session.hash()) .await .unwrap(); @@ -658,7 +662,9 @@ mod tests { ); // Revoking the central session retires the refresh chain. - let session2 = create_session(&store, &user_id).await.unwrap(); + let session2 = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); let token2 = issue_refresh(&store, &user_id, &client_id, &session2.hash()) .await .unwrap(); diff --git a/crates/im-core/src/sessions.rs b/crates/im-core/src/sessions.rs index 719a130..296424b 100644 --- a/crates/im-core/src/sessions.rs +++ b/crates/im-core/src/sessions.rs @@ -3,7 +3,8 @@ //! A session is what makes SSO single: once a browser holds one, every app's //! `/authorize` round-trip is a silent redirect. Revoking a session also //! revokes every refresh token bound to it — that is what "log me out -//! everywhere" means here. +//! everywhere" means here. Each session also remembers its browser (IP, +//! agent, last seen) so the sessions list can show every device separately. use crate::accounts::{Token, hash_token}; use crate::model::{User, UserId}; @@ -14,21 +15,42 @@ use crate::store::{self, Result, Store, backend}; /// Max-Age (which is set before the store is in hand). pub const SESSION_DAYS: i64 = 30; +/// Creation-time facts about the client holding the session. +#[derive(Debug, Clone, Default)] +pub struct SessionMeta { + pub ip: Option, + pub agent: Option, +} + +/// One live central session, as the sessions list shows it. +#[derive(Debug, Clone)] +pub struct SessionInfo { + pub token_hash: String, + pub created_at: time::OffsetDateTime, + pub expires_at: time::OffsetDateTime, + pub seen_at: Option, + pub ip: Option, + pub agent: Option, +} + /// Creates a session for `user`, returning the raw cookie token. The row -/// holds only its digest. -pub async fn create_session(store: &Store, user: &UserId) -> Result { +/// holds only its digest, plus what `meta` says about the browser — and the +/// first sighting is creation itself, so `seen_at` starts at `created_at`. +pub async fn create_session(store: &Store, user: &UserId, meta: &SessionMeta) -> Result { let token = Token::mint(); let now = store::now(); let days = crate::settings::policy(store).await?.session_days; let conn = store.conn.lock().await; conn.execute( - "INSERT INTO sessions (token_hash, user_id, created_at, expires_at) \ - VALUES (?1, ?2, ?3, ?4)", + "INSERT INTO sessions (token_hash, user_id, created_at, expires_at, ip, agent, seen_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?3)", turso::params![ token.hash(), user.to_string(), store::stamp(now)?, store::stamp(now + time::Duration::days(days))?, + meta.ip.clone(), + meta.agent.clone(), ], ) .await @@ -64,7 +86,25 @@ pub async fn resolve_session(store: &Store, token: &str) -> Result> return Ok(None); }; match crate::accounts::user_by_id(store, &user_id).await? { - Some(user) if !user.disabled => Ok(Some(user)), + Some(user) if !user.disabled => { + // The sighting lands after the fact, guard long dropped: one + // UPDATE per call, and the throttle keeps it near one write per + // five minutes per session no matter how chatty the browser is. + let now = store::now(); + let conn = store.conn.lock().await; + conn.execute( + "UPDATE sessions SET seen_at = ?1 WHERE token_hash = ?2 \ + AND (seen_at IS NULL OR seen_at < ?3)", + turso::params![ + store::stamp(now)?, + hash_token(token), + store::stamp(now - time::Duration::minutes(5))?, + ], + ) + .await + .map_err(backend)?; + Ok(Some(user)) + } _ => Ok(None), } } @@ -102,6 +142,69 @@ pub(crate) async fn revoke_session_hash(store: &Store, hash: &str) -> Result<()> Ok(()) } +/// Active (not revoked, not expired) sessions of `user`, newest first. +pub async fn list_sessions(store: &Store, user: &UserId) -> Result> { + // Revocation filters in SQL; expiry is a stamp comparison, done beside + // `resolve_session` in Rust where a corrupt stamp surfaces as an error. + let now = store::now(); + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT token_hash, created_at, expires_at, seen_at, ip, agent FROM sessions \ + WHERE user_id = ?1 AND revoked_at IS NULL ORDER BY created_at DESC", + turso::params![user.to_string()], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + let expires_at = store::parse_stamp(&store::text(&row, 2)?)?; + if expires_at < now { + continue; + } + let seen_at = match store::opt_text(&row, 3)? { + Some(raw) => Some(store::parse_stamp(&raw)?), + None => None, + }; + out.push(SessionInfo { + token_hash: store::text(&row, 0)?, + created_at: store::parse_stamp(&store::text(&row, 1)?)?, + expires_at, + seen_at, + ip: store::opt_text(&row, 4)?, + agent: store::opt_text(&row, 5)?, + }); + } + Ok(out) +} + +/// Revokes `hash` only if it names a session of `user`; true when it did. +/// The cascade is [`revoke_session_hash`]'s, so a device gone from the list +/// takes its app tokens down with it. +pub async fn revoke_owned_session(store: &Store, user: &UserId, hash: &str) -> Result { + // Ownership reads first: a hash naming someone else's session — or no + // session at all — is a quiet false, never a revoke. + let owned = { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT user_id FROM sessions WHERE token_hash = ?1 AND revoked_at IS NULL", + turso::params![hash], + ) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) => store::text(&row, 0)? == user.as_str(), + None => false, + } + }; + if !owned { + return Ok(false); + } + revoke_session_hash(store, hash).await?; + Ok(true) +} + /// The admin's "log this person out everywhere": every central session of /// theirs dies, and the cascades above take every refresh token and every /// live app session down with them. Introspection is per-request, so the @@ -217,7 +320,9 @@ mod tests { #[tokio::test] async fn session_roundtrip_and_revoke() { let (store, user_id) = fixture().await; - let token = create_session(&store, &user_id).await.unwrap(); + let token = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); let user = resolve_session(&store, token.expose()) .await .unwrap() @@ -242,8 +347,12 @@ mod tests { #[tokio::test] async fn revoke_except_keeps_the_asking_session() { let (store, user_id) = fixture().await; - let mine = create_session(&store, &user_id).await.unwrap(); - let other = create_session(&store, &user_id).await.unwrap(); + let mine = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); + let other = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); let count = revoke_user_sessions_except(&store, &user_id, mine.expose()) .await @@ -262,4 +371,138 @@ mod tests { .is_none() ); } + + #[tokio::test] + async fn list_shows_only_active_newest_first_with_facts() { + let (store, user_id) = fixture().await; + let plain = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); + let meta = SessionMeta { + ip: Some("203.0.113.7".to_string()), + agent: Some("TestBrowser/1.0".to_string()), + }; + let noted = create_session(&store, &user_id, &meta).await.unwrap(); + + let listed = list_sessions(&store, &user_id).await.unwrap(); + assert_eq!(listed.len(), 2); + // Newest first: the noted session was created second. + assert_eq!(listed[0].token_hash, noted.hash()); + assert_eq!(listed[0].ip.as_deref(), Some("203.0.113.7")); + assert_eq!(listed[0].agent.as_deref(), Some("TestBrowser/1.0")); + assert_eq!(listed[0].seen_at, Some(listed[0].created_at)); + assert_eq!(listed[1].token_hash, plain.hash()); + assert!(listed[1].ip.is_none()); + assert!(listed[1].agent.is_none()); + assert!(listed[1].created_at <= listed[0].created_at); + + // A revoked session leaves the list; an expired one never shows. + revoke_session(&store, plain.expose()).await.unwrap(); + let listed = list_sessions(&store, &user_id).await.unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].token_hash, noted.hash()); + + let conn = store.conn.lock().await; + conn.execute( + "UPDATE sessions SET expires_at = ?1 WHERE token_hash = ?2", + turso::params![ + store::stamp(store::now() - time::Duration::days(1)).unwrap(), + noted.hash(), + ], + ) + .await + .unwrap(); + drop(conn); + assert!(list_sessions(&store, &user_id).await.unwrap().is_empty()); + } + + #[tokio::test] + async fn revoke_owned_refuses_a_strangers_session() { + let (store, user_id) = fixture().await; + let invite = create_invite(&store, "bob@example.com", None, false) + .await + .unwrap(); + let stranger = create_user_from_invite(&store, invite.expose(), "Bob", "tDLr9!mZQ2xvQ") + .await + .unwrap(); + let mine = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); + let theirs = create_session(&store, &stranger.id, &SessionMeta::default()) + .await + .unwrap(); + + // Someone else's hash is a quiet false, and their session survives it. + assert!(!revoke_owned_session(&store, &user_id, &theirs.hash()) + .await + .unwrap()); + assert!( + resolve_session(&store, theirs.expose()) + .await + .unwrap() + .is_some() + ); + assert!(!revoke_owned_session(&store, &user_id, "no-such-hash") + .await + .unwrap()); + + assert!(revoke_owned_session(&store, &user_id, &mine.hash()) + .await + .unwrap()); + assert!( + resolve_session(&store, mine.expose()) + .await + .unwrap() + .is_none() + ); + // Revoking twice is a quiet false the second time. + assert!(!revoke_owned_session(&store, &user_id, &mine.hash()) + .await + .unwrap()); + } + + #[tokio::test] + async fn resolve_touches_seen_at_past_the_throttle() { + let (store, user_id) = fixture().await; + let token = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); + // Backdate the sighting past the throttle without sleeping. + let conn = store.conn.lock().await; + conn.execute( + "UPDATE sessions SET seen_at = ?1 WHERE token_hash = ?2", + turso::params![ + store::stamp(store::now() - time::Duration::minutes(10)).unwrap(), + token.hash(), + ], + ) + .await + .unwrap(); + drop(conn); + + let before = list_sessions(&store, &user_id).await.unwrap(); + assert_eq!(before.len(), 1); + let stale = before[0].seen_at.unwrap(); + + assert!( + resolve_session(&store, token.expose()) + .await + .unwrap() + .is_some() + ); + let after = list_sessions(&store, &user_id).await.unwrap(); + assert!(after[0].seen_at.unwrap() > stale); + + // A fresh sighting is inside the throttle: resolving again is a + // no-op write, so seen_at stands still. + let fresh = after[0].seen_at.unwrap(); + assert!( + resolve_session(&store, token.expose()) + .await + .unwrap() + .is_some() + ); + let again = list_sessions(&store, &user_id).await.unwrap(); + assert_eq!(again[0].seen_at, Some(fresh)); + } } diff --git a/crates/im-core/src/store.rs b/crates/im-core/src/store.rs index b3d8d62..a48396c 100644 --- a/crates/im-core/src/store.rs +++ b/crates/im-core/src/store.rs @@ -54,7 +54,10 @@ CREATE TABLE IF NOT EXISTS sessions ( user_id TEXT NOT NULL REFERENCES users(id), created_at TEXT NOT NULL, expires_at TEXT NOT NULL, - revoked_at TEXT + revoked_at TEXT, + ip TEXT, + agent TEXT, + seen_at TEXT ); CREATE TABLE IF NOT EXISTS oidc_clients ( client_id TEXT PRIMARY KEY, @@ -179,16 +182,31 @@ impl Store { let outcome = async { conn.execute_batch(SCHEMA).await.map_err(backend)?; // Columns born after databases already existed: the CREATE above - // is `IF NOT EXISTS`, so an old users table never sees them from - // it. Each goes in with its own guarded ALTER — a boot either - // adds the column or finds it there, and re-boot is a no-op. - // The photo's bytes are never a column: they live as files under - // the storage tree (see `photos.rs`). + // is `IF NOT EXISTS`, so an old table never sees them from it. + // Each goes in with its own guarded ALTER — a boot either adds + // the column or finds it there, and re-boot is a no-op. if !has_column(&conn, "users", "photo_mime").await? { conn.execute("ALTER TABLE users ADD COLUMN photo_mime TEXT", ()) .await .map_err(backend)?; } + // What a session remembers about its browser: the listing shows + // these, so old databases grow them the same guarded way. + if !has_column(&conn, "sessions", "ip").await? { + conn.execute("ALTER TABLE sessions ADD COLUMN ip TEXT", ()) + .await + .map_err(backend)?; + } + if !has_column(&conn, "sessions", "agent").await? { + conn.execute("ALTER TABLE sessions ADD COLUMN agent TEXT", ()) + .await + .map_err(backend)?; + } + if !has_column(&conn, "sessions", "seen_at").await? { + conn.execute("ALTER TABLE sessions ADD COLUMN seen_at TEXT", ()) + .await + .map_err(backend)?; + } Ok(()) } .await; diff --git a/crates/im-migrate/src/main.rs b/crates/im-migrate/src/main.rs index d6ac83c..8860740 100644 --- a/crates/im-migrate/src/main.rs +++ b/crates/im-migrate/src/main.rs @@ -34,7 +34,8 @@ CREATE TABLE IF NOT EXISTS users ( totp_confirmed INTEGER NOT NULL DEFAULT 0, admin INTEGER NOT NULL DEFAULT 0, disabled INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL + created_at TEXT NOT NULL, + photo_mime TEXT ); CREATE TABLE IF NOT EXISTS invites ( token TEXT PRIMARY KEY, @@ -50,7 +51,10 @@ CREATE TABLE IF NOT EXISTS sessions ( user_id TEXT NOT NULL REFERENCES users(id), created_at TEXT NOT NULL, expires_at TEXT NOT NULL, - revoked_at TEXT + revoked_at TEXT, + ip TEXT, + agent TEXT, + seen_at TEXT ); CREATE TABLE IF NOT EXISTS oidc_clients ( client_id TEXT PRIMARY KEY, @@ -101,6 +105,18 @@ CREATE TABLE IF NOT EXISTS events ( actor TEXT, detail TEXT ); +CREATE TABLE IF NOT EXISTS reset_links ( + token TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id), + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + used_at TEXT +); +CREATE TABLE IF NOT EXISTS login_attempts ( + key TEXT NOT NULL, + at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS login_attempts_key ON login_attempts(key, at); CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL diff --git a/crates/im-web/assets/main.css b/crates/im-web/assets/main.css index bd029d5..8de56eb 100644 --- a/crates/im-web/assets/main.css +++ b/crates/im-web/assets/main.css @@ -523,6 +523,50 @@ body:has(.auth-stage) > .auth-stage::-webkit-scrollbar { letter-spacing: -0.01em; } +.session-list { + display: flex; + flex-direction: column; +} + +.session-row { + display: flex; + gap: 12px; + align-items: flex-start; + padding: 12px 0; + border-top: 1px solid var(--border-soft); +} +.session-row:first-child { + border-top: 0; + padding-top: 0; +} +.session-row:last-child { + padding-bottom: 0; +} +.session-row form { + flex: none; +} + +.session-main { + flex: 1; + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; +} + +.session-device { + font-size: 13px; + overflow-wrap: anywhere; +} +.session-device .chip { + margin-left: 8px; +} + +.session-meta { + font-size: 12px; + color: var(--muted); +} + @media (max-width: 720px) { .auth-stage { padding: 0 16px 24px; @@ -777,6 +821,19 @@ body:has(.admin-shell) { color: var(--ink); } +.admin-sessions summary { + cursor: pointer; + font-size: 12px; + display: inline-block; +} +.admin-sessions[open] summary { + margin-bottom: 8px; +} +.admin-sessions .admin-table td:first-child { + overflow-wrap: anywhere; + max-width: 280px; +} + input[type=checkbox] { accent-color: var(--accent); } diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index 7106ac8..cf04b89 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -162,6 +162,7 @@ async fn admin_page(cx: &Cx) -> Result { match code { "invited" => "Invite created.", "revoked" => "Sessions revoked — every device is signed out.", + "session_revoked" => "Session revoked.", "disabled" => "Account disabled.", "enabled" => "Account enabled.", "smtp" => "Mail settings saved.", @@ -229,6 +230,67 @@ fn account_section(me: &User) -> String { ) } +/// One person's live sessions as the disclosure under their row: a small +/// table with a per-session revoke, or the muted line when nothing is live. +/// The admin's own row gets one too — "you" still signs in from somewhere. +fn sessions_row(user: &User, sessions: &[im_core::sessions::SessionInfo]) -> String { + let id = escape(&user.id.to_string()); + let body = if sessions.is_empty() { + r#"
No active sessions
"#.to_string() + } else { + let mut rows = String::new(); + for session in sessions { + let seen_at = session.seen_at.unwrap_or(session.created_at); + let seen = seen_at + .format(&time::macros::format_description!( + "[year]-[month]-[day] [hour]:[minute]" + )) + .unwrap_or_else(|_| seen_at.date().to_string()); + rows.push_str(&format!( + concat!( + r#"{}"#, + r#"{}"#, + r#"{}"#, + r#"{}"#, + r#""#, + r#"
"#, + r#""#, + r#""#, + r#""#, + r#"
"# + ), + session + .agent + .as_deref() + .filter(|agent| !agent.is_empty()) + .map(escape) + .unwrap_or_else(|| "Unknown device".to_string()), + session + .ip + .as_deref() + .map(escape) + .unwrap_or_else(|| "—".to_string()), + session.created_at.date(), + seen, + escape(&session.token_hash), + id = id, + )); + } + format!( + concat!( + r#""#, + r#""#, + r#"{rows}
DeviceAddressSigned inLast seen
"# + ), + rows = rows, + ) + }; + format!( + r#"
Sessions ({}){body}
"#, + sessions.len() + ) +} + async fn users_section( cx: &Cx, me: &User, @@ -298,6 +360,8 @@ async fn users_section( flags, actions )); + let sessions = im_core::sessions::list_sessions(&app(cx).store, &user.id).await?; + rows.push_str(&sessions_row(user, &sessions)); } // Invites still waiting on their person sit in the same table — "waiting" // instead of a name, and the one action an outstanding link understands: @@ -673,6 +737,28 @@ async fn revoke(cx: &Cx, Form(input): Form) -> Result { back(cx, "users", "&ok=revoked") } +#[derive(Deserialize)] +struct SessionRevokeForm { + user: String, + session: String, +} + +/// Revokes one session of one person — the per-row door beside the +/// sign-them-out-everywhere one above. +#[route(POST "/admin/session_revoke")] +async fn session_revoke(cx: &Cx, Form(input): Form) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + let user_id = UserId::from(input.user.clone()); + if !im_core::sessions::revoke_owned_session(&app(cx).store, &user_id, &input.session).await? { + return back(cx, "users", "&error=session_unknown"); + } + server::log_event(cx, "session_revoked", Some(&me.email), Some(&input.user)).await; + back(cx, "users", "&ok=session_revoked") +} + #[route(POST "/admin/disable")] async fn disable(cx: &Cx, Form(input): Form) -> Result { set_disabled(cx, input, true).await diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index 6fa9b5c..5c0e1ef 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -43,6 +43,34 @@ fn safe_back(raw: &str) -> &str { } } +/// Creation-time facts for the session row: the address the browser came +/// through and the agent it claims to be. The accept loop discards the peer +/// address, so the proxy headers are the only source — the first +/// `x-forwarded-for` hop, else `x-real-ip`, else nothing known. +fn session_meta(cx: &Cx) -> im_core::sessions::SessionMeta { + let headers = topcoat::router::request::headers(cx); + let ip = headers + .get("x-forwarded-for") + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.split(',').next()) + .map(str::trim) + .filter(|hop| !hop.is_empty()) + .map(str::to_string) + .or_else(|| { + headers + .get("x-real-ip") + .and_then(|value| value.to_str().ok()) + .map(str::trim) + .filter(|ip| !ip.is_empty()) + .map(str::to_string) + }); + let agent = headers + .get("user-agent") + .and_then(|value| value.to_str().ok()) + .map(|value| value.chars().take(255).collect::()); + im_core::sessions::SessionMeta { ip, agent } +} + #[derive(Deserialize)] pub struct LoginForm { email: String, @@ -138,7 +166,7 @@ async fn login_totp(cx: &Cx, Form(input): Form) -> Redirect { return see("/login/totp?error=bad_code".to_string()); } let _ = accounts::clear_login_failures(store, &totp_key).await; - let token = im_core::sessions::create_session(store, &user_id).await?; + let token = im_core::sessions::create_session(store, &user_id, &session_meta(cx)).await?; let email = accounts::user_by_id(store, &user_id) .await? .map(|u| u.email); @@ -219,7 +247,7 @@ async fn enroll(cx: &Cx, Form(input): Form) -> Redirect { return see("/enroll?error=bad_code".to_string()); } im_core::totp::confirm_totp(store, &user_id).await?; - let token = im_core::sessions::create_session(store, &user_id).await?; + let token = im_core::sessions::create_session(store, &user_id, &session_meta(cx)).await?; let email = accounts::user_by_id(store, &user_id) .await? .map(|u| u.email); @@ -307,3 +335,38 @@ async fn reset(cx: &Cx, Form(input): Form) -> Redirect { Err(e) => Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), } } + +#[derive(Deserialize)] +struct SessionRevokeForm { + session: String, +} + +/// Revokes one of the signer's own sessions. The current one signs this +/// browser out — the server row dies and the cookie is tidied; any other +/// just dies where it lives. +#[route(POST "/sessions/revoke")] +async fn revoke_session(cx: &Cx, Form(input): Form) -> Redirect { + let Some(user) = server::current_user(cx).await else { + return see("/".to_string()); + }; + let store = &server::app(cx).store; + if let Some(presented) = server::presented_session(cx) { + if im_core::accounts::hash_token(&presented) == input.session { + im_core::sessions::revoke_session(store, &presented).await?; + server::clear_session_cookie(cx); + return see("/".to_string()); + } + } + // The row's address, when it is still there, is the useful half of the + // log line — which of their devices they just killed. + let ip = im_core::sessions::list_sessions(store, &user.id) + .await? + .into_iter() + .find(|s| s.token_hash == input.session) + .and_then(|s| s.ip); + if !im_core::sessions::revoke_owned_session(store, &user.id, &input.session).await? { + return see("/?error=session_unknown".to_string()); + } + server::log_event(cx, "session_revoked", Some(&user.email), ip.as_deref()).await; + see("/?ok=session_revoked".to_string()) +} diff --git a/crates/im-web/src/pages.rs b/crates/im-web/src/pages.rs index 5108672..643f921 100644 --- a/crates/im-web/src/pages.rs +++ b/crates/im-web/src/pages.rs @@ -38,6 +38,7 @@ pub fn error_text(code: &str) -> &'static str { "not_an_image" => "That file is not an image.", "no_file" => "Choose an image first.", "reset_invalid" => "This reset link is not valid — ask for a fresh one.", + "session_unknown" => "That session is already gone.", _ => "Something went wrong. Try again.", } } @@ -49,6 +50,7 @@ pub fn ok_text(code: &str) -> &'static str { "enrolled" => "Two-factor sign-in is on. You're all set.", "photo_saved" => "Profile photo updated.", "photo_removed" => "Profile photo removed.", + "session_revoked" => "Session revoked.", _ => "Done.", } } @@ -409,6 +411,79 @@ async fn enroll(cx: &Cx) -> Result { .into_response(cx) } +/// The sessions card builds its rows as a string — one per live session — +/// so its interpolations never pass through `view!`'s escaping. The +/// discipline matches admin.rs's `escape`: everything user-controlled +/// (agent, address) crosses it before it reaches the markup. +fn escape(raw: &str) -> String { + raw.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) +} + +/// The device line of a session row: the agent shortened to fit the row, or +/// the honest fallback when the session predates agent capture. +fn device_name(agent: Option<&str>) -> String { + const MAX: usize = 80; + match agent { + None | Some("") => "Unknown device".to_string(), + Some(agent) if agent.chars().count() > MAX => { + format!("{}…", agent.chars().take(MAX).collect::()) + } + Some(agent) => agent.to_string(), + } +} + +/// `2026-09-04 10:22`: the last-seen stamp. An unrenderable stamp falls back +/// to the day — a stamp that cannot print must still say something true. +fn stamp_min(when: time::OffsetDateTime) -> String { + when.format(&time::macros::format_description!( + "[year]-[month]-[day] [hour]:[minute]" + )) + .unwrap_or_else(|_| when.date().to_string()) +} + +/// The sessions card's rows: device, address, stamps, and the per-session +/// revoke. The current row wears the chip and its button reads as the way +/// out of this browser; every other button names what it does instead. +fn sessions_html(sessions: &[im_core::sessions::SessionInfo], current: Option<&str>) -> String { + let mut rows = String::new(); + for session in sessions { + let mine = current == Some(session.token_hash.as_str()); + let seen = session.seen_at.unwrap_or(session.created_at); + let chip = if mine { + r#" This session"# + } else { + "" + }; + rows.push_str(&format!( + concat!( + r#"
"#, + r#"
{}{}
"#, + r#"
{}
"#, + r#"
Signed in {} · Last seen {}
"#, + r#"
"#, + r#"
"#, + r#""#, + r#"
"# + ), + escape(&device_name(session.agent.as_deref())), + chip, + session + .ip + .as_deref() + .map(escape) + .unwrap_or_else(|| "—".to_string()), + session.created_at.date(), + stamp_min(seen), + escape(&session.token_hash), + if mine { "Sign out" } else { "Revoke" }, + )); + } + rows +} + /// The signed-in landing. im is an auth service, not an app: this page is /// the proof of session, the person's profile — photo and the counts their /// 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 { let error = query_value(&query, "error"); let stats = im_core::stats::profile_stats(&server::app(cx).store, &user.id).await?; let joined = user.created_at.date().to_string(); + let sessions = im_core::sessions::list_sessions(&server::app(cx).store, &user.id).await?; + let current = + server::presented_session(cx).map(|token| im_core::accounts::hash_token(&token)); + let sessions_html = sessions_html(&sessions, current.as_deref()); let stage = view! { cx =>
@@ -536,6 +615,10 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { +
+
"Sessions"
+
(topcoat::view::Unescaped::new_unchecked(sessions_html))
+