diff --git a/config/im.toml b/config/im.toml index 8fef96b..0b1c2ce 100644 --- a/config/im.toml +++ b/config/im.toml @@ -5,6 +5,13 @@ 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. +# +# This list is a FIRST-BOOT seed only: once the services table has rows, the +# file's lines are dead letters and the admin panel owns names and order. +# The addresses maintain themselves — im rewrites its own row from `issuer` +# on every boot, and a sibling registers itself over POST /family/register +# with its client pair. A row an app keeps can be renamed and reordered in +# the panel, but not re-pointed or removed there. [[services]] key = "in" name = "Files" diff --git a/crates/im-core/src/services.rs b/crates/im-core/src/services.rs index 8d5245d..39b9156 100644 --- a/crates/im-core/src/services.rs +++ b/crates/im-core/src/services.rs @@ -1,9 +1,13 @@ //! 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 admin panel (add, rename, reorder, remove), and served -//! to the sibling apps over `GET /family`, which each mirrors into its own -//! database. +//! landing's services home. The list lives in the database, seeded once from +//! the config's `[[services]]` on first boot and served to the sibling apps +//! over `GET /family`, which each mirrors into its own database. +//! +//! Names and order are the admin panel's. Addresses maintain themselves: an +//! app writes its own row through [`register`] — im from its `issuer` on +//! every boot, a sibling over `POST /family/register` — and a row an app +//! keeps is neither removed nor re-pointed from the panel, because the next +//! boot would undo it. use serde::Serialize; @@ -19,8 +23,18 @@ pub struct Service { pub key: String, pub name: String, pub url: String, + /// The app that keeps this row — `SELF_OWNER` for im's own entry, a + /// client id for a sibling that registered itself, `None` for a row the + /// seed or the panel made. Never serialized: `/family`'s shape is the + /// three public fields the siblings mirror, and nothing more. + #[serde(skip)] + pub owner: Option, } +/// The owner im writes on its own row, registered from `issuer` on every +/// boot — not a client id, because im is nobody's client. +pub const SELF_OWNER: &str = "im"; + /// 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 @@ -49,10 +63,7 @@ pub fn validate(key: &str, name: &str, url: &str) -> std::result::Result<(), Str if authority.is_empty() { return Err(format!("url {url:?} must name a host")); } - if trimmed - .chars() - .any(|c| c.is_whitespace() || c.is_control()) - { + if trimmed.chars().any(|c| c.is_whitespace() || c.is_control()) { return Err(format!( "url {url:?} must not carry spaces or control characters" )); @@ -73,7 +84,7 @@ 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", + "SELECT key, name, url, owner FROM services ORDER BY position, key", (), ) .await @@ -84,6 +95,7 @@ pub async fn list(store: &Store) -> Result> { key: store::text(&row, 0)?, name: store::text(&row, 1)?, url: store::text(&row, 2)?, + owner: store::opt_text(&row, 3)?, }); } Ok(services) @@ -123,9 +135,20 @@ pub async fn add(store: &Store, service: &Service) -> Result<()> { /// 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. +/// A row an app keeps only takes its new name here: the address is the +/// app's own, rewritten on its every boot, so accepting one from the panel +/// would show an edit the next boot silently undoes. 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('/'); + if let Some(row) = owned_row(store, key).await? + && row.1.is_some() + && row.0 != url + { + return Err(StoreError::Invalid(format!( + "service {key:?} keeps its own address; its app re-registers it on every boot" + ))); + } let conn = store.conn.lock().await; let updated = conn .execute( @@ -143,7 +166,14 @@ pub async fn edit(store: &Store, key: &str, name: &str, url: &str) -> Result<()> /// 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. +/// A row an app keeps is not the panel's to take: it would come back on the +/// app's next boot. pub async fn remove(store: &Store, key: &str) -> Result<()> { + if let Some((_, Some(_))) = owned_row(store, key).await? { + return Err(StoreError::Invalid(format!( + "service {key:?} is kept by its app; it re-registers on every boot" + ))); + } let conn = store.conn.lock().await; let mut rows = conn .query( @@ -157,12 +187,9 @@ pub async fn remove(store: &Store, key: &str) -> Result<()> { }; 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("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], @@ -226,6 +253,73 @@ pub async fn move_service(store: &Store, key: &str, up: bool) -> Result<()> { Ok(()) } +/// A row's stored `(url, owner)`, or `None` when no row carries the key. +async fn owned_row(store: &Store, key: &str) -> Result)>> { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT url, owner FROM services WHERE key = ?1", + turso::params![key], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(None); + }; + Ok(Some((store::text(&row, 0)?, store::opt_text(&row, 1)?))) +} + +/// An app writing its own row: im from its `issuer` on every boot, a sibling +/// over `POST /family/register` with its client id as the `owner`. A key +/// nobody holds is appended (or claimed, keeping the name the seed or the +/// panel gave it); a key the caller already holds takes the new address +/// only — the name is the admin's after the first insert. A key another app +/// keeps is a conflict, never a takeover. +pub async fn register( + store: &Store, + key: &str, + name: &str, + url: &str, + owner: &str, +) -> Result { + validate(key, name, url).map_err(StoreError::Invalid)?; + let url = url.trim_end_matches('/').to_string(); + match owned_row(store, key).await? { + Some((_, Some(held))) if held != owner => { + return Err(StoreError::Conflict(format!( + "service key {key:?} belongs to another app" + ))); + } + Some(_) => { + // Claiming an unowned row or refreshing our own: the address is + // the app's to say, the name stays whatever is stored. + 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], + ) + .await + .map_err(backend)?; + } + 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], + ) + .await + .map_err(backend)?; + } + } + let row = list(store) + .await? + .into_iter() + .find(|service| service.key == key) + .ok_or_else(|| StoreError::Backend(format!("service {key:?} vanished after its write")))?; + Ok(row) +} + /// 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` @@ -269,11 +363,17 @@ mod tests { key: key.to_string(), name: name.to_string(), url: url.to_string(), + owner: None, } } async fn keys(store: &Store) -> Vec { - list(store).await.unwrap().into_iter().map(|s| s.key).collect() + list(store) + .await + .unwrap() + .into_iter() + .map(|s| s.key) + .collect() } #[tokio::test] @@ -299,12 +399,9 @@ mod tests { #[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(); + 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(); @@ -375,7 +472,9 @@ mod tests { .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(); + add(&store, &service("wiki", "Wiki", "http://wiki")) + .await + .unwrap(); assert_eq!( keys(&store).await, vec!["in".to_string(), "iz".to_string(), "wiki".to_string()] @@ -385,13 +484,126 @@ mod tests { #[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://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"); + 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()); } + + #[tokio::test] + async fn an_app_registers_itself_appending_then_claiming_then_refreshing() { + let store = store().await; + // Nothing on the list yet: the app's own row is appended. + let row = register( + &store, + "im", + "Account", + "http://127.0.0.1:7650/", + SELF_OWNER, + ) + .await + .unwrap(); + assert_eq!( + row.url, "http://127.0.0.1:7650", + "the slash is normalized off" + ); + assert_eq!(row.owner.as_deref(), Some(SELF_OWNER)); + + // 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") + .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")); + + // The same app's next boot moves the address only. + let row = register(&store, "in", "Whatever", "https://in.dizey.sh", "in-client") + .await + .unwrap(); + assert_eq!(row.name, "Dosyalar"); + assert_eq!(row.url, "https://in.dizey.sh"); + // And no row was duplicated by any of it. + assert_eq!(keys(&store).await, vec!["im".to_string(), "in".to_string()]); + } + + #[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") + .await + .unwrap(); + assert!(matches!( + register(&store, "in", "Files", "https://evil.example", "iz-client").await, + Err(StoreError::Conflict(_)) + )); + assert_eq!(list(&store).await.unwrap()[0].url, "https://in.example"); + } + + #[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") + .await + .unwrap(); + assert!(matches!( + remove(&store, "in").await, + Err(StoreError::Invalid(_)) + )); + assert!(matches!( + edit(&store, "in", "Dosyalar", "https://elsewhere.example").await, + Err(StoreError::Invalid(_)) + )); + // The name is still the admin's, and a name-only edit lands. + edit(&store, "in", "Dosyalar", "https://in.example") + .await + .unwrap(); + let row = &list(&store).await.unwrap()[0]; + assert_eq!(row.name, "Dosyalar"); + assert_eq!(row.url, "https://in.example"); + // An unowned row is still the panel's to take. + add(&store, &service("wiki", "Wiki", "http://wiki")) + .await + .unwrap(); + remove(&store, "wiki").await.unwrap(); + assert_eq!(keys(&store).await, vec!["in".to_string()]); + } + + #[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) + .await + .unwrap(); + let json = serde_json::to_value(list(&store).await.unwrap()).unwrap(); + let row = &json.as_array().unwrap()[0]; + assert_eq!( + row.as_object().unwrap().keys().collect::>(), + vec!["key", "name", "url"], + "the sibling mirrors deserialize this shape: {json}" + ); + } } diff --git a/crates/im-core/src/store.rs b/crates/im-core/src/store.rs index 516793e..98ab139 100644 --- a/crates/im-core/src/store.rs +++ b/crates/im-core/src/store.rs @@ -21,6 +21,10 @@ pub enum StoreError { /// caller turns it into the page's refusal, never a database problem. #[error("{0}")] Invalid(String), + /// The write is well-formed but the row belongs to someone else — the + /// web layer answers 409, not 400. + #[error("{0}")] + Conflict(String), } pub type Result = std::result::Result; @@ -135,7 +139,8 @@ CREATE TABLE IF NOT EXISTS services ( key TEXT PRIMARY KEY, name TEXT NOT NULL, url TEXT NOT NULL, - position INTEGER NOT NULL + position INTEGER NOT NULL, + owner TEXT ); "; @@ -207,9 +212,12 @@ impl Store { // born before these columns grow them here — TEXT NOT NULL with // a DEFAULT so every existing row reads the default. if !has_column(&conn, "users", "theme").await? { - conn.execute("ALTER TABLE users ADD COLUMN theme TEXT NOT NULL DEFAULT 'light'", ()) - .await - .map_err(backend)?; + conn.execute( + "ALTER TABLE users ADD COLUMN theme TEXT NOT NULL DEFAULT 'light'", + (), + ) + .await + .map_err(backend)?; } if !has_column(&conn, "users", "language").await? { conn.execute( @@ -229,6 +237,14 @@ impl Store { } // 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", ()) + .await + .map_err(backend)?; + } if !has_column(&conn, "sessions", "ip").await? { conn.execute("ALTER TABLE sessions ADD COLUMN ip TEXT", ()) .await diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index ba6de32..3d249e7 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -420,17 +420,35 @@ async fn services_section(cx: &Cx, lang: i18n::Lang) -> Result