forge
Explore
Log in

Don't you dare go Hollow

a person's sign-ins are capped by the panel's new per-user ceiling: create_session, already the one door every login walks through, keeps the newest max_sessions live rows and revokes the overflow in the same critical section as the insert — newest-first with a rowid tiebreak so the cut is deterministic and the fresh login never evicts itself, expired rows holding no slot — and the cascade already written for revocation takes the overflow's app sessions and refresh tokens down with it, so the oldest device is truly logged out, not just the cookie ignored; the ceiling defaults to five, clamped at one, set from the admin panel's settings card as 'Sign-in sessions per user'; and every person can now see their connected apps: a new apps tab on the signed-in landing lists the OIDC clients holding live grants — name, client id, grant count, last connected — grouped per client from list_connected_apps, empty-noted when nothing is connected, everything user-or-app-controlled escaped

Browse files at this commit

586231628c35f9dbc2b81c53790477bd14e36debAhmet Kaan GümüşParent: 474a6f1
crates/im-core/src/oidc.rsmodified+186 -0
@@ -516,6 +516,51 @@ pub async fn introspect_app_session(
516 })))516 })))
517 }517 }
518 518
519+/// One app a person is signed into, as the connected-apps list shows it:
520+/// the client, its display name, how many of its app sessions are live,
521+/// and when the person first and last connected to it.
522+#[derive(Debug, Clone)]
523+pub struct ConnectedApp {
524+ pub client_id: String,
525+ pub name: String,
526+ pub count: i64,
527+ pub first_at: time::OffsetDateTime,
528+ pub last_at: time::OffsetDateTime,
529+}
530+
531+/// The OIDC clients holding at least one live app session for `user`,
532+/// most recently connected first. Revocation and expiry filter in SQL
533+/// beside the introspection answer and `stats`' counts; the display name
534+/// falls back to the raw `client_id` when no registered client row stands
535+/// behind it.
536+pub async fn list_connected_apps(store: &Store, user: &UserId) -> Result<Vec<ConnectedApp>> {
537+ let conn = store.conn.lock().await;
538+ let mut rows = conn
539+ .query(
540+ "SELECT a.client_id, COALESCE(c.name, a.client_id), COUNT(*), \
541+ MIN(a.created_at), MAX(a.created_at) \
542+ FROM app_sessions a \
543+ LEFT JOIN oidc_clients c ON c.client_id = a.client_id \
544+ WHERE a.user_id = ?1 AND a.revoked_at IS NULL AND a.expires_at > ?2 \
545+ GROUP BY a.client_id \
546+ ORDER BY MAX(a.created_at) DESC, a.client_id",
547+ turso::params![user.to_string(), store::stamp(store::now())?],
548+ )
549+ .await
550+ .map_err(backend)?;
551+ let mut out = Vec::new();
552+ while let Some(row) = rows.next().await.map_err(backend)? {
553+ out.push(ConnectedApp {
554+ client_id: store::text(&row, 0)?,
555+ name: store::text(&row, 1)?,
556+ count: store::int(&row, 2)?,
557+ first_at: store::parse_stamp(&store::text(&row, 3)?)?,
558+ last_at: store::parse_stamp(&store::text(&row, 4)?)?,
559+ });
560+ }
561+ Ok(out)
562+}
563+
519 #[cfg(test)]564 #[cfg(test)]
520 mod tests {565 mod tests {
521 use super::*;566 use super::*;
@@ -723,4 +768,145 @@ mod tests {
723 .contains(&"http://app/callback".to_string())768 .contains(&"http://app/callback".to_string())
724 );769 );
725 }770 }
771+
772+ #[tokio::test]
773+ async fn connected_apps_list_live_grants_newest_first() {
774+ let (store, client_id, user_id) = fixture().await;
775+ let (other_id, _secret) =
776+ create_client(&store, "other", vec!["http://other/callback".into()])
777+ .await
778+ .unwrap();
779+ let session = create_session(&store, &user_id, &SessionMeta::default())
780+ .await
781+ .unwrap();
782+
783+ // Two grants on the first client, one on the second; the second
784+ // client connected last and leads.
785+ issue_app_session(&store, &user_id, &client_id, &session.hash())
786+ .await
787+ .unwrap();
788+ issue_app_session(&store, &user_id, &client_id, &session.hash())
789+ .await
790+ .unwrap();
791+ issue_app_session(&store, &user_id, &other_id, &session.hash())
792+ .await
793+ .unwrap();
794+ let apps = list_connected_apps(&store, &user_id).await.unwrap();
795+ assert_eq!(apps.len(), 2);
796+ assert_eq!(apps[0].client_id, other_id.as_str());
797+ assert_eq!(apps[0].name, "other");
798+ assert_eq!(apps[0].count, 1);
799+ // The first client aggregates its two grants under its registered
800+ // display name.
801+ assert_eq!(apps[1].client_id, client_id.as_str());
802+ assert_eq!(apps[1].name, "demo");
803+ assert_eq!(apps[1].count, 2);
804+ assert!(apps[1].first_at <= apps[1].last_at);
805+
806+ // Backdate the second client's grant an hour: it connected last no
807+ // more, and the order follows the stamps, not the inserts.
808+ let conn = store.conn.lock().await;
809+ conn.execute(
810+ "UPDATE app_sessions SET created_at = ?1 WHERE client_id = ?2",
811+ turso::params![
812+ store::stamp(store::now() - time::Duration::hours(1)).unwrap(),
813+ other_id.as_str(),
814+ ],
815+ )
816+ .await
817+ .unwrap();
818+ drop(conn);
819+ let apps = list_connected_apps(&store, &user_id).await.unwrap();
820+ assert_eq!(apps[0].client_id, client_id.as_str());
821+ assert_eq!(apps[1].client_id, other_id.as_str());
822+ assert_eq!(apps[1].first_at, apps[1].last_at);
823+
824+ // Another person's grants never show up in someone else's list.
825+ let invite = create_invite(&store, "bob@example.com", None, false)
826+ .await
827+ .unwrap();
828+ let bob = create_user_from_invite(&store, invite.expose(), "Bob", "tDLr9!mZQ2xvQ")
829+ .await
830+ .unwrap();
831+ let bobs_session = create_session(&store, &bob.id, &SessionMeta::default())
832+ .await
833+ .unwrap();
834+ issue_app_session(&store, &bob.id, &other_id, &bobs_session.hash())
835+ .await
836+ .unwrap();
837+ let bobs_apps = list_connected_apps(&store, &bob.id).await.unwrap();
838+ assert_eq!(bobs_apps.len(), 1);
839+ assert_eq!(bobs_apps[0].client_id, other_id.as_str());
840+ assert_eq!(bobs_apps[0].count, 1);
841+ }
842+
843+ #[tokio::test]
844+ async fn connected_apps_skip_revoked_grants_and_fall_back_to_raw_ids() {
845+ let (store, client_id, user_id) = fixture().await;
846+ let session = create_session(&store, &user_id, &SessionMeta::default())
847+ .await
848+ .unwrap();
849+
850+ // Two grants on the client; then one of them is revoked.
851+ let revocable = issue_app_session(&store, &user_id, &client_id, &session.hash())
852+ .await
853+ .unwrap();
854+ issue_app_session(&store, &user_id, &client_id, &session.hash())
855+ .await
856+ .unwrap();
857+ let conn = store.conn.lock().await;
858+ conn.execute(
859+ "UPDATE app_sessions SET revoked_at = ?1 WHERE token_hash = ?2",
860+ turso::params![
861+ store::stamp(store::now()).unwrap(),
862+ hash_token(revocable.expose()),
863+ ],
864+ )
865+ .await
866+ .unwrap();
867+ drop(conn);
868+ let apps = list_connected_apps(&store, &user_id).await.unwrap();
869+ assert_eq!(apps.len(), 1);
870+ assert_eq!(apps[0].client_id, client_id.as_str());
871+ assert_eq!(apps[0].count, 1);
872+
873+ // A grant whose client row never existed shows the raw client_id
874+ // as its name.
875+ let conn = store.conn.lock().await;
876+ conn.execute(
877+ "INSERT INTO app_sessions \
878+ (token_hash, user_id, client_id, session_hash, created_at, expires_at) \
879+ VALUES ('ghost-hash', ?1, 'ghost-app', ?2, ?3, ?4)",
880+ turso::params![
881+ user_id.to_string(),
882+ session.hash(),
883+ store::stamp(store::now()).unwrap(),
884+ store::stamp(store::now() + time::Duration::days(30)).unwrap(),
885+ ],
886+ )
887+ .await
888+ .unwrap();
889+ drop(conn);
890+ let apps = list_connected_apps(&store, &user_id).await.unwrap();
891+ assert_eq!(apps.len(), 2);
892+ let ghost = apps
893+ .iter()
894+ .find(|app| app.client_id == "ghost-app")
895+ .unwrap();
896+ assert_eq!(ghost.name, "ghost-app");
897+ assert_eq!(ghost.count, 1);
898+
899+ // And an expired grant is not a connected app either.
900+ let conn = store.conn.lock().await;
901+ conn.execute(
902+ "UPDATE app_sessions SET expires_at = ?1 WHERE client_id = 'ghost-app'",
903+ turso::params![store::stamp(store::now() - time::Duration::days(1)).unwrap()],
904+ )
905+ .await
906+ .unwrap();
907+ drop(conn);
908+ let apps = list_connected_apps(&store, &user_id).await.unwrap();
909+ assert_eq!(apps.len(), 1);
910+ assert_eq!(apps[0].client_id, client_id.as_str());
911+ }
726 }912 }
crates/im-core/src/sessions.rsmodified+164 -2
@@ -36,10 +36,17 @@ pub struct SessionInfo {
36 /// Creates a session for `user`, returning the raw cookie token. The row36 /// Creates a session for `user`, returning the raw cookie token. The row
37 /// holds only its digest, plus what `meta` says about the browser — and the37 /// holds only its digest, plus what `meta` says about the browser — and the
38 /// first sighting is creation itself, so `seen_at` starts at `created_at`.38 /// first sighting is creation itself, so `seen_at` starts at `created_at`.
39+///
40+/// The panel's `max_sessions` policy caps how many live sessions one
41+/// person may hold: past the cap the oldest of their sessions is revoked
42+/// in the same write, and the cascade takes every app session and refresh
43+/// token born under it down too. The session being created is the newest
44+/// by construction, so a fresh login never evicts itself.
39 pub async fn create_session(store: &Store, user: &UserId, meta: &SessionMeta) -> Result<Token> {45 pub async fn create_session(store: &Store, user: &UserId, meta: &SessionMeta) -> Result<Token> {
40 let token = Token::mint();46 let token = Token::mint();
41 let now = store::now();47 let now = store::now();
42- let days = crate::settings::policy(store).await?.session_days;48+ // One policy read serves both the lifetime and the per-user cap.
49+ let policy = crate::settings::policy(store).await?;
43 let conn = store.conn.lock().await;50 let conn = store.conn.lock().await;
44 conn.execute(51 conn.execute(
45 "INSERT INTO sessions (token_hash, user_id, created_at, expires_at, ip, agent, seen_at) \52 "INSERT INTO sessions (token_hash, user_id, created_at, expires_at, ip, agent, seen_at) \
@@ -48,13 +55,45 @@ pub async fn create_session(store: &Store, user: &UserId, meta: &SessionMeta) ->
48 token.hash(),55 token.hash(),
49 user.to_string(),56 user.to_string(),
50 store::stamp(now)?,57 store::stamp(now)?,
51- store::stamp(now + time::Duration::days(days))?,58+ store::stamp(now + time::Duration::days(policy.session_days))?,
52 meta.ip.clone(),59 meta.ip.clone(),
53 meta.agent.clone(),60 meta.agent.clone(),
54 ],61 ],
55 )62 )
56 .await63 .await
57 .map_err(backend)?;64 .map_err(backend)?;
65+ // The cap, enforced beside the insert: keep the newest `max_sessions`
66+ // live sessions of this user and revoke the rest, under the same lock
67+ // so the store never shows more than the cap allows. Newest-first with
68+ // a rowid tiebreak keeps the cut deterministic when stamps collide, and
69+ // an expired row is no session anymore — it neither holds a slot nor
70+ // needs a revoke.
71+ let mut rows = conn
72+ .query(
73+ "SELECT token_hash, expires_at FROM sessions \
74+ WHERE user_id = ?1 AND revoked_at IS NULL \
75+ ORDER BY created_at DESC, rowid DESC",
76+ turso::params![user.to_string()],
77+ )
78+ .await
79+ .map_err(backend)?;
80+ let mut kept = 0i64;
81+ let mut overflow = Vec::new();
82+ while let Some(row) = rows.next().await.map_err(backend)? {
83+ // Expiry is a stamp comparison beside `resolve_session`, where a
84+ // corrupt stamp surfaces as an error.
85+ if store::parse_stamp(&store::text(&row, 1)?)? < now {
86+ continue;
87+ }
88+ if kept < policy.max_sessions {
89+ kept += 1;
90+ } else {
91+ overflow.push(store::text(&row, 0)?);
92+ }
93+ }
94+ for hash in &overflow {
95+ revoke_session_hash_conn(&conn, hash).await?;
96+ }
58 Ok(token)97 Ok(token)
59 }98 }
60 99
@@ -120,6 +159,13 @@ pub async fn revoke_session(store: &Store, token: &str) -> Result<()> {
120 /// revoke-everything below.159 /// revoke-everything below.
121 pub(crate) async fn revoke_session_hash(store: &Store, hash: &str) -> Result<()> {160 pub(crate) async fn revoke_session_hash(store: &Store, hash: &str) -> Result<()> {
122 let conn = store.conn.lock().await;161 let conn = store.conn.lock().await;
162+ revoke_session_hash_conn(&conn, hash).await
163+}
164+
165+/// The UPDATE half of [`revoke_session_hash`], runnable under a lock the
166+/// caller already holds — session creation revokes its overflow with it
167+/// inside the same critical section that inserts the fresh row.
168+async fn revoke_session_hash_conn(conn: &turso::Connection, hash: &str) -> Result<()> {
123 let now = store::stamp(store::now())?;169 let now = store::stamp(store::now())?;
124 conn.execute(170 conn.execute(
125 "UPDATE sessions SET revoked_at = ?1 WHERE token_hash = ?2 AND revoked_at IS NULL",171 "UPDATE sessions SET revoked_at = ?1 WHERE token_hash = ?2 AND revoked_at IS NULL",
@@ -505,4 +551,120 @@ mod tests {
505 let again = list_sessions(&store, &user_id).await.unwrap();551 let again = list_sessions(&store, &user_id).await.unwrap();
506 assert_eq!(again[0].seen_at, Some(fresh));552 assert_eq!(again[0].seen_at, Some(fresh));
507 }553 }
554+
555+ #[tokio::test]
556+ async fn cap_evicts_the_oldest_session_and_its_app_tokens() {
557+ let (store, user_id) = fixture().await;
558+ let mut tokens = Vec::new();
559+ for _ in 0..5 {
560+ tokens.push(
561+ create_session(&store, &user_id, &SessionMeta::default())
562+ .await
563+ .unwrap(),
564+ );
565+ }
566+ // An app session and a refresh token ride on the oldest central
567+ // session, so the eviction's cascade has something to kill.
568+ let (client_id, _secret) =
569+ crate::oidc::create_client(&store, "evictee", vec!["http://app/callback".into()])
570+ .await
571+ .unwrap();
572+ let oldest = &tokens[0];
573+ let app_token =
574+ crate::oidc::issue_app_session(&store, &user_id, &client_id, &oldest.hash())
575+ .await
576+ .unwrap();
577+ let refresh =
578+ crate::oidc::issue_refresh(&store, &user_id, &client_id, &oldest.hash())
579+ .await
580+ .unwrap();
581+
582+ // The sixth login pushes the first one out.
583+ let fresh = create_session(&store, &user_id, &SessionMeta::default())
584+ .await
585+ .unwrap();
586+ assert!(
587+ resolve_session(&store, oldest.expose())
588+ .await
589+ .unwrap()
590+ .is_none()
591+ );
592+ for token in &tokens[1..] {
593+ assert!(
594+ resolve_session(&store, token.expose())
595+ .await
596+ .unwrap()
597+ .is_some()
598+ );
599+ }
600+ assert!(
601+ resolve_session(&store, fresh.expose())
602+ .await
603+ .unwrap()
604+ .is_some()
605+ );
606+ assert_eq!(list_sessions(&store, &user_id).await.unwrap().len(), 5);
607+
608+ // The cascade: the evicted session's app session and refresh token
609+ // stop resolving too.
610+ assert!(
611+ crate::oidc::introspect_app_session(
612+ &store,
613+ app_token.expose(),
614+ client_id.as_str()
615+ )
616+ .await
617+ .unwrap()
618+ .is_none()
619+ );
620+ assert!(
621+ crate::oidc::rotate_refresh(&store, refresh.expose())
622+ .await
623+ .unwrap()
624+ .is_none()
625+ );
626+ }
627+
628+ #[tokio::test]
629+ async fn cap_follows_the_policy() {
630+ let (store, user_id) = fixture().await;
631+ crate::settings::set_policy(
632+ &store,
633+ &crate::settings::Policy {
634+ max_sessions: 2,
635+ ..Default::default()
636+ },
637+ )
638+ .await
639+ .unwrap();
640+
641+ let first = create_session(&store, &user_id, &SessionMeta::default())
642+ .await
643+ .unwrap();
644+ let second = create_session(&store, &user_id, &SessionMeta::default())
645+ .await
646+ .unwrap();
647+ // The third login evicts the first: the cap is two now.
648+ let third = create_session(&store, &user_id, &SessionMeta::default())
649+ .await
650+ .unwrap();
651+ assert!(
652+ resolve_session(&store, first.expose())
653+ .await
654+ .unwrap()
655+ .is_none()
656+ );
657+ assert!(
658+ resolve_session(&store, second.expose())
659+ .await
660+ .unwrap()
661+ .is_some()
662+ );
663+ assert!(
664+ resolve_session(&store, third.expose())
665+ .await
666+ .unwrap()
667+ .is_some()
668+ );
669+ }
508 }670 }
crates/im-core/src/settings.rsmodified+33 -0
@@ -238,6 +238,7 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res
238 pub struct Policy {238 pub struct Policy {
239 pub invite_days: i64,239 pub invite_days: i64,
240 pub session_days: i64,240 pub session_days: i64,
241+ pub max_sessions: i64,
241 pub pending_minutes: i64,242 pub pending_minutes: i64,
242 pub reset_minutes: i64,243 pub reset_minutes: i64,
243 pub login_attempts_per_hour: i64,244 pub login_attempts_per_hour: i64,
@@ -248,6 +249,7 @@ impl Default for Policy {
248 Self {249 Self {
249 invite_days: 7,250 invite_days: 7,
250 session_days: 30,251 session_days: 30,
252+ max_sessions: 5,
251 pending_minutes: 10,253 pending_minutes: 10,
252 reset_minutes: 60,254 reset_minutes: 60,
253 login_attempts_per_hour: 10,255 login_attempts_per_hour: 10,
@@ -268,6 +270,7 @@ pub async fn policy(store: &Store) -> Result<Policy> {
268 Ok(Policy {270 Ok(Policy {
269 invite_days: number(store, "invite_days", defaults.invite_days).await?,271 invite_days: number(store, "invite_days", defaults.invite_days).await?,
270 session_days: number(store, "session_days", defaults.session_days).await?,272 session_days: number(store, "session_days", defaults.session_days).await?,
273+ max_sessions: number(store, "max_sessions", defaults.max_sessions).await?,
271 pending_minutes: number(store, "pending_minutes", defaults.pending_minutes).await?,274 pending_minutes: number(store, "pending_minutes", defaults.pending_minutes).await?,
272 reset_minutes: number(store, "reset_minutes", defaults.reset_minutes).await?,275 reset_minutes: number(store, "reset_minutes", defaults.reset_minutes).await?,
273 login_attempts_per_hour: number(276 login_attempts_per_hour: number(
@@ -297,6 +300,12 @@ pub async fn set_policy(store: &Store, policy: &Policy) -> Result<()> {
297 &clamp(policy.session_days, defaults.session_days).to_string(),300 &clamp(policy.session_days, defaults.session_days).to_string(),
298 )301 )
299 .await?;302 .await?;
303+ set(
304+ store,
305+ "max_sessions",
306+ &clamp(policy.max_sessions, defaults.max_sessions).to_string(),
307+ )
308+ .await?;
300 set(309 set(
301 store,310 store,
302 "pending_minutes",311 "pending_minutes",
@@ -461,4 +470,28 @@ mod tests {
461 assert_eq!(standing(&store).await.unwrap(), Standing::Unchecked);470 assert_eq!(standing(&store).await.unwrap(), Standing::Unchecked);
462 assert!(last_check(&store).await.unwrap().is_none());471 assert!(last_check(&store).await.unwrap().is_none());
463 }472 }
473+
474+ #[tokio::test]
475+ async fn policy_defaults_roundtrip_and_zero_clamps_to_default() {
476+ let store = Store::open(Path::new(":memory:")).await.unwrap();
477+
478+ // A fresh database reads as the born-with defaults.
479+ assert_eq!(policy(&store).await.unwrap(), Policy::default());
480+ assert_eq!(policy(&store).await.unwrap().max_sessions, 5);
481+
482+ // A written value comes back...
483+ let mut value = Policy::default();
484+ value.max_sessions = 2;
485+ set_policy(&store, &value).await.unwrap();
486+ assert_eq!(policy(&store).await.unwrap().max_sessions, 2);
487+
488+ // ...and zero or negative — a cap that would lock every user out
489+ // of their own account — clamps back to the default, unstored.
490+ value.max_sessions = 0;
491+ set_policy(&store, &value).await.unwrap();
492+ assert_eq!(policy(&store).await.unwrap().max_sessions, 5);
493+ value.max_sessions = -3;
494+ set_policy(&store, &value).await.unwrap();
495+ assert_eq!(policy(&store).await.unwrap().max_sessions, 5);
496+ }
464 }497 }
crates/im-web/src/admin.rsmodified+8 -2
@@ -604,8 +604,8 @@ async fn service_outcome(
604 }604 }
605 605
606 /// The knobs the code shipped with, now the panel's: invite and reset link606 /// The knobs the code shipped with, now the panel's: invite and reset link
607-/// lifetimes, the sign-in session's days, the pending marker's minutes, and607+/// lifetimes, the sign-in session's days and per-user ceiling, the pending
608-/// the sign-in failure ceiling. Same form skin as Mail.608+/// marker's minutes, and the sign-in failure ceiling. Same form skin as Mail.
609 async fn settings_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::Error> {609 async fn settings_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::Error> {
610 let policy = settings::policy(&app(cx).store).await?;610 let policy = settings::policy(&app(cx).store).await?;
611 Ok(format!(611 Ok(format!(
@@ -617,6 +617,8 @@ async fn settings_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::
617 <input class="auth-input auth-input-mono" type="number" name="invite_days" min="1" value="{}"></label>617 <input class="auth-input auth-input-mono" type="number" name="invite_days" min="1" value="{}"></label>
618 <label class="auth-field"><span class="auth-label">{session_days}</span>618 <label class="auth-field"><span class="auth-label">{session_days}</span>
619 <input class="auth-input auth-input-mono" type="number" name="session_days" min="1" value="{}"></label>619 <input class="auth-input auth-input-mono" type="number" name="session_days" min="1" value="{}"></label>
620+ <label class="auth-field"><span class="auth-label">{max_sessions}</span>
621+ <input class="auth-input auth-input-mono" type="number" name="max_sessions" min="1" value="{}"></label>
620 <label class="auth-field"><span class="auth-label">{pending_minutes}</span>622 <label class="auth-field"><span class="auth-label">{pending_minutes}</span>
621 <input class="auth-input auth-input-mono" type="number" name="pending_minutes" min="1" value="{}"></label>623 <input class="auth-input auth-input-mono" type="number" name="pending_minutes" min="1" value="{}"></label>
622 <label class="auth-field"><span class="auth-label">{reset_minutes}</span>624 <label class="auth-field"><span class="auth-label">{reset_minutes}</span>
@@ -628,6 +630,7 @@ async fn settings_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::
628 </div>"#,630 </div>"#,
629 policy.invite_days,631 policy.invite_days,
630 policy.session_days,632 policy.session_days,
633+ policy.max_sessions,
631 policy.pending_minutes,634 policy.pending_minutes,
632 policy.reset_minutes,635 policy.reset_minutes,
633 policy.login_attempts_per_hour,636 policy.login_attempts_per_hour,
@@ -635,6 +638,7 @@ async fn settings_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::
635 sub = t(lang, Key::SettingsSub),638 sub = t(lang, Key::SettingsSub),
636 invite_days = t(lang, Key::InviteDaysLabel),639 invite_days = t(lang, Key::InviteDaysLabel),
637 session_days = t(lang, Key::SessionDaysLabel),640 session_days = t(lang, Key::SessionDaysLabel),
641+ max_sessions = t(lang, Key::MaxSessionsLabel),
638 pending_minutes = t(lang, Key::PendingMinutesLabel),642 pending_minutes = t(lang, Key::PendingMinutesLabel),
639 reset_minutes = t(lang, Key::ResetMinutesLabel),643 reset_minutes = t(lang, Key::ResetMinutesLabel),
640 attempts = t(lang, Key::LoginAttemptsLabel),644 attempts = t(lang, Key::LoginAttemptsLabel),
@@ -646,6 +650,7 @@ async fn settings_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::
646 struct PolicyForm {650 struct PolicyForm {
647 invite_days: i64,651 invite_days: i64,
648 session_days: i64,652 session_days: i64,
653+ max_sessions: i64,
649 pending_minutes: i64,654 pending_minutes: i64,
650 reset_minutes: i64,655 reset_minutes: i64,
651 login_attempts_per_hour: i64,656 login_attempts_per_hour: i64,
@@ -663,6 +668,7 @@ async fn settings_save(cx: &Cx, Form(input): Form<PolicyForm>) -> Result<Respons
663 &settings::Policy {668 &settings::Policy {
664 invite_days: input.invite_days,669 invite_days: input.invite_days,
665 session_days: input.session_days,670 session_days: input.session_days,
671+ max_sessions: input.max_sessions,
666 pending_minutes: input.pending_minutes,672 pending_minutes: input.pending_minutes,
667 reset_minutes: input.reset_minutes,673 reset_minutes: input.reset_minutes,
668 login_attempts_per_hour: input.login_attempts_per_hour,674 login_attempts_per_hour: input.login_attempts_per_hour,
crates/im-web/src/directory.rsmodified+77 -0
@@ -916,4 +916,81 @@ mod tests {
916 // The unowned rows still do.916 // The unowned rows still do.
917 assert!(panel.contains(r#"action="/admin/services_remove""#));917 assert!(panel.contains(r#"action="/admin/services_remove""#));
918 }918 }
919+ #[tokio::test]
920+ async fn admin_settings_save_and_echo_the_max_sessions_ceiling() {
921+ let Setup { router, store, .. } = setup().await;
922+ let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
923+ .await
924+ .unwrap()
925+ .unwrap();
926+ let session = im_core::sessions::create_session(&store, &ada.id, &Default::default())
927+ .await
928+ .unwrap();
929+ let cookie = format!("{SESSION_COOKIE}={}", session.expose());
930+
931+ let (_status, location, _) = post_form(
932+ &router,
933+ "/admin/settings",
934+ "invite_days=30&session_days=7&max_sessions=2&pending_minutes=10&reset_minutes=15&login_attempts_per_hour=20",
935+ Some(&cookie),
936+ )
937+ .await;
938+ assert_eq!(
939+ location.as_deref(),
940+ Some("/admin?section=settings&ok=settings")
941+ );
942+ let panel = get_page(&router, "/admin?section=settings", &cookie).await;
943+ assert!(
944+ panel.contains(r#"name="max_sessions" min="1" value="2""#),
945+ "the saved ceiling must echo back into the form: {panel}"
946+ );
947+ }
948+
949+ #[tokio::test]
950+ async fn the_landing_lists_connected_apps_and_an_empty_note_without_them() {
951+ let Setup {
952+ router,
953+ client_id,
954+ store,
955+ ..
956+ } = setup().await;
957+ let ben = im_core::accounts::user_by_email(&store, "ben@example.com")
958+ .await
959+ .unwrap()
960+ .unwrap();
961+ let session = im_core::sessions::create_session(&store, &ben.id, &Default::default())
962+ .await
963+ .unwrap();
964+ let cookie = format!("{SESSION_COOKIE}={}", session.expose());
965+
966+ // No grants yet: the section is its empty note, with no rows at all.
967+ let page = get_page(&router, "/?section=apps", &cookie).await;
968+ assert!(page.contains("Connected apps"), "the title is missing");
969+ assert!(
970+ page.contains("No apps are connected yet."),
971+ "the empty note is missing: {page}"
972+ );
973+
974+ // A minted app session is a grant: the seeded app shows under Ben's
975+ // landing with its name, its client id and its active count.
976+ im_core::oidc::issue_app_session(
977+ &store,
978+ &ben.id,
979+ &ClientId::from(client_id.clone()),
980+ &im_core::accounts::hash_token(session.expose()),
981+ )
982+ .await
983+ .unwrap();
984+ let page = get_page(&router, "/?section=apps", &cookie).await;
985+ assert!(page.contains("tasks"), "the app's name is missing: {page}");
986+ assert!(
987+ page.contains(&client_id),
988+ "the client id is missing: {page}"
989+ );
990+ assert!(
991+ !page.contains("No apps are connected yet."),
992+ "the empty note must yield once a grant exists"
993+ );
994+ }
995+
919 }996 }
crates/im-web/src/i18n.rsmodified+15 -0
@@ -145,6 +145,10 @@ pub enum Key {
145 ExpiresLabel,145 ExpiresLabel,
146 SignOutButton,146 SignOutButton,
147 RevokeButton,147 RevokeButton,
148+ AppsEmpty,
149+ ClientIdLabel,
150+ ActiveGrantsLabel,
151+ LastConnectedLabel,
148 152
149 // Admin panel nav and banners.153 // Admin panel nav and banners.
150 NavUsers,154 NavUsers,
@@ -228,6 +232,7 @@ pub enum Key {
228 SettingsSub,232 SettingsSub,
229 InviteDaysLabel,233 InviteDaysLabel,
230 SessionDaysLabel,234 SessionDaysLabel,
235+ MaxSessionsLabel,
231 PendingMinutesLabel,236 PendingMinutesLabel,
232 ResetMinutesLabel,237 ResetMinutesLabel,
233 LoginAttemptsLabel,238 LoginAttemptsLabel,
@@ -501,6 +506,14 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
501 (SignOutButton, Tr) => "Oturumu kapat",506 (SignOutButton, Tr) => "Oturumu kapat",
502 (RevokeButton, En) => "Revoke",507 (RevokeButton, En) => "Revoke",
503 (RevokeButton, Tr) => "İptal et",508 (RevokeButton, Tr) => "İptal et",
509+ (AppsEmpty, En) => "No apps are connected yet.",
510+ (AppsEmpty, Tr) => "Henüz bağlı uygulama yok.",
511+ (ClientIdLabel, En) => "Client ID",
512+ (ClientIdLabel, Tr) => "İstemci kimliği",
513+ (ActiveGrantsLabel, En) => "Active grants",
514+ (ActiveGrantsLabel, Tr) => "Etkin yetkiler",
515+ (LastConnectedLabel, En) => "Last connected",
516+ (LastConnectedLabel, Tr) => "Son bağlanma",
504 517
505 (NavUsers, En) => "Users",518 (NavUsers, En) => "Users",
506 (NavUsers, Tr) => "Kullanıcılar",519 (NavUsers, Tr) => "Kullanıcılar",
@@ -663,6 +676,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
663 (InviteDaysLabel, Tr) => "Davet bağlantısı, gün",676 (InviteDaysLabel, Tr) => "Davet bağlantısı, gün",
664 (SessionDaysLabel, En) => "Sign-in session, days",677 (SessionDaysLabel, En) => "Sign-in session, days",
665 (SessionDaysLabel, Tr) => "Oturum süresi, gün",678 (SessionDaysLabel, Tr) => "Oturum süresi, gün",
679+ (MaxSessionsLabel, En) => "Sign-in sessions per user",
680+ (MaxSessionsLabel, Tr) => "Kullanıcı başına oturum",
666 (PendingMinutesLabel, En) => "Second-factor window, minutes",681 (PendingMinutesLabel, En) => "Second-factor window, minutes",
667 (PendingMinutesLabel, Tr) => "İkinci faktör penceresi, dakika",682 (PendingMinutesLabel, Tr) => "İkinci faktör penceresi, dakika",
668 (ResetMinutesLabel, En) => "Reset link, minutes",683 (ResetMinutesLabel, En) => "Reset link, minutes",
crates/im-web/src/pages.rsmodified+51 -1
@@ -568,6 +568,43 @@ fn sessions_html(
568 rows568 rows
569 }569 }
570 570
571+/// The connected-apps card builds its rows as a string — one per app holding
572+/// an active grant — under the sessions card's own discipline: everything
573+/// app-controlled (name, client id) crosses `escape` before it reaches the
574+/// markup. The summary names the app and carries its active count; the
575+/// detail holds the client id and the last-connected stamp.
576+fn apps_html(apps: &[im_core::oidc::ConnectedApp], lang: Lang) -> String {
577+ let mut rows = String::new();
578+ for app in apps {
579+ rows.push_str(&format!(
580+ concat!(
581+ r#"<details class="session-item"><summary class="session-head">"#,
582+ r#"<span class="session-device">{}</span>"#,
583+ r#"<span class="session-ip mono">{}</span>"#,
584+ r#"</summary><div class="session-detail">"#,
585+ r#"<dl class="profile-fields">"#,
586+ r#"<div class="profile-field"><dt class="auth-label">{}</dt>"#,
587+ r#"<dd class="profile-value mono">{}</dd></div>"#,
588+ r#"<div class="profile-field"><dt class="auth-label">{}</dt>"#,
589+ r#"<dd class="profile-value">{}</dd></div>"#,
590+ r#"<div class="profile-field"><dt class="auth-label">{}</dt>"#,
591+ r#"<dd class="profile-value">{}</dd></div>"#,
592+ r#"</dl>"#,
593+ r#"</div></details>"#
594+ ),
595+ escape(&app.name),
596+ app.count,
597+ t(lang, Key::ClientIdLabel),
598+ escape(&app.client_id),
599+ t(lang, Key::ActiveGrantsLabel),
600+ app.count,
601+ t(lang, Key::LastConnectedLabel),
602+ stamp_min(app.last_at),
603+ ));
604+ }
605+ rows
606+}
607+
571 /// The signed-in landing. im is an auth service, not an app: this page is608 /// The signed-in landing. im is an auth service, not an app: this page is
572 /// the proof of session, the person's profile — photo and the counts their609 /// the proof of session, the person's profile — photo and the counts their
573 /// identity has earned — and the way out. izlek gives a profile its own610 /// identity has earned — and the way out. izlek gives a profile its own
@@ -586,11 +623,18 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result {
586 let sessions = im_core::sessions::list_sessions(&server::app(cx).store, &user.id).await?;623 let sessions = im_core::sessions::list_sessions(&server::app(cx).store, &user.id).await?;
587 let current = server::presented_session(cx).map(|token| im_core::accounts::hash_token(&token));624 let current = server::presented_session(cx).map(|token| im_core::accounts::hash_token(&token));
588 let sessions_html = sessions_html(&sessions, current.as_deref(), lang);625 let sessions_html = sessions_html(&sessions, current.as_deref(), lang);
626+ let apps = im_core::oidc::list_connected_apps(&server::app(cx).store, &user.id).await?;
627+ let apps_html = if apps.is_empty() {
628+ format!(r#"<div class="auth-sub">{}</div>"#, t(lang, Key::AppsEmpty))
629+ } else {
630+ apps_html(&apps, lang)
631+ };
589 // Same idiom as the admin panel's nav: one tab per section, the live one632 // Same idiom as the admin panel's nav: one tab per section, the live one
590 // underlined.633 // underlined.
591 let nav = [634 let nav = [
592 ("profile", t(lang, Key::ProfileLabel)),635 ("profile", t(lang, Key::ProfileLabel)),
593 ("sessions", t(lang, Key::SessionsTitle)),636 ("sessions", t(lang, Key::SessionsTitle)),
637+ ("apps", t(lang, Key::StatConnectedApps)),
594 ("preferences", t(lang, Key::PreferencesLabel)),638 ("preferences", t(lang, Key::PreferencesLabel)),
595 ("password", t(lang, Key::PasswordLabel)),639 ("password", t(lang, Key::PasswordLabel)),
596 ]640 ]
@@ -630,6 +674,12 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result {
630 </form>674 </form>
631 </div>675 </div>
632 }676 }
677+ if section == "apps" {
678+ <div class="auth-card">
679+ <div class="auth-title">(t(lang, Key::StatConnectedApps))</div>
680+ <div class="session-list">(topcoat::view::Unescaped::new_unchecked(apps_html))</div>
681+ </div>
682+ }
633 if section == "preferences" {683 if section == "preferences" {
634 <div class="auth-card">684 <div class="auth-card">
635 <div class="auth-title">(t(lang, Key::PreferencesLabel))</div>685 <div class="auth-title">(t(lang, Key::PreferencesLabel))</div>
@@ -704,7 +754,7 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result {
704 <div class="auth-sub">(t(lang, Key::AccountPasswordNote))</div>754 <div class="auth-sub">(t(lang, Key::AccountPasswordNote))</div>
705 </div>755 </div>
706 }756 }
707- if section != "sessions" && section != "preferences" && section != "password" {757+ if section != "sessions" && section != "preferences" && section != "password" && section != "apps" {
708 <div class="auth-card">758 <div class="auth-card">
709 <div class="profile-head">759 <div class="profile-head">
710 if user.has_photo {760 if user.has_photo {