From cc56357dc26fb5fce2cf39e09bb460bdeaba76cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 8 Sep 2026 01:40:01 +0300 Subject: [PATCH] =?UTF-8?q?the=20family=20list=20moves=20into=20the=20hous?= =?UTF-8?q?e:=20a=20services=20table=20owns=20the=20wordmarks,=20seeded=20?= =?UTF-8?q?once=20from=20the=20config's=20[[services]]=20on=20first=20boot?= =?UTF-8?q?=20and=20never=20again,=20edited=20instead=20from=20the=20landi?= =?UTF-8?q?ng's=20Services=20card=20where=20an=20admin=20adds,=20renames,?= =?UTF-8?q?=20re-points,=20reorders=20or=20removes=20entries=20=E2=80=94?= =?UTF-8?q?=20members=20see=20the=20same=20card=20read-only;=20a=20new=20G?= =?UTF-8?q?ET=20/family=20answers=20the=20list=20to=20registered=20apps=20?= =?UTF-8?q?behind=20the=20same=20basic=20client=20pair=20as=20the=20direct?= =?UTF-8?q?ory,=20the=20trio=20and=20the=20cards=20render=20the=20table,?= =?UTF-8?q?=20and=20the=20logout=20back-door=20now=20trusts=20only=20origi?= =?UTF-8?q?ns=20the=20table=20knows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/im-core/src/lib.rs | 2 + crates/im-core/src/services.rs | 397 +++++++++++++++++++++++++++++++++ crates/im-core/src/store.rs | 10 + crates/im-web/src/auth.rs | 125 ++++++++++- crates/im-web/src/directory.rs | 332 +++++++++++++++++++++++++-- crates/im-web/src/i18n.rs | 19 ++ crates/im-web/src/layout.rs | 9 +- crates/im-web/src/main.rs | 28 +++ crates/im-web/src/pages.rs | 77 ++++++- 9 files changed, 964 insertions(+), 35 deletions(-) create mode 100644 crates/im-core/src/services.rs diff --git a/crates/im-core/src/lib.rs b/crates/im-core/src/lib.rs index 50f6c53..fedac8f 100644 --- a/crates/im-core/src/lib.rs +++ b/crates/im-core/src/lib.rs @@ -16,6 +16,8 @@ pub mod oidc; #[cfg(feature = "server")] pub mod photos; #[cfg(feature = "server")] +pub mod services; +#[cfg(feature = "server")] mod secret; #[cfg(feature = "server")] pub mod sessions; diff --git a/crates/im-core/src/services.rs b/crates/im-core/src/services.rs new file mode 100644 index 0000000..b3d3f15 --- /dev/null +++ b/crates/im-core/src/services.rs @@ -0,0 +1,397 @@ +//! The family: the services every topbar shows as wordmarks and the +//! landing's services home. The list lives in the database and the admin +//! panel owns it — seeded once from the config's `[[services]]` on first +//! boot, edited from the landing (add, rename, reorder, remove), and served +//! to the sibling apps over `GET /family`, which each mirrors into its own +//! database. + +use serde::Serialize; + +use crate::store::{self, Result, Store, StoreError, backend}; + +/// One service of the family: the wordmark `key` ("in", "im", "iz" — or a +/// later sibling; the key rules are mechanical, not a fixed trio), the +/// human `name`, and the absolute base `url` without a trailing slash. +/// `position` is the stored order and never leaves this module — readers +/// get the list already ordered. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Service { + pub key: String, + pub name: String, + pub url: String, +} + +/// The form-level rules every stored row obeys: a key of lowercase ASCII +/// letters, digits, and dashes; a non-empty name; an absolute http(s) URL. +/// Returns the reason a value is refused — the panel shows it as its one +/// generic refusal, the exact words stay a store matter. +pub fn validate(key: &str, name: &str, url: &str) -> std::result::Result<(), String> { + if key.is_empty() + || !key + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') + { + return Err(format!( + "key {key:?} must be lowercase letters, digits, or dashes" + )); + } + if name.trim().is_empty() { + return Err("name must not be empty".to_string()); + } + let trimmed = url.trim_end_matches('/'); + let Some(rest) = trimmed + .strip_prefix("http://") + .or_else(|| trimmed.strip_prefix("https://")) + else { + return Err(format!("url {url:?} must be an http(s) URL")); + }; + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + if authority.is_empty() { + return Err(format!("url {url:?} must name a host")); + } + if trimmed + .chars() + .any(|c| c.is_whitespace() || c.is_control()) + { + return Err(format!( + "url {url:?} must not carry spaces or control characters" + )); + } + Ok(()) +} + +/// The one doorway every write passes: [`validate`], with the URL in its +/// stored form — no trailing slash. +fn checked(service: &Service) -> Result { + validate(&service.key, &service.name, &service.url).map_err(StoreError::Invalid)?; + Ok(service.url.trim_end_matches('/').to_string()) +} + +/// Every service, in the stored order — the one order the trio, the landing +/// cards, and `/family` all render in. +pub async fn list(store: &Store) -> Result> { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT key, name, url FROM services ORDER BY position, key", + (), + ) + .await + .map_err(backend)?; + let mut services = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + services.push(Service { + key: store::text(&row, 0)?, + name: store::text(&row, 1)?, + url: store::text(&row, 2)?, + }); + } + Ok(services) +} + +/// Appends a service at the end of the family. A key already on the list is +/// refused — the add form is the only writer, and a silent overwrite would +/// surprise it. +pub async fn add(store: &Store, service: &Service) -> Result<()> { + let url = checked(service)?; + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT 1 FROM services WHERE key = ?1", + turso::params![service.key.as_str()], + ) + .await + .map_err(backend)?; + let taken = rows.next().await.map_err(backend)?.is_some(); + drop(rows); + if taken { + return Err(StoreError::Invalid(format!( + "service key {:?} is already on the list", + service.key + ))); + } + conn.execute( + "INSERT INTO services (key, name, url, position) \ + VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(position), -1) + 1 FROM services))", + turso::params![service.key.as_str(), service.name.trim(), url.as_str()], + ) + .await + .map_err(backend)?; + Ok(()) +} + +/// Rewrites a service's name and address. The key travels in the form's +/// hidden field and is not editable; a key not on the list is refused, so a +/// form posted against a since-removed row cannot resurrect it. +pub async fn edit(store: &Store, key: &str, name: &str, url: &str) -> Result<()> { + validate(key, name, url).map_err(StoreError::Invalid)?; + let url = url.trim_end_matches('/'); + let conn = store.conn.lock().await; + let updated = conn + .execute( + "UPDATE services SET name = ?2, url = ?3 WHERE key = ?1", + turso::params![key, name.trim(), url], + ) + .await + .map_err(backend)?; + if updated == 0 { + return Err(StoreError::Invalid(format!("no service keyed {key:?}"))); + } + Ok(()) +} + +/// Takes a service off the list and closes the gap: every later row slides +/// down one, so positions stay contiguous and the next add appends cleanly. +/// A key not on the list is a no-op — the panel only offers existing rows. +pub async fn remove(store: &Store, key: &str) -> Result<()> { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT position FROM services WHERE key = ?1", + turso::params![key], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(()); + }; + let position = store::int(&row, 0)?; + drop(rows); + conn.execute( + "DELETE FROM services WHERE key = ?1", + turso::params![key], + ) + .await + .map_err(backend)?; + conn.execute( + "UPDATE services SET position = position - 1 WHERE position > ?1", + turso::params![position], + ) + .await + .map_err(backend)?; + Ok(()) +} + +/// Swaps a service one slot toward the front (`up`) or the back. An edge +/// row has no neighbor in that direction and the list is left alone. +pub async fn move_service(store: &Store, key: &str, up: bool) -> Result<()> { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT position FROM services WHERE key = ?1", + turso::params![key], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(()); + }; + let position = store::int(&row, 0)?; + drop(rows); + let mut neighbor = if up { + conn.query( + "SELECT key, position FROM services WHERE position < ?1 \ + ORDER BY position DESC LIMIT 1", + turso::params![position], + ) + .await + .map_err(backend)? + } else { + conn.query( + "SELECT key, position FROM services WHERE position > ?1 \ + ORDER BY position ASC LIMIT 1", + turso::params![position], + ) + .await + .map_err(backend)? + }; + let Some(row) = neighbor.next().await.map_err(backend)? else { + return Ok(()); + }; + let other_key = store::text(&row, 0)?; + let other_position = store::int(&row, 1)?; + drop(neighbor); + conn.execute( + "UPDATE services SET position = ?1 WHERE key = ?2", + turso::params![other_position, key], + ) + .await + .map_err(backend)?; + conn.execute( + "UPDATE services SET position = ?1 WHERE key = ?2", + turso::params![position, other_key], + ) + .await + .map_err(backend)?; + Ok(()) +} + +/// The one-time seed: a database with no services yet takes the config's +/// list as the starting rows, in the order the file names them. After that +/// the panel owns the list and the same config is ignored — the `false` +/// return tells the boot it did nothing. +pub async fn seed_from(store: &Store, seed: &[Service]) -> Result { + if !list(store).await?.is_empty() { + return Ok(false); + } + let conn = store.conn.lock().await; + for (position, service) in seed.iter().enumerate() { + let url = checked(service)?; + conn.execute( + "INSERT OR IGNORE INTO services (key, name, url, position) \ + VALUES (?1, ?2, ?3, ?4)", + turso::params![ + service.key.as_str(), + service.name.trim(), + url.as_str(), + position as i64 + ], + ) + .await + .map_err(backend)?; + } + Ok(true) +} + +#[cfg(test)] +mod tests { + use std::path::Path; + + use super::*; + use crate::store::StoreError; + + async fn store() -> Store { + Store::open(Path::new(":memory:")).await.unwrap() + } + + fn service(key: &str, name: &str, url: &str) -> Service { + Service { + key: key.to_string(), + name: name.to_string(), + url: url.to_string(), + } + } + + async fn keys(store: &Store) -> Vec { + list(store).await.unwrap().into_iter().map(|s| s.key).collect() + } + + #[tokio::test] + async fn the_seed_fills_an_empty_table_once_and_then_hands_over() { + let store = store().await; + let seed = vec![ + service("in", "Files", "http://127.0.0.1:7655/"), + service("im", "Account", "http://127.0.0.1:7650"), + ]; + assert!(seed_from(&store, &seed).await.unwrap()); + // A trailing slash in the file is not in the table: the stored form + // is slash-free, everywhere. + assert_eq!(list(&store).await.unwrap()[0].url, "http://127.0.0.1:7655"); + // The panel renamed the first entry; a re-boot with the same config + // must not bring the old name back. + edit(&store, "in", "Renamed", "http://127.0.0.1:7655") + .await + .unwrap(); + assert!(!seed_from(&store, &seed).await.unwrap()); + assert_eq!(list(&store).await.unwrap()[0].name, "Renamed"); + } + + #[tokio::test] + async fn add_appends_edit_rewrites_and_a_taken_key_is_refused() { + let store = store().await; + seed_from( + &store, + &[service("im", "Account", "http://127.0.0.1:7650")], + ) + .await + .unwrap(); + add(&store, &service("in", "Files", "http://127.0.0.1:7655")) + .await + .unwrap(); + add(&store, &service("in", "Again", "http://elsewhere/")) + .await + .err() + .unwrap_or_else(|| panic!("a taken key must be refused")); + // The refused add changed nothing. + assert_eq!(keys(&store).await, vec!["im".to_string(), "in".to_string()]); + edit(&store, "in", "Dosyalar", "https://in.example") + .await + .unwrap(); + let services = list(&store).await.unwrap(); + assert_eq!(services[1].name, "Dosyalar"); + assert_eq!(services[1].url, "https://in.example"); + // A form posted against a since-removed key cannot resurrect it. + remove(&store, "in").await.unwrap(); + assert!(matches!( + edit(&store, "in", "Zombie", "https://in.example").await, + Err(StoreError::Invalid(_)) + )); + assert_eq!(keys(&store).await, vec!["im".to_string()]); + } + + #[tokio::test] + async fn moving_swaps_with_the_neighbor_and_edges_stay_put() { + let store = store().await; + seed_from( + &store, + &[ + service("in", "Files", "http://127.0.0.1:7655"), + service("im", "Account", "http://127.0.0.1:7650"), + service("iz", "Board", "http://127.0.0.1:7654"), + ], + ) + .await + .unwrap(); + move_service(&store, "iz", true).await.unwrap(); + assert_eq!( + keys(&store).await, + vec!["in".to_string(), "iz".to_string(), "im".to_string()] + ); + // The front edge has nothing above it; the list does not move. + move_service(&store, "in", true).await.unwrap(); + assert_eq!( + keys(&store).await, + vec!["in".to_string(), "iz".to_string(), "im".to_string()] + ); + move_service(&store, "in", false).await.unwrap(); + assert_eq!( + keys(&store).await, + vec!["iz".to_string(), "in".to_string(), "im".to_string()] + ); + } + + #[tokio::test] + async fn removing_closes_the_gap_so_the_next_add_appends_last() { + let store = store().await; + seed_from( + &store, + &[ + service("in", "Files", "http://127.0.0.1:7655"), + service("im", "Account", "http://127.0.0.1:7650"), + service("iz", "Board", "http://127.0.0.1:7654"), + ], + ) + .await + .unwrap(); + remove(&store, "im").await.unwrap(); + remove(&store, "im").await.unwrap(); // already gone: a no-op + add(&store, &service("wiki", "Wiki", "http://wiki")).await.unwrap(); + assert_eq!( + keys(&store).await, + vec!["in".to_string(), "iz".to_string(), "wiki".to_string()] + ); + } + + #[tokio::test] + async fn the_value_rules_refuse_garbage_before_the_database_sees_it() { + assert!(validate("in", "Files", "http://in.example").is_ok()); + assert!(validate("In", "Files", "http://in.example").is_err(), "uppercase key"); + assert!(validate("in!", "Files", "http://in.example").is_err(), "punctuated key"); + assert!(validate("in", " ", "http://in.example").is_err(), "blank name"); + assert!(validate("in", "Files", "ftp://in.example").is_err(), "non-http url"); + assert!(validate("in", "Files", "http://").is_err(), "hostless url"); + assert!(validate("in", "Files", "http://in.example/path x").is_err(), "space in url"); + // A trailing slash is not garbage — it is normalized away. + assert!(validate("in", "Files", "http://in.example/").is_ok()); + } +} diff --git a/crates/im-core/src/store.rs b/crates/im-core/src/store.rs index 4d66bb4..516793e 100644 --- a/crates/im-core/src/store.rs +++ b/crates/im-core/src/store.rs @@ -17,6 +17,10 @@ pub enum StoreError { Corrupt(String), #[error("io: {0}")] Io(#[from] std::io::Error), + /// A value a panel form offered is against the stored rules — the + /// caller turns it into the page's refusal, never a database problem. + #[error("{0}")] + Invalid(String), } pub type Result = std::result::Result; @@ -127,6 +131,12 @@ CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL ); +CREATE TABLE IF NOT EXISTS services ( + key TEXT PRIMARY KEY, + name TEXT NOT NULL, + url TEXT NOT NULL, + position INTEGER NOT NULL +); "; /// One database handle with the at-rest key beside it. Turso is a diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index 429676b..56fc56e 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -45,10 +45,10 @@ 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 +/// origin is exactly one of the family's stored 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 { +fn logout_target(raw: Option<&str>, services: &[im_core::services::Service]) -> String { let Some(raw) = raw else { return "/".to_string(); }; @@ -320,10 +320,121 @@ async fn logout_return(cx: &Cx) -> Redirect { .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, - )) + let services = im_core::services::list(&server::app(cx).store).await?; + see(logout_target(back.as_deref(), &services)) +} + +// --------------------------------------------------------------------------- +// The landing Services card's writes +// --------------------------------------------------------------------------- + +/// The admin behind this request, or `None` — the handlers below send a +/// non-admin to the front door, where the card carries no forms anyway. +/// The admin panel's `require_admin` is the same gate with the same answer. +async fn landing_admin(cx: &Cx) -> Option { + match server::current_user(cx).await { + Some(user) if user.admin => Some(user), + _ => None, + } +} + +/// One user of the card's forms: key, name, address. The add form fills all +/// three; the edit form carries the key in its hidden field. +#[derive(Deserialize)] +pub struct ServiceForm { + key: String, + name: String, + url: String, +} + +/// The landing answer to a services write: back to the card with the good +/// news, or with the card's one refusal when the store said the value is +/// against the rules. Anything else is a real failure and travels as one. +fn service_outcome(outcome: im_core::store::Result<()>) -> Redirect { + match outcome { + Ok(()) => see("/?ok=services".to_string()), + Err(im_core::store::StoreError::Invalid(_)) => see("/?error=bad_service".to_string()), + Err(e) => Err(e.into()), + } +} + +#[route(POST "/services/add")] +async fn service_add(cx: &Cx, Form(input): Form) -> Redirect { + let Some(me) = landing_admin(cx).await else { + return see("/".to_string()); + }; + let outcome = im_core::services::add( + &server::app(cx).store, + &im_core::services::Service { + key: input.key, + name: input.name, + url: input.url, + }, + ) + .await; + if outcome.is_ok() { + server::log_event(cx, "services_updated", Some(&me.email), None).await; + } + service_outcome(outcome) +} + +#[route(POST "/services/edit")] +async fn service_edit(cx: &Cx, Form(input): Form) -> Redirect { + let Some(me) = landing_admin(cx).await else { + return see("/".to_string()); + }; + let outcome = im_core::services::edit( + &server::app(cx).store, + &input.key, + &input.name, + &input.url, + ) + .await; + if outcome.is_ok() { + server::log_event(cx, "services_updated", Some(&me.email), None).await; + } + service_outcome(outcome) +} + +#[derive(Deserialize)] +struct ServiceKeyForm { + key: String, +} + +#[route(POST "/services/remove")] +async fn service_remove(cx: &Cx, Form(input): Form) -> Redirect { + let Some(me) = landing_admin(cx).await else { + return see("/".to_string()); + }; + let outcome = im_core::services::remove(&server::app(cx).store, &input.key).await; + if outcome.is_ok() { + server::log_event(cx, "services_updated", Some(&me.email), None).await; + } + service_outcome(outcome) +} + +#[derive(Deserialize)] +struct ServiceMoveForm { + key: String, + dir: String, +} + +/// Up or down one slot; anything else in `dir` is the card's refusal. +#[route(POST "/services/move")] +async fn service_move(cx: &Cx, Form(input): Form) -> Redirect { + let Some(me) = landing_admin(cx).await else { + return see("/".to_string()); + }; + let up = match input.dir.as_str() { + "up" => true, + "down" => false, + _ => return see("/?error=bad_service".to_string()), + }; + let outcome = im_core::services::move_service(&server::app(cx).store, &input.key, up).await; + if outcome.is_ok() { + server::log_event(cx, "services_updated", Some(&me.email), None).await; + } + service_outcome(outcome) } #[derive(Deserialize)] diff --git a/crates/im-web/src/directory.rs b/crates/im-web/src/directory.rs index bf06d3a..4b939ed 100644 --- a/crates/im-web/src/directory.rs +++ b/crates/im-web/src/directory.rs @@ -46,6 +46,22 @@ async fn directory(cx: &Cx) -> topcoat::Result topcoat::Result { + if !server::valid_app(cx).await { + return (StatusCode::UNAUTHORIZED, Json(serde_json::json!({ "error": "invalid_client" }))) + .into_response(cx); + } + let store = server::app(cx).store.clone(); + let services = im_core::services::list(&store).await?; + Json(serde_json::to_value(services).unwrap()).into_response(cx) +} + #[cfg(test)] mod tests { use std::path::Path; @@ -55,6 +71,7 @@ mod tests { use im_core::oidc::create_client; use im_core::model::ClientId; use im_core::store::Store; + use topcoat::asset::RouterBuilderAssetExt as _; use topcoat::cookie::RouterBuilderCookieExt as _; use topcoat::router::{Body, Router, RouterBuilderDiscoverExt as _, StatusCode, header, to_bytes}; @@ -94,6 +111,29 @@ mod tests { im_core::accounts::set_disabled(&store, &gone.id, true) .await .unwrap(); + let 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(), + }, + ]; + // The boot's one-time seed: the config's list becomes the table's + // starting rows, which is what every reader — /family, the trio, the + // landing card, the logout allowlist — now goes through. + im_core::services::seed_from(&store, &core_services(&services)) + .await + .unwrap(); let (live, _) = tokio::sync::broadcast::channel(64); let app = server::App { store: store.clone(), @@ -101,29 +141,21 @@ mod tests { 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(), - }, - ], + services, }, live, }; let router = Router::builder() .discover() .cookies() + // The pages shell renders its stylesheet link through the asset + // catalog, so the tests render pages against the real bundle — + // the same one `serve` loads beside the executable. + .assets(topcoat::asset::AssetBundle::load_dir(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../target/debug/assets" + )) + .unwrap()) .app_context(app) .build(); Setup { @@ -153,6 +185,21 @@ mod tests { (parts.status, String::from_utf8(bytes).unwrap()) } + /// The config's service list as the domain module's own shape — the one + /// conversion the boot-time seed needs. + fn core_services( + config: &[crate::config::Service], + ) -> Vec { + config + .iter() + .map(|service| im_core::services::Service { + key: service.key.clone(), + name: service.name.clone(), + url: service.url.clone(), + }) + .collect() + } + /// A form post through the router, answered as (status, Location, body). async fn post_form( router: &Router, @@ -200,6 +247,34 @@ mod tests { (parts.status, location) } + /// `GET /family` with an app's Basic pair (or without one). + async fn get_family(router: &Router, authorization: Option) -> (StatusCode, String) { + let mut builder = http::Request::builder().uri("/family"); + if let Some(value) = authorization { + builder = builder.header(header::AUTHORIZATION, value); + } + let response = router.handle(builder.body(Body::empty()).unwrap()).await; + let (parts, body) = response.into_parts(); + let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec(); + (parts.status, String::from_utf8(bytes).unwrap()) + } + + /// A page GET as a signed-in browser: the whole document back. + async fn get_page(router: &Router, uri: &str, cookie: &str) -> String { + let response = router + .handle( + http::Request::builder() + .uri(uri) + .header(header::COOKIE, cookie) + .body(Body::empty()) + .unwrap(), + ) + .await; + let (_, body) = response.into_parts(); + let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec(); + String::from_utf8(bytes).unwrap() + } + #[tokio::test] async fn the_directory_names_every_non_disabled_user_with_its_admin_flag() { let Setup { @@ -255,8 +330,10 @@ mod tests { .unwrap() .unwrap(); - // The RP-initiated exit: `back` naming a configured service's own + // The RP-initiated exit: `back` naming a stored service's own // origin is honored verbatim — the sibling gets its browser back. + // The allowlist is the seeded table now; the config's copy is only + // the seed's source. let one = im_core::sessions::create_session(&store, &ada.id, &Default::default()) .await .unwrap(); @@ -324,4 +401,223 @@ mod tests { assert_eq!(status, StatusCode::SEE_OTHER); assert_eq!(location.as_deref(), Some("/")); } + + #[tokio::test] + async fn family_serves_the_stored_list_to_registered_apps_only() { + let Setup { + router, + client_id, + secret, + .. + } = setup().await; + let (status, body) = get_family(&router, None).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!( + serde_json::from_str::(&body).unwrap()["error"], + "invalid_client" + ); + let (status, _) = get_family(&router, Some(basic(&client_id, "wrong"))).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + + // The seeded rows, in stored order, as a bare JSON array. + let (status, body) = get_family(&router, Some(basic(&client_id, &secret))).await; + assert_eq!(status, StatusCode::OK); + let family = serde_json::from_str::(&body).unwrap(); + let family = family + .as_array() + .unwrap() + .iter() + .map(|s| s["key"].as_str().unwrap()) + .collect::>(); + assert_eq!(family, vec!["in", "im", "iz"], "{body}"); + } + + #[tokio::test] + async fn the_panel_edits_the_family_and_every_reader_follows_the_table() { + let Setup { + router, + client_id, + secret, + store, + } = setup().await; + let ada = im_core::accounts::user_by_email(&store, "ada@example.com") + .await + .unwrap() + .unwrap(); + let ben = im_core::accounts::user_by_email(&store, "ben@example.com") + .await + .unwrap() + .unwrap(); + + // A non-admin's post is sent to the front door and writes nothing. + let ben_session = im_core::sessions::create_session(&store, &ben.id, &Default::default()) + .await + .unwrap(); + let (status, location, _) = post_form( + &router, + "/services/add", + "key=wiki&name=Wiki&url=http%3A%2F%2F127.0.0.1%3A99", + Some(&format!("{SESSION_COOKIE}={}", ben_session.expose())), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!(location.as_deref(), Some("/")); + + // The admin's add lands back on the card, and /family carries the + // new row at the end — trailing slash stored off, like every URL. + let session = im_core::sessions::create_session(&store, &ada.id, &Default::default()) + .await + .unwrap(); + let cookie = format!("{SESSION_COOKIE}={}", session.expose()); + let (status, location, _) = post_form( + &router, + "/services/add", + "key=wiki&name=Wiki&url=http%3A%2F%2F127.0.0.1%3A99%2F", + Some(&cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!(location.as_deref(), Some("/?ok=services")); + let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; + let family = serde_json::from_str::(&body).unwrap(); + let family = family.as_array().unwrap(); + let keys = family + .iter() + .map(|s| s["key"].as_str().unwrap()) + .collect::>(); + assert_eq!(keys, vec!["in", "im", "iz", "wiki"], "{body}"); + assert_eq!(family[3]["url"], "http://127.0.0.1:99"); + assert!(get_page(&router, "/?section=profile", &cookie) + .await + .contains(r#"action="/services/add""#)); + assert!(!get_page( + &router, + "/?section=profile", + &format!("{SESSION_COOKIE}={}", ben_session.expose()) + ) + .await + .contains(r#"action="/services/add""#)); + + // Edit rewrites name and address; move up swaps with the neighbor. + let (_status, location, _) = post_form( + &router, + "/services/edit", + "key=wiki&name=Docs&url=http%3A%2F%2F127.0.0.1%3A98", + Some(&cookie), + ) + .await; + assert_eq!(location.as_deref(), Some("/?ok=services")); + let (_status, location, _) = post_form( + &router, + "/services/move", + "key=wiki&dir=up", + Some(&cookie), + ) + .await; + assert_eq!(location.as_deref(), Some("/?ok=services")); + let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; + let family = serde_json::from_str::(&body).unwrap(); + let family = family.as_array().unwrap(); + let keys = family + .iter() + .map(|s| s["key"].as_str().unwrap()) + .collect::>(); + assert_eq!(keys, vec!["in", "im", "wiki", "iz"], "{body}"); + assert_eq!(family[2]["name"], "Docs"); + assert_eq!(family[2]["url"], "http://127.0.0.1:98"); + + // The logout allowlist is the table too: the DB-added origin — one + // no config ever named — gets its browser back. + let wiki_session = 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%3A98%2F", + &format!("{SESSION_COOKIE}={}", wiki_session.expose()), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!(location.as_deref(), Some("http://127.0.0.1:98/")); + + // And once the row is gone, the same origin is refused to the door. + let (_status, location, _) = post_form( + &router, + "/services/remove", + "key=wiki", + Some(&cookie), + ) + .await; + assert_eq!(location.as_deref(), Some("/?ok=services")); + let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; + let family = serde_json::from_str::(&body).unwrap(); + let keys = family + .as_array() + .unwrap() + .iter() + .map(|s| s["key"].as_str().unwrap()) + .collect::>(); + assert_eq!(keys, vec!["in", "im", "iz"], "{body}"); + let gone_session = 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%3A98%2F", + &format!("{SESSION_COOKIE}={}", gone_session.expose()), + ) + .await; + assert_eq!(location.as_deref(), Some("/")); + + // A value against the rules is the card's refusal, not a write. + let bad_session = im_core::sessions::create_session(&store, &ada.id, &Default::default()) + .await + .unwrap(); + let (_status, location, _) = post_form( + &router, + "/services/add", + "key=Wiki!&name=Wiki&url=http%3A%2F%2F127.0.0.1%3A97", + Some(&format!("{SESSION_COOKIE}={}", bad_session.expose())), + ) + .await; + assert_eq!(location.as_deref(), Some("/?error=bad_service")); + let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; + assert_eq!( + serde_json::from_str::(&body) + .unwrap() + .as_array() + .unwrap() + .len(), + 3, + "{body}" + ); + } + + #[tokio::test] + async fn the_seed_fills_an_empty_table_once_and_never_rewrites_it() { + let Setup { + router, + client_id, + secret, + store, + } = setup().await; + // The setup already seeded; a re-boot's seed must be a no-op, even + // though `in` is exactly the name the config carries. + let reseed = vec![im_core::services::Service { + key: "in".into(), + name: "Files".into(), + url: "http://127.0.0.1:7655".into(), + }]; + assert!(!im_core::services::seed_from(&store, &reseed).await.unwrap()); + let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; + assert_eq!( + serde_json::from_str::(&body) + .unwrap() + .as_array() + .unwrap() + .len(), + 3, + "{body}" + ); + } } diff --git a/crates/im-web/src/i18n.rs b/crates/im-web/src/i18n.rs index 62a6472..fdffc37 100644 --- a/crates/im-web/src/i18n.rs +++ b/crates/im-web/src/i18n.rs @@ -65,6 +65,7 @@ pub enum Key { ErrBadTheme, ErrBadUi, ErrBadLanguage, + ErrBadService, ErrFallback, // Good-news codes (`pages.rs`'s `ok_text`). @@ -127,6 +128,10 @@ pub enum Key { StatConnectedApps, SessionsTitle, ServicesTitle, + ServiceKeyLabel, + ServiceAdd, + ServiceMoveUp, + ServiceMoveDown, SignOutEverywhere, AdminPanelLink, ViewPhotoAria, @@ -329,6 +334,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (ErrBadUi, Tr) => "Bu bir arayüz değil.", (ErrBadLanguage, En) => "That is not a language.", (ErrBadLanguage, Tr) => "Bu bir dil değil.", + (ErrBadService, En) => { + "A service needs a key of lowercase letters, digits, or dashes, a name, and an http(s) address." + } + (ErrBadService, Tr) => { + "Bir hizmet; küçük harf, rakam ya da tire ile yazılmış bir anahtar, bir ad ve http(s) adresi ister." + } (ErrFallback, En) => "Something went wrong. Try again.", (ErrFallback, Tr) => "Bir şeyler ters gitti. Yeniden dene.", @@ -450,6 +461,14 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (SessionsTitle, Tr) => "Oturumlar", (ServicesTitle, En) => "Services", (ServicesTitle, Tr) => "Hizmetler", + (ServiceKeyLabel, En) => "Key", + (ServiceKeyLabel, Tr) => "Anahtar", + (ServiceAdd, En) => "Add service", + (ServiceAdd, Tr) => "Hizmet ekle", + (ServiceMoveUp, En) => "Move up", + (ServiceMoveUp, Tr) => "Yukarı taşı", + (ServiceMoveDown, En) => "Move down", + (ServiceMoveDown, Tr) => "Aşağı taşı", (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 a100eac..a5e0ac3 100644 --- a/crates/im-web/src/layout.rs +++ b/crates/im-web/src/layout.rs @@ -24,12 +24,13 @@ pub async fn wordmark(cx: &Cx) -> Result { } } -/// The signed-in chrome's app trio: every configured service's wordmark, +/// The signed-in chrome's app trio: every family 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. +/// siblings plain links. A family with no members renders nothing — the +/// single mark above stays the whole chrome. The list is the stored one, +/// the same rows `/family` serves. pub async fn service_trio(cx: &Cx) -> Result { - let services = &server::app(cx).config.services; + let services = im_core::services::list(&server::app(cx).store).await?; let marks = (!services.is_empty()).then(|| { services .iter() diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index f1cdc83..2a9d5df 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -143,6 +143,33 @@ async fn open_store(config: &Config) -> Arc { ) } +/// The one-time seed: a database with no services yet takes the config's +/// `[[services]]` list as the family's starting rows. Afterwards the admin +/// panel owns the list and the same file lines are dead letters — the seed +/// only fires again if the table is emptied. +async fn seed_services(store: &Store, config: &Config) { + if config.services.is_empty() { + return; + } + let seed: Vec = config + .services + .iter() + .map(|service| im_core::services::Service { + key: service.key.clone(), + name: service.name.clone(), + url: service.url.clone(), + }) + .collect(); + match im_core::services::seed_from(store, &seed).await { + Ok(true) => println!( + "im services seeded from config ({} entries)", + seed.len() + ), + Ok(false) => {} + Err(e) => eprintln!("im: seeding services from config failed: {e}"), + } +} + /// `im-web invite [--admin]`: creates the invite, mails it when the /// panel has configured a sender, prints the link otherwise (dev mode). /// @@ -215,6 +242,7 @@ async fn serve(config: Config) { println!("im {line}"); } let store = open_store(&config).await; + seed_services(&store, &config).await; let (live, _) = tokio::sync::broadcast::channel(64); // Told when the process is stopping, so the live streams end instead of // being waited out — see `live::Shutdown`. diff --git a/crates/im-web/src/pages.rs b/crates/im-web/src/pages.rs index f8dfaa0..c650e29 100644 --- a/crates/im-web/src/pages.rs +++ b/crates/im-web/src/pages.rs @@ -41,6 +41,7 @@ pub fn error_text(code: &str, lang: Lang) -> &'static str { "bad_theme" => t(lang, Key::ErrBadTheme), "bad_ui" => t(lang, Key::ErrBadUi), "bad_language" => t(lang, Key::ErrBadLanguage), + "bad_service" => t(lang, Key::ErrBadService), "empty_subject" => t(lang, Key::ErrEmptySubject), "empty_body" => t(lang, Key::ErrEmptyBody), "no_such_user" => t(lang, Key::ErrNoSuchUser), @@ -59,6 +60,7 @@ pub fn ok_text(code: &str, lang: Lang) -> &'static str { "photo_removed" => t(lang, Key::OkPhotoRemoved), "session_revoked" => t(lang, Key::OkSessionRevoked), "preferences" => t(lang, Key::Saved), + "services" => t(lang, Key::Saved), "password" => t(lang, Key::PasswordSaved), _ => t(lang, Key::OkDone), } @@ -601,13 +603,13 @@ 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 services home: one card per family member — 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 + // door to the rest. The list is the stored one — the rows `/family` + // serves — and an admin gets the handles on it right under the cards. + let services = im_core::services::list(&server::app(cx).store).await?; + let services_html = services .iter() .map(|service| { let current = service.key == "im"; @@ -624,6 +626,11 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { ) }) .collect::(); + let services_manage = if user.admin { + services_manage_html(&services, lang) + } else { + String::new() + }; let stage = view! { cx =>
@@ -631,10 +638,11 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { (wordmark(cx).await?) (service_trio(cx).await?) - if !services_html.is_empty() { + if !services_html.is_empty() || user.admin {
(t(lang, Key::ServicesTitle))
(topcoat::view::Unescaped::new_unchecked(services_html))
+ (topcoat::view::Unescaped::new_unchecked(services_manage))
} if let Some(code) = ok { @@ -846,6 +854,63 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { shell(cx, "im", Some(user), stage).await } +/// The admin's handles under the services grid: a name-and-address edit per +/// row, the up/down pair, the remove, and the add form. Every action is a +/// plain form post answering a 303 back to this card — the landing idiom — +/// wearing the admin panel's quiet row-button skin, laid out by the same +/// flex row the panel's invite line uses. +fn services_manage_html(services: &[im_core::services::Service], lang: Lang) -> String { + let mut rows = String::new(); + for service in services { + let key = escape(&service.key); + rows.push_str(&format!( + r#"
+
+ + + + +
+
+ + +
+
+ + +
+
+ + +
+
"#, + name = escape(&service.name), + url = escape(&service.url), + name_label = t(lang, Key::NameCol), + url_label = t(lang, Key::AddressLabel), + save = t(lang, Key::SaveButton), + up = t(lang, Key::ServiceMoveUp), + down = t(lang, Key::ServiceMoveDown), + remove = t(lang, Key::Remove), + )); + } + rows.push_str(&format!( + r#"
+
+ + + + +
+
"#, + key_label = t(lang, Key::ServiceKeyLabel), + name_label = t(lang, Key::NameCol), + url_label = t(lang, Key::AddressLabel), + add = t(lang, Key::ServiceAdd), + )); + rows +} + /// "Forgot it?" — the self-serve reset ask. It answers the same whether the /// address has an account: one quiet note, the same one for every address. #[page("/forgot")]