diff --git a/config/im.toml b/config/im.toml index 1f5f44d..8fef96b 100644 --- a/config/im.toml +++ b/config/im.toml @@ -2,6 +2,24 @@ database = "im.db" listen = "127.0.0.1:7650" issuer = "http://127.0.0.1:7650" +# The sibling apps of the switcher and the landing's services home, in +# wordmark order. Prod uses https://.dizey.sh — deploy-side config, +# not committed here. +[[services]] +key = "in" +name = "Files" +url = "http://127.0.0.1:7655" + +[[services]] +key = "im" +name = "Account" +url = "http://127.0.0.1:7650" + +[[services]] +key = "iz" +name = "Board" +url = "http://127.0.0.1:7654" + # Without an [smtp] table the server runs in dev mode: invite links are # printed to stdout instead of mailed. # [smtp] diff --git a/crates/im-web/assets/main.css b/crates/im-web/assets/main.css index 96d820e..6d01f31 100644 --- a/crates/im-web/assets/main.css +++ b/crates/im-web/assets/main.css @@ -319,11 +319,76 @@ body:has(.auth-stage) > .auth-stage::-webkit-scrollbar { padding: 4px 0 10px; } +.service-trio { + display: flex; + justify-content: center; + align-items: baseline; + gap: 10px; + padding: 0 0 2px; +} + +.trio-mark { + font-family: var(--font-mono); + font-size: 13px; + font-weight: 500; + letter-spacing: 0.02em; + text-decoration: none; + color: var(--muted); +} +.trio-mark:hover { + color: var(--ink); +} +.trio-mark-on { + color: var(--ink); + box-shadow: inset 0 -2px 0 var(--accent); +} + +.trio-sep { + color: var(--muted-soft); +} + .landing-stage .auth-column { margin-top: max(24px, (100dvh - 640px) / 2); margin-bottom: 24px; } +.service-grid { + display: flex; + flex-wrap: wrap; + gap: 10px; +} + +.service-card { + flex: 1 1 140px; + display: flex; + align-items: center; + gap: 10px; + padding: 10px 14px; + border: 1px solid var(--border); + border-radius: var(--radius); + text-decoration: none; + color: inherit; +} +.service-card:hover { + border-color: var(--accent); + color: inherit; +} +.service-card-on { + border-color: var(--accent); + background: var(--accent-tint); +} + +.service-mark { + font-family: var(--font-mono); + font-size: 15px; + font-weight: 500; +} + +.service-name { + font-size: 13px; + color: var(--muted); +} + .auth-card { background: var(--surface); border: 1px solid var(--border); diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index e34fbd9..429676b 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -43,6 +43,47 @@ fn safe_back(raw: &str) -> &str { } } +/// Where a logout sends the browser. A local absolute path always +/// qualifies — the login `back` rule. An absolute URL qualifies when its +/// origin is exactly one of the configured services': the sibling app that +/// sent the browser here gets it handed back. A foreign origin — and +/// anything unparseable — is refused to the front door. +fn logout_target(raw: Option<&str>, services: &[crate::config::Service]) -> String { + let Some(raw) = raw else { + return "/".to_string(); + }; + if raw.starts_with('/') && !raw.starts_with("//") { + return raw.to_string(); + } + if let Some(origin) = url_origin(raw) { + if services + .iter() + .any(|s| url_origin(&s.url).is_some_and(|known| known == origin)) + { + return raw.to_string(); + } + } + "/".to_string() +} + +/// The `scheme://authority` of an absolute http(s) URL, lowercased — the +/// whole of what an origin match compares. `None` for anything else. +fn url_origin(raw: &str) -> Option { + let (scheme, rest) = raw.split_once("://")?; + if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") { + return None; + } + let authority = rest.split(['/', '?', '#']).next()?; + if authority.is_empty() { + return None; + } + Some(format!( + "{}://{}", + scheme.to_ascii_lowercase(), + authority.to_ascii_lowercase() + )) +} + /// 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 @@ -248,6 +289,14 @@ async fn enroll(cx: &Cx, Form(input): Form) -> Redirect { /// refresh token any app is still holding — see `sessions::revoke_session`. #[route(POST "/logout")] async fn logout(cx: &Cx) -> Redirect { + sign_out_everywhere(cx).await?; + see("/".to_string()) +} + +/// The shared half of both logouts: the central session dies — with it +/// every refresh token and app session bound to it — and the cookie is +/// tidied. Where the browser goes next is each route's own business. +async fn sign_out_everywhere(cx: &Cx) -> Result<()> { if let Some(token) = server::presented_session(cx) { let email = im_core::sessions::resolve_session(&server::app(cx).store, &token) .await? @@ -256,7 +305,25 @@ async fn logout(cx: &Cx) -> Redirect { server::log_event(cx, "logout", email.as_deref(), None).await; } server::clear_session_cookie(cx); - see("/".to_string()) + Ok(()) +} + +/// The RP-initiated exit: a sibling app has cleared its own cookie and +/// sent the browser here as a top-level navigation. `back` names the +/// return address, judged by [`logout_target`] — and the central session +/// dies whatever the answer is. +#[route(GET "/logout")] +async fn logout_return(cx: &Cx) -> Redirect { + let query = topcoat::router::request::uri(cx) + .query() + .unwrap_or("") + .to_string(); + let back = crate::pages::query_value(&query, "back"); + sign_out_everywhere(cx).await?; + see(logout_target( + back.as_deref(), + &server::app(cx).config.services, + )) } #[derive(Deserialize)] diff --git a/crates/im-web/src/config.rs b/crates/im-web/src/config.rs index b47504d..5310dcb 100644 --- a/crates/im-web/src/config.rs +++ b/crates/im-web/src/config.rs @@ -25,6 +25,24 @@ pub struct Config { /// The OIDC issuer — the public base URL every endpoint address and every /// `iss` claim derives from. pub issuer: String, + pub services: Vec, +} + +/// One sibling app in the switcher and on the landing's services home: +/// the wordmark `key` ("in", "im", "iz" — im's own), a human `name`, and +/// the absolute base `url` without a trailing slash. +#[derive(Clone)] +pub struct Service { + pub key: String, + pub name: String, + pub url: String, +} + +#[derive(Deserialize)] +struct RawService { + key: String, + name: String, + url: String, } #[derive(Deserialize)] @@ -32,6 +50,8 @@ struct Raw { database: Option, listen: Option, issuer: Option, + #[serde(default)] + services: Vec, } impl Config { @@ -52,6 +72,26 @@ impl Config { if !issuer.starts_with("http://") && !issuer.starts_with("https://") { return Err(format!("{PATH}: issuer {issuer:?} must be an http(s) URL")); } + let mut services = Vec::new(); + for service in raw.services { + if !matches!(service.key.as_str(), "in" | "im" | "iz") { + return Err(format!( + "{PATH}: services: key {:?} must be in, im, or iz", + service.key + )); + } + if !service.url.starts_with("http://") && !service.url.starts_with("https://") { + return Err(format!( + "{PATH}: services.{}.url {:?} must be an http(s) URL", + service.key, service.url + )); + } + services.push(Service { + key: service.key, + name: service.name, + url: service.url.trim_end_matches('/').to_string(), + }); + } Ok(Config { database: PathBuf::from(raw.database.unwrap_or_else(|| "im.db".to_string())), listen: raw @@ -60,6 +100,7 @@ impl Config { .parse() .map_err(|e| format!("{PATH}: listen: {e}"))?, issuer: issuer.trim_end_matches('/').to_string(), + services, }) } diff --git a/crates/im-web/src/directory.rs b/crates/im-web/src/directory.rs index d41879c..bf06d3a 100644 --- a/crates/im-web/src/directory.rs +++ b/crates/im-web/src/directory.rs @@ -53,21 +53,23 @@ mod tests { use im_core::accounts::{create_invite, create_user_from_invite}; use im_core::oidc::create_client; + use im_core::model::ClientId; use im_core::store::Store; use topcoat::cookie::RouterBuilderCookieExt as _; use topcoat::router::{Body, Router, RouterBuilderDiscoverExt as _, StatusCode, header, to_bytes}; use crate::config::Config; - use crate::server; + use crate::server::{self, SESSION_COOKIE}; struct Setup { router: Router, client_id: String, secret: String, + store: Arc, } async fn setup() -> Setup { - let store = Store::open(Path::new(":memory:")).await.unwrap(); + let store = Arc::new(Store::open(Path::new(":memory:")).await.unwrap()); let (client_id, secret) = create_client(&store, "tasks", vec!["http://app/callback".into()]) .await .unwrap(); @@ -94,11 +96,28 @@ mod tests { .unwrap(); let (live, _) = tokio::sync::broadcast::channel(64); let app = server::App { - store: Arc::new(store), + store: store.clone(), config: Config { database: ":memory:".into(), listen: "127.0.0.1:7650".parse().unwrap(), issuer: "http://127.0.0.1:7650".into(), + services: vec![ + crate::config::Service { + key: "in".into(), + name: "Files".into(), + url: "http://127.0.0.1:7655".into(), + }, + crate::config::Service { + key: "im".into(), + name: "Account".into(), + url: "http://127.0.0.1:7650".into(), + }, + crate::config::Service { + key: "iz".into(), + name: "Board".into(), + url: "http://127.0.0.1:7654".into(), + }, + ], }, live, }; @@ -111,6 +130,7 @@ mod tests { router, client_id: client_id.to_string(), secret: secret.expose().to_string(), + store, } } @@ -133,12 +153,60 @@ mod tests { (parts.status, String::from_utf8(bytes).unwrap()) } + /// A form post through the router, answered as (status, Location, body). + async fn post_form( + router: &Router, + uri: &str, + body: &str, + cookie: Option<&str>, + ) -> (StatusCode, Option, String) { + let mut builder = http::Request::builder() + .method(http::Method::POST) + .uri(uri) + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); + if let Some(cookie) = cookie { + builder = builder.header(header::COOKIE, cookie); + } + let response = router + .handle(builder.body(Body::from(body.to_string())).unwrap()) + .await; + let (parts, body) = response.into_parts(); + let location = parts + .headers + .get(header::LOCATION) + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec(); + (parts.status, location, String::from_utf8(bytes).unwrap()) + } + + /// A top-level GET (the RP-initiated logout's shape), same answer triple. + async fn get_location(router: &Router, uri: &str, cookie: &str) -> (StatusCode, Option) { + let response = router + .handle( + http::Request::builder() + .uri(uri) + .header(header::COOKIE, cookie) + .body(Body::empty()) + .unwrap(), + ) + .await; + let (parts, _) = response.into_parts(); + let location = parts + .headers + .get(header::LOCATION) + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + (parts.status, location) + } + #[tokio::test] async fn the_directory_names_every_non_disabled_user_with_its_admin_flag() { let Setup { router, client_id, secret, + .. } = setup().await; let (status, body) = get(&router, Some(basic(&client_id, &secret))).await; assert_eq!(status, StatusCode::OK); @@ -173,4 +241,87 @@ mod tests { let (status, _) = get(&router, Some(basic("no-such-client", "wrong"))).await; assert_eq!(status, StatusCode::UNAUTHORIZED); } + + #[tokio::test] + async fn logout_revokes_the_central_session_and_only_returns_known_origins() { + let Setup { + router, + client_id, + secret, + store, + } = setup().await; + let ada = im_core::accounts::user_by_email(&store, "ada@example.com") + .await + .unwrap() + .unwrap(); + + // The RP-initiated exit: `back` naming a configured service's own + // origin is honored verbatim — the sibling gets its browser back. + let one = im_core::sessions::create_session(&store, &ada.id, &Default::default()) + .await + .unwrap(); + let (status, location) = get_location( + &router, + "/logout?back=http%3A%2F%2F127.0.0.1%3A7655%2F", + &format!("{SESSION_COOKIE}={}", one.expose()), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!(location.as_deref(), Some("http://127.0.0.1:7655/")); + + // A live app session bound to a second central session introspects + // active — until a logout with a foreign `back` lands. The refusal + // itself goes to the front door, and the revocation still lands: + // the very next introspection is inactive. + let two = im_core::sessions::create_session(&store, &ada.id, &Default::default()) + .await + .unwrap(); + let app_token = im_core::oidc::issue_app_session( + &store, + &ada.id, + &ClientId::from(client_id.clone()), + &im_core::accounts::hash_token(two.expose()), + ) + .await + .unwrap(); + let probe = format!( + "token={}&client_id={client_id}&client_secret={secret}", + app_token.expose() + ); + let (status, _, body) = post_form(&router, "/introspect", &probe, None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + serde_json::from_str::(&body).unwrap()["active"], + true + ); + + let (status, location) = get_location( + &router, + "/logout?back=https%3A%2F%2Fevil.example%2F", + &format!("{SESSION_COOKIE}={}", two.expose()), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!(location.as_deref(), Some("/")); + let (status, _, body) = post_form(&router, "/introspect", &probe, None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + serde_json::from_str::(&body).unwrap()["active"], + false + ); + + // im's own form logout is untouched: front door, no `back` at all. + let three = im_core::sessions::create_session(&store, &ada.id, &Default::default()) + .await + .unwrap(); + let (status, location, _) = post_form( + &router, + "/logout", + "", + Some(&format!("{SESSION_COOKIE}={}", three.expose())), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!(location.as_deref(), Some("/")); + } } diff --git a/crates/im-web/src/i18n.rs b/crates/im-web/src/i18n.rs index 3d8fef5..62a6472 100644 --- a/crates/im-web/src/i18n.rs +++ b/crates/im-web/src/i18n.rs @@ -126,6 +126,7 @@ pub enum Key { StatActiveSessions, StatConnectedApps, SessionsTitle, + ServicesTitle, SignOutEverywhere, AdminPanelLink, ViewPhotoAria, @@ -447,6 +448,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (StatConnectedApps, Tr) => "Bağlı uygulamalar", (SessionsTitle, En) => "Sessions", (SessionsTitle, Tr) => "Oturumlar", + (ServicesTitle, En) => "Services", + (ServicesTitle, Tr) => "Hizmetler", (SignOutEverywhere, En) => "Sign out everywhere", (SignOutEverywhere, Tr) => "Her yerde oturumu kapat", (AdminPanelLink, En) => "Admin panel", diff --git a/crates/im-web/src/layout.rs b/crates/im-web/src/layout.rs index b2777bf..a100eac 100644 --- a/crates/im-web/src/layout.rs +++ b/crates/im-web/src/layout.rs @@ -8,6 +8,7 @@ use topcoat::context::Cx; use topcoat::view::view; use crate::i18n::{Key, Lang, lang_of, t}; +use crate::server; /// `style/main.scss`, compiled by `build.rs` into `assets/main.css`. const STYLE: Asset = asset!("assets/main.css"); @@ -23,6 +24,37 @@ pub async fn wordmark(cx: &Cx) -> Result { } } +/// The signed-in chrome's app trio: every configured service's wordmark, +/// middots between, the home one (`im`) inked and marked current, its +/// siblings plain links. A deployment that names no services renders +/// nothing — the single mark above stays the whole chrome. +pub async fn service_trio(cx: &Cx) -> Result { + let services = &server::app(cx).config.services; + let marks = (!services.is_empty()).then(|| { + services + .iter() + .map(|service| { + let key = crate::pages::escape(&service.key); + if service.key == "im" { + format!( + r#"{key}"# + ) + } else { + let url = crate::pages::escape(&service.url); + format!(r#"{key}"#) + } + }) + .collect::>() + .join(r#"·"#) + }); + view! { + cx => + if let Some(marks) = marks { + + } + } +} + /// The profile card's face: the photo when the account has one, the name's /// first letter on a quiet tile when it does not. The URL's stamp comes from /// `photo::PhotoStamps`, so a changed photo is a changed URL. diff --git a/crates/im-web/src/pages.rs b/crates/im-web/src/pages.rs index 9b2785a..f8dfaa0 100644 --- a/crates/im-web/src/pages.rs +++ b/crates/im-web/src/pages.rs @@ -12,7 +12,7 @@ use topcoat::router::{page, path_param, route}; use topcoat::view::view; use crate::i18n::{Key, Lang, lang_of, t}; -use crate::layout::{avatar, shell, wordmark}; +use crate::layout::{avatar, service_trio, shell, wordmark}; use crate::server::{self, PendingPurpose}; path_param!(token); @@ -429,7 +429,7 @@ async fn enroll(cx: &Cx) -> Result { /// 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 { +pub(crate) fn escape(raw: &str) -> String { raw.replace('&', "&") .replace('<', "<") .replace('>', ">") @@ -601,12 +601,42 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { ) }) .collect::(); + // The services home: one card per configured app — wordmark and name, + // the whole card the link. im's own card reads current. Above the + // profile sections: im is the account center, and its landing is the + // door to the rest. + let services_html = server::app(cx) + .config + .services + .iter() + .map(|service| { + let current = service.key == "im"; + let open = if current { + r#""#.to_string() + } else { + format!(r#""#, escape(&service.url)) + }; + format!( + r#"{open}{}{}"#, + escape(&service.key), + escape(&service.name), + if current { "span" } else { "a" }, + ) + }) + .collect::(); let stage = view! { cx =>
(wordmark(cx).await?) + (service_trio(cx).await?) + if !services_html.is_empty() { +
+
(t(lang, Key::ServicesTitle))
+
(topcoat::view::Unescaped::new_unchecked(services_html))
+
+ } if let Some(code) = ok {
(ok_text(&code, lang))
} diff --git a/crates/im-web/src/people.rs b/crates/im-web/src/people.rs index a445d41..6d9f81b 100644 --- a/crates/im-web/src/people.rs +++ b/crates/im-web/src/people.rs @@ -14,7 +14,7 @@ use topcoat::view::view; use im_core::accounts; use crate::i18n::{Key, lang_of, t}; -use crate::layout::{avatar, shell, wordmark}; +use crate::layout::{avatar, service_trio, shell, wordmark}; use crate::server; path_param!(user_id); @@ -40,6 +40,7 @@ async fn people_page(cx: &Cx) -> Result {
(wordmark(cx).await?) + (service_trio(cx).await?)
if person.has_photo { diff --git a/crates/im-web/src/photo.rs b/crates/im-web/src/photo.rs index 04c26a2..dc0501a 100644 --- a/crates/im-web/src/photo.rs +++ b/crates/im-web/src/photo.rs @@ -326,6 +326,7 @@ mod tests { database: ":memory:".into(), listen: "127.0.0.1:7650".parse().unwrap(), issuer: "http://127.0.0.1:7650".into(), + services: Vec::new(), }, live, }; diff --git a/style/main.scss b/style/main.scss index b105cbe..a40b0df 100644 --- a/style/main.scss +++ b/style/main.scss @@ -279,6 +279,35 @@ body:has(.auth-stage) { padding: 4px 0 10px; } +// The app trio under the signed-in wordmark: lower-case marks in the +// wordmark's mono, the home one inked, its siblings quiet links. The +// middots are part of the mark, not decoration between cards. +.service-trio { + display: flex; + justify-content: center; + align-items: baseline; + gap: 10px; + padding: 0 0 2px; +} + +.trio-mark { + font-family: var(--font-mono); + font-size: 13px; + font-weight: 500; + letter-spacing: 0.02em; + text-decoration: none; + color: var(--muted); + + &:hover { color: var(--ink); } + + &-on { + color: var(--ink); + box-shadow: inset 0 -2px 0 var(--accent); + } +} + +.trio-sep { color: var(--muted-soft); } + // The landing's column tops out where it would sit if the TALLEST section // were the one being centred: the wordmark and tab row hold that line on // every section, and shorter sections simply end sooner below it. 640px @@ -290,6 +319,48 @@ body:has(.auth-stage) { margin-bottom: 24px; } +// The landing's services home: one card per configured app — wordmark and +// name on one line, the whole card the link. im's own card reads current: +// accent border, tinted, no pointer. +.service-grid { + display: flex; + flex-wrap: wrap; + gap: 10px; +} + +.service-card { + flex: 1 1 140px; + display: flex; + align-items: center; + gap: 10px; + padding: 10px 14px; + border: 1px solid var(--border); + border-radius: var(--radius); + text-decoration: none; + color: inherit; + + &:hover { + border-color: var(--accent); + color: inherit; + } + + &-on { + border-color: var(--accent); + background: var(--accent-tint); + } +} + +.service-mark { + font-family: var(--font-mono); + font-size: 15px; + font-weight: 500; +} + +.service-name { + font-size: 13px; + color: var(--muted); +} + .auth-card {