diff --git a/config/in.toml b/config/in.toml index 2598329..d11aa8a 100644 --- a/config/in.toml +++ b/config/in.toml @@ -20,16 +20,70 @@ base_url = "" # created on boot. Not written here: it defaults to beside the database file, # and the boot completes this file with the value it resolved. +# The suite the signed-in chrome's switcher links to: one [[services]] +# table per app — `key` the word the switcher renders, `name` its hover +# label, `url` the address the link points at (scheme and host, no +# trailing slash). In names itself among them so the switcher can mark +# where the reader is. Production sets these on the deploy side as +# https://.dizey.sh; this committed copy carries only the +# development addresses. +# Where drive files, thumbnails and staged upload chunks live as files, created on boot. +storage = "/home/tahinli/Documents/Code/Rust/in/storage" + +[[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" + [oidc] # The provider that signs people in. Required: no default is guessed. -issuer = "" +issuer = "http://127.0.0.1:7650" # The client id In presents to the provider. Required. -client_id = "" +client_id = "in-dev-capture" # The client secret In presents to the provider. Required. Filled in only on # the machine that runs the server — the committed copy stays empty. -client_secret = "" +client_secret = "in-dev-secret" # Where the provider sends the browser back after sign-in. Not written here: # it defaults from `listen` on every boot, so moving the address never leaves # a stale callback behind. Set it only when the public address differs from # the bind address (a proxy in front, for instance). # redirect_uri = "http://127.0.0.1:7655/auth/callback" + +# Where the file bytes themselves live. With no [storage.r2] table, the +# bytes stay on local disk in the `storage` tree (files/ and thumbs/ beside +# the database) — the default, and the only shape every other key here +# describes. +# +# Setting [storage.r2] moves the file and thumbnail bytes into a Cloudflare +# R2 bucket. The database keeps every row, quota and piece of metadata — +# only the bytes move. `storage` still names the local tree either way: +# upload chunks stage there, then stream up to the bucket. +# +# [storage.r2] +# account_id — the R2 account id; the endpoint becomes +# https://.r2.cloudflarestorage.com +# bucket — the bucket the blobs land in, under files/ and thumbs/ — the same +# layout the local tree uses, so an rclone maps one onto the other. +# key_file — a path (resolved against this config directory) to a file with +# two lines: the R2 access key id on the first, the secret on the second. +# Create it readable only by the user the server runs as (0600); it is +# read once at boot and never logged: +# (umask 077 && printf '%s\n%s\n' '' '' > config/r2.keys) +# +# Absence is meaningful: no table, no bucket, local bytes. Nothing here is +# ever completed into the file for you. +# +# Migrating an existing deployment's bytes into the bucket — database and +# storage tree stay where they are; run once with the server stopped: +# rclone copy /files :r2,account=,key=:/files +# rclone copy /thumbs :r2,account=,key=:/thumbs diff --git a/crates/in-client/examples/mint.rs b/crates/in-client/examples/mint.rs index 247bbb1..4a3ec19 100644 --- a/crates/in-client/examples/mint.rs +++ b/crates/in-client/examples/mint.rs @@ -29,6 +29,7 @@ fn main() { redirect_uri: String::new(), cookie_name, cookie_key: key, + logout_back: String::new(), }; let exp = time::OffsetDateTime::now_utc() + time::Duration::days(1); println!("{}", in_client::mint_session_cookie(&config, &token, exp)); diff --git a/crates/in-client/src/lib.rs b/crates/in-client/src/lib.rs index 0a3cf3a..0423966 100644 --- a/crates/in-client/src/lib.rs +++ b/crates/in-client/src/lib.rs @@ -44,6 +44,13 @@ pub struct Config { pub cookie_name: String, /// 32 bytes, generated once per app and kept out of the repository. pub cookie_key: [u8; 32], + /// The app's public origin — `base_url` when the file sets one, else + /// the address bound, derived the way the app derives its public links. + /// After clearing the local cookie, `/auth/logout` walks the browser on + /// to im's `/logout?back={logout_back}/`, so the central session ends + /// and the person lands back at this app's front door. Empty is legal — + /// im catches a stray `back` on its own `/` — but a real app sets it. + pub logout_back: String, } /// The registered state: the config, one HTTP client, and the JWKS cache. @@ -534,12 +541,24 @@ async fn in_callback(cx: &Cx) -> Result { } } -/// Signs out of the app only. To end the central session too, post to im's -/// `/logout` — a link there is a silent re-login, by design. +/// Signs out of the app, then out of im: the local cookie is cleared +/// first — this app forgets the person even if the central hop never +/// lands — and the browser is sent on to im's `/logout` with this app's +/// public address as `back`. im revokes the central session and returns +/// them here. The hop is a top-level navigation (the user menu's sign-out +/// link carries `data-hard`), never a fetch. #[route(GET "/auth/logout")] async fn in_logout(cx: &Cx) -> Result { - clear_cookie(cx, &client(cx).config.cookie_name); - see(cx, "/") + let state = client(cx); + clear_cookie(cx, &state.config.cookie_name); + see( + cx, + &format!( + "{}/logout?back={}", + state.config.issuer, + urlencoded(&format!("{}/", state.config.logout_back)), + ), + ) } fn urlencoded(raw: &str) -> String { @@ -859,6 +878,7 @@ mod tests { redirect_uri: "http://app.test/auth/callback".into(), cookie_name: "in_session".into(), cookie_key: [7u8; 32], + logout_back: String::new(), }; assert_eq!(introspect_path(), "/introspect"); let exp = OffsetDateTime::now_utc() + time::Duration::hours(1); @@ -916,6 +936,27 @@ mod tests { ); } + #[tokio::test] + async fn logout_clears_the_cookie_and_walks_to_the_issuer() { + let router = test_router(test_config("http://im.test".into())); + let res = TestResponse::of( + router + .handle(get("/auth/logout", Some(&session_cookie("tok-1")))) + .await, + ) + .await; + assert_eq!(res.status, http::StatusCode::SEE_OTHER); + assert_eq!( + res.location.as_deref(), + Some("http://im.test/logout?back=http%3A%2F%2Fapp.test%2F"), + "{}", + res.text() + ); + // This app forgets the person on the very answer, whatever im then + // does with the central session. + assert!(res.clears_session()); + } + #[route(GET "/whoami")] async fn whoami(cx: &Cx) -> Result { match current_user(cx).await { @@ -932,6 +973,7 @@ mod tests { redirect_uri: "http://app.test/auth/callback".into(), cookie_name: "in_session".into(), cookie_key: [7u8; 32], + logout_back: "http://app.test".into(), } } diff --git a/crates/in-core/src/config.rs b/crates/in-core/src/config.rs index c4acaa0..23e7237 100644 --- a/crates/in-core/src/config.rs +++ b/crates/in-core/src/config.rs @@ -302,6 +302,10 @@ pub struct Config { /// banners that mint them — when the file sets one. `None` follows the /// address bound. pub base_url: Option, + /// The suite the signed-in chrome's switcher links to, from the + /// `[[services]]` tables. An empty list is a file silent about any + /// suite, and the chrome stays exactly as it has always been. + pub services: Vec, /// The OIDC provider In trusts. pub oidc: OidcConfig, /// Keys the file sets that nothing here reads, in the order the file @@ -478,6 +482,22 @@ impl Config { })?; } + // The suite the chrome's switcher links to. A silent list keeps the + // single-app chrome; an entry present must be whole, because a + // wordmark pointing nowhere is worse than none — and its url must + // be joinable to a link for the same reason `base_url` must. + let mut services = Vec::new(); + for (i, entry) in toml.services.unwrap_or_default().into_iter().enumerate() { + let key = value(entry.key) + .ok_or_else(|| service_error(i, "its key is missing or empty".into()))?; + let name = value(entry.name) + .ok_or_else(|| service_error(i, "its name is missing or empty".into()))?; + let url = value(entry.url) + .ok_or_else(|| service_error(i, "its url is missing or empty".into()))?; + Config::validate_base_url(&url).map_err(|why| service_error(i, why))?; + services.push(ServiceConfig { key, name, url }); + } + let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?; let issuer = value(oidc_toml.issuer).ok_or(ConfigError::Missing("oidc.issuer"))?; let client_id = value(oidc_toml.client_id).ok_or(ConfigError::Missing("oidc.client_id"))?; @@ -501,6 +521,7 @@ impl Config { purge_after_days, default_quota_bytes, base_url, + services, oidc: OidcConfig { issuer, client_id, @@ -581,6 +602,15 @@ fn listen_url_of(listen: &SocketAddr) -> String { } } +/// The boot error for a `[[services]]` entry that is not whole. Entries are +/// numbered from one, so the message names the offender a human can find. +fn service_error(index: usize, why: String) -> ConfigError { + ConfigError::Invalid { + key: "services", + why: format!("entry {}: {why}", index + 1), + } +} + impl Config { /// Whether a base URL is an origin a public link can be built on: an /// `http` or `https` scheme and no trailing slash. Shared by the file's @@ -917,6 +947,78 @@ redirect_uri = "https://files.example.com/auth/callback" )); } + /// The switcher is off until the file names a suite: a `[[services]]`-less + /// file is the chrome as it has always been, no half-rendered trio. + #[test] + fn a_file_without_services_leaves_the_switcher_off() { + let scratch = Scratch::new(); + scratch.write(FULL); + let config = scratch.load().unwrap(); + assert!(config.services.is_empty()); + } + + #[test] + fn services_parse_in_the_order_the_file_gives_them() { + let scratch = Scratch::new(); + scratch.write(&FULL.replace( + "[oidc]", + "[[services]]\n\ + key = \"in\"\n\ + name = \"Files\"\n\ + url = \"https://files.example.com\"\n\ + \n\ + [[services]]\n\ + key = \"im\"\n\ + name = \"Account\"\n\ + url = \"https://id.example.com\"\n\ + [oidc]", + )); + let config = scratch.load().unwrap(); + assert_eq!( + config.services, + vec![ + ServiceConfig { + key: "in".into(), + name: "Files".into(), + url: "https://files.example.com".into(), + }, + ServiceConfig { + key: "im".into(), + name: "Account".into(), + url: "https://id.example.com".into(), + }, + ] + ); + } + + #[test] + fn a_service_url_without_a_scheme_is_refused() { + let scratch = Scratch::new(); + scratch.write(&FULL.replace( + "[oidc]", + "[[services]]\nkey = \"im\"\nname = \"Account\"\nurl = \"id.example.com\"\n[oidc]", + )); + assert!(matches!( + scratch.load().unwrap_err(), + ConfigError::Invalid { key: "services", .. } + )); + } + + #[test] + fn an_incomplete_service_entry_names_the_offender() { + let scratch = Scratch::new(); + scratch.write(&FULL.replace( + "[oidc]", + "[[services]]\nkey = \"im\"\nname = \"\"\nurl = \"https://id.example.com\"\n[oidc]", + )); + let err = scratch.load().unwrap_err(); + assert!(matches!( + err, + ConfigError::Invalid { key: "services", .. } + )); + assert!(err.to_string().contains("entry 1"), "{err}"); + } + #[test] fn zero_live_seconds_is_refused() { let scratch = Scratch::new(); diff --git a/crates/in-core/src/lib.rs b/crates/in-core/src/lib.rs index 771c786..8e27f17 100644 --- a/crates/in-core/src/lib.rs +++ b/crates/in-core/src/lib.rs @@ -20,7 +20,7 @@ pub use store::{ }; #[cfg(feature = "server")] -pub use config::{Config, ConfigError, OidcConfig}; +pub use config::{Config, ConfigError, OidcConfig, ServiceConfig}; #[cfg(feature = "server")] pub use live::{Change, Topic, next_seq}; #[cfg(feature = "server")] diff --git a/crates/in-web/src/layout.rs b/crates/in-web/src/layout.rs index 8de245c..96151c1 100644 --- a/crates/in-web/src/layout.rs +++ b/crates/in-web/src/layout.rs @@ -221,14 +221,51 @@ pub async fn topbar_nav(cx: &Cx, active: NavPage, lang: Lang) -> Result { } } -/// The signed-in chrome: the monogram, the page nav, the identity menu. -/// Wave-2 pages render their content under this. +/// This app's key in the `[[services]]` list: the entry matching it is the +/// one marked as where the reader already is. +const SELF_KEY: &str = "in"; + +/// The topbar's suite switcher: every `[[services]]` entry as its wordmark, +/// beside the page nav, the current one marked. Rendered only when the file +/// names a suite — a file silent about the others keeps the chrome exactly +/// as it has always been. The links point at the services' own addresses, +/// so the cross-origin ones navigate the browser natively; this app's entry +/// lands where a soft-nav swap would have gone anyway. +async fn app_switcher(cx: &Cx) -> Result { + let empty = app(cx).config.services.is_empty(); + view! { + cx => + if !empty { + + + } + } +} + +/// The signed-in chrome: the monogram, the page nav, the suite switcher, +/// the identity menu. Wave-2 pages render their content under this. pub async fn topbar(cx: &Cx, active: NavPage, user: &User, lang: Lang) -> Result { view! { cx =>
(mark(cx).await?) (topbar_nav(cx, active, lang).await?) + (app_switcher(cx).await?) (user_menu(cx, user, lang).await?)
(avatar_script(cx).await?) diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs index db52526..858d299 100644 --- a/crates/in-web/src/main.rs +++ b/crates/in-web/src/main.rs @@ -207,6 +207,9 @@ async fn main() { redirect_uri: config.oidc.redirect_uri.clone(), cookie_name: "in_session".to_string(), cookie_key, + // Where im's `/logout` sends the browser after the central + // sign-out: the same origin public links carry. + logout_back: config.public_origin(), }; // Told when the process is stopping, so the live streams end instead of diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs index 01c1afc..a4019ab 100644 --- a/crates/in-web/tests/http.rs +++ b/crates/in-web/tests/http.rs @@ -9,14 +9,13 @@ //! //! New HTTP tests belong in this file rather than a new `tests/*.rs`: one //! test binary links and runs once. - +use in_core::{Config, OidcConfig, ServiceConfig}; use std::collections::HashMap; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use http::{HeaderValue, Request, StatusCode, header}; use in_core::store::{ShareKind, Store, TursoStore}; -use in_core::{Config, OidcConfig}; use in_web::server::App; use topcoat::asset::{AssetBundle, RouterBuilderAssetExt}; use topcoat::cookie::RouterBuilderCookieExt; @@ -316,12 +315,13 @@ struct TestApp { impl TestApp { async fn build() -> Self { - Self::build_with(None).await + Self::build_with(None, Vec::new()).await } /// The same workspace with a config `base_url` set — the key that - /// decides where the public links are told to point. - async fn build_with(base_url: Option<&str>) -> Self { + /// decides where the public links are told to point — and optional + /// `[[services]]` entries, the suite the topbar's switcher links to. + async fn build_with(base_url: Option<&str>, services: Vec) -> Self { let dir = std::env::temp_dir().join(format!("in-http-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let db = dir.join("in.db"); @@ -339,6 +339,7 @@ impl TestApp { redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), cookie_name: "in_session".to_string(), cookie_key: [7u8; 32], + logout_back: "http://127.0.0.1:7655".to_string(), }; let config = Config { database: db.to_str().unwrap().to_string(), @@ -348,6 +349,7 @@ impl TestApp { purge_after_days: 30, default_quota_bytes: 10 * 1024 * 1024 * 1024, base_url: base_url.map(str::to_string), + services, r2: None, oidc: OidcConfig { issuer: fake.url(), @@ -2693,6 +2695,55 @@ async fn topbar_nav_has_no_search_link() { assert!(!nav.contains("Search"), "search leaked into the nav: {nav}"); } +#[tokio::test] +async fn the_suite_switcher_renders_when_services_are_set() { + // No [[services]]: no switcher — the chrome as it always was. + let bare = TestApp::build().await; + let cookie = bare + .sign_in("sub-switch0", "switch0@in.test", "Switch0") + .await; + let page = bare.get("/drive", Some(&cookie)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!(!page.text().contains("app-switcher"), "{}", page.text()); + + let app = TestApp::build_with( + None, + vec![ + ServiceConfig { + key: "in".into(), + name: "Files".into(), + url: "https://files.example.com".into(), + }, + ServiceConfig { + key: "im".into(), + name: "Account".into(), + url: "https://id.example.com".into(), + }, + ServiceConfig { + key: "iz".into(), + name: "Board".into(), + url: "https://board.example.com".into(), + }, + ], + ) + .await; + let cookie = app.sign_in("sub-switch", "switch@in.test", "Switch").await; + let page = app.get("/drive", Some(&cookie)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + let body = page.text(); + let nav_start = body.find("app-switcher").expect("no switcher"); + let nav_end = body[nav_start..] + .find("") + .expect("switcher never closes"); + let nav = &body[nav_start..nav_start + nav_end]; + assert!(nav.contains("href=\"https://files.example.com/\""), "{nav}"); + assert!(nav.contains("href=\"https://id.example.com/\""), "{nav}"); + assert!(nav.contains("href=\"https://board.example.com/\""), "{nav}"); + assert!(nav.contains("title=\"Files\""), "{nav}"); + // Exactly the app the reader is already in is marked. + assert_eq!(nav.matches("aria-current").count(), 1, "{nav}"); +} + // -- settings --------------------------------------------------------------- #[tokio::test] @@ -2791,7 +2842,7 @@ async fn settings_quota_and_disable_guards() { /// `base_url`. #[tokio::test] async fn share_links_carry_the_configured_base_url() { - let app = TestApp::build_with(Some("https://files.example.com")).await; + let app = TestApp::build_with(Some("https://files.example.com"), Vec::new()).await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "notes.txt", b"hello in").await; @@ -3118,7 +3169,7 @@ async fn server_address_setting_drives_share_links() { /// file sets one: the setting wins only while it is non-empty. #[tokio::test] async fn cleared_setting_falls_back_to_the_configured_base_url() { - let app = TestApp::build_with(Some("https://cfg.example.com")).await; + let app = TestApp::build_with(Some("https://cfg.example.com"), Vec::new()).await; let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; let owner = owner_of(&app, "sub-admin").await; let file = file_id(&app, &owner, "notes.txt", b"hello in").await; diff --git a/style/main.scss b/style/main.scss index c1e8dde..cbc2168 100644 --- a/style/main.scss +++ b/style/main.scss @@ -479,6 +479,34 @@ a { } } +// The suite switcher: the other apps of the family, as their wordmarks, +// beside the page nav. Rendered only when `[[services]]` is set; the app +// the reader is already in is marked the way the page nav marks itself. +.app-switcher { + display: flex; + align-items: center; + gap: 14px; + // The trio keeps its width at every width: the page nav beside it is the + // region that pans under the finger, this never squishes. + flex: none; + + &-mark { + font-family: var(--font-mono); + font-size: 13px; + font-weight: 500; + letter-spacing: 0.02em; + color: var(--muted); + text-decoration: none; + + &:hover { color: var(--ink); } + } + // The current app, spelled out — `&` stays at the head of a compound + // selector here, so the pair of classes cannot ride the ampersand. + .app-switcher-mark.app-switcher-here { + color: var(--ink); + box-shadow: inset 0 -2px 0 var(--ink); + } +} .scaffold-note { margin: 24px; padding: 20px 24px; @@ -4318,6 +4346,8 @@ input[type="radio"] { &::-webkit-scrollbar { display: none; } } + .app-switcher { gap: 10px; } + // The avatar says who is signed in at this width; the name is the menu's. .user-menu-trigger-name { display: none; } @@ -4330,6 +4360,8 @@ input[type="radio"] { } .topbar-nav-links { gap: 10px; } + + .app-switcher { gap: 8px; } } // -- board -----------------------------------------------------------------