diff --git a/crates/im-core/src/services.rs b/crates/im-core/src/services.rs index 39b9156..ac3962e 100644 --- a/crates/im-core/src/services.rs +++ b/crates/im-core/src/services.rs @@ -29,6 +29,14 @@ pub struct Service { /// three public fields the siblings mirror, and nothing more. #[serde(skip)] pub owner: Option, + /// The relying-party credential this row answers for — the client id + /// `POST /family/register` authenticated, stamped on every register, + /// insert and refresh alike. im's own row stays `None`: the IdP is not + /// its own client. This is the panel's join key between the wordmark + /// and its Rotate/Revoke controls; a row the seed or the panel made + /// carries `None` until its app registers. + #[serde(skip)] + pub client_id: Option, } /// The owner im writes on its own row, registered from `issuer` on every @@ -84,7 +92,7 @@ pub async fn list(store: &Store) -> Result> { let conn = store.conn.lock().await; let mut rows = conn .query( - "SELECT key, name, url, owner FROM services ORDER BY position, key", + "SELECT key, name, url, owner, client_id FROM services ORDER BY position, key", (), ) .await @@ -96,6 +104,7 @@ pub async fn list(store: &Store) -> Result> { name: store::text(&row, 1)?, url: store::text(&row, 2)?, owner: store::opt_text(&row, 3)?, + client_id: store::opt_text(&row, 4)?, }); } Ok(services) @@ -281,6 +290,7 @@ pub async fn register( name: &str, url: &str, owner: &str, + client_id: Option<&str>, ) -> Result { validate(key, name, url).map_err(StoreError::Invalid)?; let url = url.trim_end_matches('/').to_string(); @@ -292,11 +302,12 @@ pub async fn register( } Some(_) => { // Claiming an unowned row or refreshing our own: the address is - // the app's to say, the name stays whatever is stored. + // the app's to say, the name stays whatever is stored, and the + // credential stamp follows the caller on every register. let conn = store.conn.lock().await; conn.execute( - "UPDATE services SET url = ?2, owner = ?3 WHERE key = ?1", - turso::params![key, url.as_str(), owner], + "UPDATE services SET url = ?2, owner = ?3, client_id = ?4 WHERE key = ?1", + turso::params![key, url.as_str(), owner, client_id], ) .await .map_err(backend)?; @@ -304,9 +315,9 @@ pub async fn register( None => { let conn = store.conn.lock().await; conn.execute( - "INSERT INTO services (key, name, url, position, owner) \ - VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(position), -1) + 1 FROM services), ?4)", - turso::params![key, name.trim(), url.as_str(), owner], + "INSERT INTO services (key, name, url, position, owner, client_id) \ + VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(position), -1) + 1 FROM services), ?4, ?5)", + turso::params![key, name.trim(), url.as_str(), owner, client_id], ) .await .map_err(backend)?; @@ -364,6 +375,7 @@ mod tests { name: name.to_string(), url: url.to_string(), owner: None, + client_id: None, } } @@ -519,6 +531,7 @@ mod tests { "Account", "http://127.0.0.1:7650/", SELF_OWNER, + None, ) .await .unwrap(); @@ -527,25 +540,36 @@ mod tests { "the slash is normalized off" ); assert_eq!(row.owner.as_deref(), Some(SELF_OWNER)); + assert_eq!(row.client_id, None, "im is not its own client"); // A seeded row belongs to nobody; the app that names it claims it, // keeping the name the seed (or a later rename) gave it. add(&store, &service("in", "Dosyalar", "http://127.0.0.1:7655")) .await .unwrap(); - let row = register(&store, "in", "Files", "https://in.example", "in-client") + let row = register(&store, "in", "Files", "https://in.example", "in-client", Some("in-client")) .await .unwrap(); assert_eq!(row.name, "Dosyalar", "the name stays the admin's"); assert_eq!(row.url, "https://in.example"); assert_eq!(row.owner.as_deref(), Some("in-client")); + assert_eq!( + row.client_id.as_deref(), + Some("in-client"), + "the claim stamps the credential" + ); // The same app's next boot moves the address only. - let row = register(&store, "in", "Whatever", "https://in.dizey.sh", "in-client") + let row = register(&store, "in", "Whatever", "https://in.dizey.sh", "in-client", Some("in-client")) .await .unwrap(); assert_eq!(row.name, "Dosyalar"); assert_eq!(row.url, "https://in.dizey.sh"); + assert_eq!( + row.client_id.as_deref(), + Some("in-client"), + "the refresh keeps the stamp current" + ); // And no row was duplicated by any of it. assert_eq!(keys(&store).await, vec!["im".to_string(), "in".to_string()]); } @@ -553,11 +577,11 @@ mod tests { #[tokio::test] async fn a_key_another_app_keeps_is_a_conflict_and_the_row_is_untouched() { let store = store().await; - register(&store, "in", "Files", "https://in.example", "in-client") + register(&store, "in", "Files", "https://in.example", "in-client", Some("in-client")) .await .unwrap(); assert!(matches!( - register(&store, "in", "Files", "https://evil.example", "iz-client").await, + register(&store, "in", "Files", "https://evil.example", "iz-client", None).await, Err(StoreError::Conflict(_)) )); assert_eq!(list(&store).await.unwrap()[0].url, "https://in.example"); @@ -566,7 +590,7 @@ mod tests { #[tokio::test] async fn the_panel_cannot_remove_an_owned_row_or_move_its_address() { let store = store().await; - register(&store, "in", "Files", "https://in.example", "in-client") + register(&store, "in", "Files", "https://in.example", "in-client", Some("in-client")) .await .unwrap(); assert!(matches!( @@ -595,7 +619,7 @@ mod tests { #[tokio::test] async fn the_family_json_never_carries_the_owner() { let store = store().await; - register(&store, "im", "Account", "http://127.0.0.1:7650", SELF_OWNER) + register(&store, "im", "Account", "http://127.0.0.1:7650", SELF_OWNER, None) .await .unwrap(); let json = serde_json::to_value(list(&store).await.unwrap()).unwrap(); diff --git a/crates/im-core/src/store.rs b/crates/im-core/src/store.rs index 72de1b6..6035ce3 100644 --- a/crates/im-core/src/store.rs +++ b/crates/im-core/src/store.rs @@ -153,7 +153,8 @@ CREATE TABLE IF NOT EXISTS services ( name TEXT NOT NULL, url TEXT NOT NULL, position INTEGER NOT NULL, - owner TEXT + owner TEXT, + client_id TEXT ); "; @@ -261,13 +262,15 @@ impl Store { .await .map_err(backend)?; } - // What a session remembers about its browser: the listing shows - // these, so old databases grow them the same guarded way. - // The app that keeps a service row: `im` for this app's own - // entry, a client id for a sibling that registers itself, NULL - // for the config seed's and the panel's own rows. - if !has_column(&conn, "services", "owner").await? { - conn.execute("ALTER TABLE services ADD COLUMN owner TEXT", ()) + // The family rows' client linkage (the merge of the panel's + // services and clients sections): a `POST /family/register` + // stamps the authenticated client's id beside its row, so the + // panel can show the wordmark and its credential as one thing. + // ALTER over the owner precedent: databases born before the + // column get it here, and every existing row reads NULL until + // its app re-registers. + if !has_column(&conn, "services", "client_id").await? { + conn.execute("ALTER TABLE services ADD COLUMN client_id TEXT", ()) .await .map_err(backend)?; } diff --git a/crates/im-web/assets/main.css b/crates/im-web/assets/main.css index 43676c0..d1b3428 100644 --- a/crates/im-web/assets/main.css +++ b/crates/im-web/assets/main.css @@ -984,6 +984,13 @@ body:has(.log-list) .admin-card:has(.log-list) { border-top: 1px solid var(--border-soft); vertical-align: middle; } +.admin-table td.mono { + overflow-wrap: anywhere; +} + +.admin-clients td.muted { + white-space: nowrap; +} .mono { font-family: var(--font-mono); @@ -995,6 +1002,7 @@ body:has(.log-list) .admin-card:has(.log-list) { .actions { display: flex; + flex-wrap: wrap; gap: 8px; justify-content: flex-end; } @@ -1129,15 +1137,17 @@ body:has(.log-list) .admin-card:has(.log-list) { } .admin-confirm-pop { - position: absolute; - right: 0; - top: calc(100% + 6px); + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); z-index: 30; width: 240px; padding: 12px; background: var(--surface); border: 1px solid var(--border-strong); border-radius: var(--radius); + box-shadow: var(--shadow-2); display: flex; flex-direction: column; gap: 8px; diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index 0441fb0..46a0be6 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -132,7 +132,6 @@ async fn admin_page(cx: &Cx) -> Result { [ ("users", t(lang, Key::NavUsers)), ("services", t(lang, Key::NavServices)), - ("clients", t(lang, Key::NavClients)), ("message", t(lang, Key::NavMessage)), ("settings", t(lang, Key::NavSettings)), ("logs", t(lang, Key::NavLogs)), @@ -152,8 +151,9 @@ async fn admin_page(cx: &Cx) -> Result { "message" => message_section(cx, lang).await?, "settings" => settings_section(cx, lang).await?, "logs" => logs_section(cx, lang).await?, - "services" => services_section(cx, lang).await?, - "clients" => clients_section(cx, shown, lang).await?, + // `section=clients` lands here too — the sections are one table + // now, and the old address keeps working. + "services" | "clients" => services_section(cx, shown, lang).await?, _ => users_section(cx, &me, invited.as_deref(), lang).await?, }; @@ -438,13 +438,26 @@ async fn users_section( )) } -/// The family registry: the wordmarks every topbar's trio and the landing's -/// services home render, and `/family` serves. One table in the panel's own -/// skins — edit and remove as the two-step disclosures, the up/down pair as -/// plain row buttons — and the add line under it wearing the invite form's -/// skin. -async fn services_section(cx: &Cx, lang: i18n::Lang) -> Result { +/// The family registry, wordmarks and credentials as one table. Every +/// service row carries its client half beside it — client id, redirect +/// URIs, registered date, Rotate/Revoke — joined by the client id its +/// `POST /family/register` authenticated; a client with no service row (a +/// test or stray credential) renders as a credential-only row, and a row +/// with no client yet shows the dash. The wordmark controls stay the +/// panel's on rows no app keeps, and the two add lines — a service, a +/// client — sit under the table. +async fn services_section( + cx: &Cx, + shown: Option<(String, String)>, + lang: i18n::Lang, +) -> Result { let services = im_core::services::list(&app(cx).store).await?; + let clients = im_core::oidc::list_clients(&app(cx).store).await?; + // The join: a service row's client id names the client whose wordmark + // half and credential half render as one. + let linked = |id: Option<&String>| { + id.and_then(|cid| clients.iter().find(|client| &client.client_id.to_string() == cid)) + }; let mut rows = String::new(); for service in &services { let key = escape(&service.key); @@ -508,34 +521,141 @@ async fn services_section(cx: &Cx, lang: i18n::Lang) -> Result { + let id = escape(&client.client_id.to_string()); + let uris = client + .redirect_uris + .iter() + .map(|uri| escape(uri)) + .collect::>() + .join("
"); + let registered = client + .created_at + .format(&time::macros::format_description!( + "[year]-[month]-[day]" + )) + .unwrap_or_default(); + let controls = client_controls( + &id, + &escape(&client.name), + lang, + ); + (id, uris, registered, controls) + } + None => ("—".to_string(), "—".to_string(), "—".to_string(), String::new()), + }; rows.push_str(&format!( - r#"{key}{name}{url}{edit}{up}{down}{remove}"#, + r#"{key}{name}{url}{client_cell}{uris_cell}{registered_cell}{edit}{up}{down}{remove}{client_actions}"#, )); } + // Clients no service row answers for — the CLI's or the panel's test + // credentials — still sit in the table, their credential half alone. + for client in &clients { + let id = client.client_id.to_string(); + if services + .iter() + .any(|service| service.client_id.as_deref() == Some(id.as_str())) + { + continue; + } + let name = escape(&client.name); + let uris = client + .redirect_uris + .iter() + .map(|uri| escape(uri)) + .collect::>() + .join("
"); + let registered = client + .created_at + .format(&time::macros::format_description!("[year]-[month]-[day]")) + .unwrap_or_default(); + let controls = client_controls(&id, &name, lang); + rows.push_str(&format!( + r#"—{name}—{}{uris}{registered}{controls}"#, + escape(&id), + )); + } + // The show-once banner: the note says what to do with it, the value is + // click-to-copy, and the shelf behind it has already handed it over. + let shown_html = shown + .map(|(client_id, secret)| { + format!( + r#"
{note}
{id_label}: {client_id}
{secret}
"#, + note = t(lang, Key::SecretShownNote), + id_label = t(lang, Key::ClientIdLabel), + client_id = escape(&client_id), + secret = escape(&secret), + copied = t(lang, Key::CopiedWord), + copy = t(lang, Key::CopyWord), + ) + }) + .unwrap_or_default(); Ok(format!( r#"
{title}
+ {shown_html}
- - +
{key_label}{name_label}{url_label}
+ {rows}
{key_label}{name_label}{url_label}{id_label}{uris_label}{registered_label}
+
{service_add_label}
+
{client_add_label}
+
+ + + +
"#, title = t(lang, Key::ServicesTitle), key_label = t(lang, Key::ServiceKeyLabel), name_label = t(lang, Key::NameCol), url_label = t(lang, Key::AddressLabel), + id_label = t(lang, Key::ClientIdLabel), + uris_label = t(lang, Key::RedirectUrisLabel), + registered_label = t(lang, Key::RegisteredCol), + service_add_label = t(lang, Key::ServiceAdd), add = t(lang, Key::ServiceAdd), + client_add_label = t(lang, Key::ClientAdd), + client_add = t(lang, Key::ClientAdd), )) } +/// A client's Rotate/Revoke pair, as the two-step disclosures — the same +/// controls on a linked service row and on a credential-only row. +fn client_controls(client_id: &str, name_html: &str, lang: i18n::Lang) -> String { + let rotate = confirm_action( + "client", + client_id, + "/admin/clients_rotate", + t(lang, Key::RotateWord), + "", + &i18n::rotate_client_title(lang, name_html), + t(lang, Key::RotateCost), + t(lang, Key::ConfirmRotate), + ); + let revoke_action = confirm_action( + "client", + client_id, + "/admin/clients_revoke", + t(lang, Key::RevokeWord), + " admin-danger", + &i18n::revoke_client_title(lang, name_html), + t(lang, Key::RevokeCost), + t(lang, Key::ConfirmRevoke), + ); + format!("{rotate}{revoke_action}") +} + /// One user of the services forms: key, name, address. The add form fills /// all three; the edit form carries the key in its hidden field. #[derive(Deserialize)] @@ -558,6 +678,7 @@ async fn services_add(cx: &Cx, Form(input): Form) -> Result, - lang: i18n::Lang, -) -> Result { - let clients = im_core::oidc::list_clients(&app(cx).store).await?; - let mut rows = String::new(); - for client in &clients { - let id = escape(&client.client_id.to_string()); - let name = escape(&client.name); - let uris = client - .redirect_uris - .iter() - .map(|uri| escape(uri)) - .collect::>() - .join("
"); - let registered = client - .created_at - .format(&time::macros::format_description!("[year]-[month]-[day]")) - .unwrap_or_default(); - // Rotation kills the old pair the moment the new one exists, so it - // says what it costs before it does it — like every destructive row - // action here. - let rotate = confirm_action( - "client", - &id, - "/admin/clients_rotate", - t(lang, Key::RotateWord), - "", - &i18n::rotate_client_title(lang, &name), - t(lang, Key::RotateCost), - t(lang, Key::ConfirmRotate), - ); - let revoke_action = confirm_action( - "client", - &id, - "/admin/clients_revoke", - t(lang, Key::RevokeWord), - " admin-danger", - &i18n::revoke_client_title(lang, &name), - t(lang, Key::RevokeCost), - t(lang, Key::ConfirmRevoke), - ); - rows.push_str(&format!( - r#"{name}{id}{uris}{registered}{rotate}{revoke_action}"#, - )); - } - // The show-once banner: the note says what to do with it, the value is - // click-to-copy, and the shelf behind it has already handed it over. - let shown_html = shown - .map(|(client_id, secret)| { - format!( - r#"
{note}
{id_label}: {client_id}
{secret}
"#, - note = t(lang, Key::SecretShownNote), - id_label = t(lang, Key::ClientIdLabel), - client_id = escape(&client_id), - secret = escape(&secret), - copied = t(lang, Key::CopiedWord), - copy = t(lang, Key::CopyWord), - ) - }) - .unwrap_or_default(); - Ok(format!( - r#"
-
{title}
- {shown_html} -
- - - {rows} -
{name_label}{id_label}{uris_label}{registered_label}
-
-
- - - -
-
"#, - title = t(lang, Key::ClientsTitle), - name_label = t(lang, Key::NameCol), - id_label = t(lang, Key::ClientIdLabel), - uris_label = t(lang, Key::RedirectUrisLabel), - registered_label = t(lang, Key::RegisteredCol), - add = t(lang, Key::ClientAdd), - )) -} - /// One user of the clients forms: the name, and one or more redirect URIs /// — whitespace- or comma-separated, as loose as the CLI's argument list, /// because a family dev's `http://127.0.0.1` redirect is a legitimate row. @@ -1916,8 +1944,12 @@ mod tests { assert!(location.starts_with("/admin?section=clients&shown=")); let ticket = location.trim_start_matches("/admin?section=clients&shown="); let (id, secret) = server::take_shown_secret(ticket).expect("the one showing"); - let row = list_clients(&setup.store).await.unwrap(); - assert_eq!(id, row[0].client_id.to_string()); + let stored = list_clients(&setup.store).await.unwrap(); + let row = stored + .iter() + .find(|client| client.name == name) + .expect("the fresh row"); + assert_eq!(id, row.client_id.to_string()); (id, secret) } @@ -2182,4 +2214,75 @@ mod tests { .await; assert!(!forged.contains("
Drive"), "the service name renders"); + assert!(body.contains(&id), "the linked client id renders"); + assert!(body.contains("https://drive.dizey.sh"), "the url renders"); + assert!(body.contains("http://127.0.0.1:9000/callback"), "uris render"); + // The credential-only row: the stray client's name, no key or url. + assert!(body.contains(">stray"), "the stray client renders"); + // The bare service row and the unlinked client carry the dash. + assert!(body.contains(">Wiki"), "the bare service renders"); + assert!( + body.contains("—"), + "client-less halves read as the dash" + ); + + // The old address lands on the merged section too. + let (status, _, alias) = get_full( + &setup.router, + "/admin?section=clients", + Some(&setup.admin_cookie), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(alias.contains(">Drive"), body.contains(">Drive")); + } } diff --git a/crates/im-web/src/directory.rs b/crates/im-web/src/directory.rs index 4390fa1..c873a26 100644 --- a/crates/im-web/src/directory.rs +++ b/crates/im-web/src/directory.rs @@ -201,7 +201,15 @@ async fn family_register( .into_response(cx); }; let store = server::app(cx).store.clone(); - match im_core::services::register(&store, &input.key, &input.name, &input.url, &client_id).await + match im_core::services::register( + &store, + &input.key, + &input.name, + &input.url, + &client_id, + Some(&client_id), + ) + .await { Ok(service) => Json(serde_json::to_value(service).unwrap()).into_response(cx), Err(im_core::store::StoreError::Conflict(_)) => ( @@ -396,6 +404,7 @@ mod tests { name: service.name.clone(), url: service.url.clone(), owner: None, + client_id: None, }) .collect() } @@ -853,6 +862,7 @@ mod tests { name: "Files".into(), url: "http://127.0.0.1:7655".into(), owner: None, + client_id: None, }]; assert!(!im_core::services::seed_from(&store, &reseed).await.unwrap()); let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; @@ -1051,6 +1061,44 @@ mod tests { ); } + #[tokio::test] + async fn family_register_stamps_the_authenticated_client_on_its_row() { + let Setup { + router, + client_id, + secret, + store, + .. + } = setup().await; + + // First register: the row is appended with the caller's stamp. + let (status, _) = post_register( + &router, + Some(basic(&client_id, &secret)), + serde_json::json!({"key": "drive", "name": "Drive", "url": "https://drive.dizey.sh"}), + ) + .await; + assert_eq!(status, StatusCode::OK); + let rows = im_core::services::list(&store).await.unwrap(); + let row = rows.iter().find(|s| s.key == "drive").unwrap(); + assert_eq!(row.client_id.as_deref(), Some(client_id.as_str())); + + // The next boot's register refreshes the row and keeps the stamp + // current — one row, still the caller's. + let (status, _) = post_register( + &router, + Some(basic(&client_id, &secret)), + serde_json::json!({"key": "drive", "name": "Drive", "url": "https://drive2.dizey.sh"}), + ) + .await; + assert_eq!(status, StatusCode::OK); + let rows = im_core::services::list(&store).await.unwrap(); + assert_eq!(rows.iter().filter(|s| s.key == "drive").count(), 1); + let row = rows.iter().find(|s| s.key == "drive").unwrap(); + assert_eq!(row.url, "https://drive2.dizey.sh"); + assert_eq!(row.client_id.as_deref(), Some(client_id.as_str())); + } + #[tokio::test] async fn the_landing_lists_connected_apps_and_an_empty_note_without_them() { let Setup { diff --git a/crates/im-web/src/i18n.rs b/crates/im-web/src/i18n.rs index a246483..157fa37 100644 --- a/crates/im-web/src/i18n.rs +++ b/crates/im-web/src/i18n.rs @@ -243,8 +243,6 @@ pub enum Key { InviteButton, // Admin clients section: the family's relying parties. - NavClients, - ClientsTitle, RedirectUrisLabel, RegisteredCol, ClientAdd, @@ -726,10 +724,6 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (InviteButton, En) => "Invite", (InviteButton, Tr) => "Davet et", - (NavClients, En) => "Clients", - (NavClients, Tr) => "İstemciler", - (ClientsTitle, En) => "Clients", - (ClientsTitle, Tr) => "İstemciler", (RedirectUrisLabel, En) => "Redirect URIs", (RedirectUrisLabel, Tr) => "Yönlendirme adresleri", (RegisteredCol, En) => "Registered", diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index d9f9c46..8b8494b 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -173,6 +173,7 @@ async fn seed_services(store: &Store, config: &Config) { name: service.name.clone(), url: service.url.clone(), owner: None, + client_id: None, }) .collect(); match im_core::services::seed_from(store, &seed).await { @@ -198,6 +199,8 @@ async fn register_self(store: &Store, config: &Config) { "Account", &config.issuer, im_core::services::SELF_OWNER, + // im is nobody's client: its own row carries no credential stamp. + None, ) .await { diff --git a/style/main.scss b/style/main.scss index 659231c..e9b366e 100644 --- a/style/main.scss +++ b/style/main.scss @@ -1041,6 +1041,7 @@ body:has(.log-list) { .actions { display: flex; + flex-wrap: wrap; gap: 8px; justify-content: flex-end;