forge
Explore
Log in

Don't you dare go Hollow

the family maintains its own addresses: services rows carry an owner, im writes its own row from issuer on every boot, and a sibling writes its own over the new POST /family/register behind the same client pair as GET /family — a key nobody holds is appended or claimed keeping the admin's name, the same app's next boot moves the address only, another app's key is a 409 — while the admin panel keeps names and order but can neither remove nor re-point a row an app keeps, since the next boot would undo it; the seed stays first-boot-only and the toml comment says so

Browse files at this commit

e75961512d76233d7511046de76e12c2dc3dc2ceAhmet Kaan GümüşParent: ec7fa5c
Claude-Session: https://claude.ai/code/session_01JDMA1TAen2UjGRvUVu96KE
config/im.tomlmodified+7 -0
@@ -5,6 +5,13 @@ issuer = "http://127.0.0.1:7650"
55 # The sibling apps of the switcher and the landing's services home, in
66 # wordmark order. Prod uses https://<key>.dizey.sh — deploy-side config,
77 # not committed here.
8+#
9+# This list is a FIRST-BOOT seed only: once the services table has rows, the
10+# file's lines are dead letters and the admin panel owns names and order.
11+# The addresses maintain themselves — im rewrites its own row from `issuer`
12+# on every boot, and a sibling registers itself over POST /family/register
13+# with its client pair. A row an app keeps can be renamed and reordered in
14+# the panel, but not re-pointed or removed there.
815 [[services]]
916 key = "in"
1017 name = "Files"
crates/im-core/src/services.rsmodified+241 -29
@@ -1,9 +1,13 @@
11 //! The family: the services every topbar shows as wordmarks and the
2-//! landing's services home. The list lives in the database and the admin
3-//! panel owns it — seeded once from the config's `[[services]]` on first
4-//! boot, edited from the admin panel (add, rename, reorder, remove), and served
5-//! to the sibling apps over `GET /family`, which each mirrors into its own
6-//! database.
2+//! landing's services home. The list lives in the database, seeded once from
3+//! the config's `[[services]]` on first boot and served to the sibling apps
4+//! over `GET /family`, which each mirrors into its own database.
5+//!
6+//! Names and order are the admin panel's. Addresses maintain themselves: an
7+//! app writes its own row through [`register`] — im from its `issuer` on
8+//! every boot, a sibling over `POST /family/register` — and a row an app
9+//! keeps is neither removed nor re-pointed from the panel, because the next
10+//! boot would undo it.
711
812 use serde::Serialize;
913
@@ -19,8 +23,18 @@ pub struct Service {
1923 pub key: String,
2024 pub name: String,
2125 pub url: String,
26+ /// The app that keeps this row — `SELF_OWNER` for im's own entry, a
27+ /// client id for a sibling that registered itself, `None` for a row the
28+ /// seed or the panel made. Never serialized: `/family`'s shape is the
29+ /// three public fields the siblings mirror, and nothing more.
30+ #[serde(skip)]
31+ pub owner: Option<String>,
2232 }
2333
34+/// The owner im writes on its own row, registered from `issuer` on every
35+/// boot — not a client id, because im is nobody's client.
36+pub const SELF_OWNER: &str = "im";
37+
2438 /// The form-level rules every stored row obeys: a key of lowercase ASCII
2539 /// letters, digits, and dashes; a non-empty name; an absolute http(s) URL.
2640 /// 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
4963 if authority.is_empty() {
5064 return Err(format!("url {url:?} must name a host"));
5165 }
52- if trimmed
53- .chars()
54- .any(|c| c.is_whitespace() || c.is_control())
55- {
66+ if trimmed.chars().any(|c| c.is_whitespace() || c.is_control()) {
5667 return Err(format!(
5768 "url {url:?} must not carry spaces or control characters"
5869 ));
@@ -73,7 +84,7 @@ pub async fn list(store: &Store) -> Result<Vec<Service>> {
7384 let conn = store.conn.lock().await;
7485 let mut rows = conn
7586 .query(
76- "SELECT key, name, url FROM services ORDER BY position, key",
87+ "SELECT key, name, url, owner FROM services ORDER BY position, key",
7788 (),
7889 )
7990 .await
@@ -84,6 +95,7 @@ pub async fn list(store: &Store) -> Result<Vec<Service>> {
8495 key: store::text(&row, 0)?,
8596 name: store::text(&row, 1)?,
8697 url: store::text(&row, 2)?,
98+ owner: store::opt_text(&row, 3)?,
8799 });
88100 }
89101 Ok(services)
@@ -123,9 +135,20 @@ pub async fn add(store: &Store, service: &Service) -> Result<()> {
123135 /// Rewrites a service's name and address. The key travels in the form's
124136 /// hidden field and is not editable; a key not on the list is refused, so a
125137 /// form posted against a since-removed row cannot resurrect it.
138+/// A row an app keeps only takes its new name here: the address is the
139+/// app's own, rewritten on its every boot, so accepting one from the panel
140+/// would show an edit the next boot silently undoes.
126141 pub async fn edit(store: &Store, key: &str, name: &str, url: &str) -> Result<()> {
127142 validate(key, name, url).map_err(StoreError::Invalid)?;
128143 let url = url.trim_end_matches('/');
144+ if let Some(row) = owned_row(store, key).await?
145+ && row.1.is_some()
146+ && row.0 != url
147+ {
148+ return Err(StoreError::Invalid(format!(
149+ "service {key:?} keeps its own address; its app re-registers it on every boot"
150+ )));
151+ }
129152 let conn = store.conn.lock().await;
130153 let updated = conn
131154 .execute(
@@ -143,7 +166,14 @@ pub async fn edit(store: &Store, key: &str, name: &str, url: &str) -> Result<()>
143166 /// Takes a service off the list and closes the gap: every later row slides
144167 /// down one, so positions stay contiguous and the next add appends cleanly.
145168 /// A key not on the list is a no-op — the panel only offers existing rows.
169+/// A row an app keeps is not the panel's to take: it would come back on the
170+/// app's next boot.
146171 pub async fn remove(store: &Store, key: &str) -> Result<()> {
172+ if let Some((_, Some(_))) = owned_row(store, key).await? {
173+ return Err(StoreError::Invalid(format!(
174+ "service {key:?} is kept by its app; it re-registers on every boot"
175+ )));
176+ }
147177 let conn = store.conn.lock().await;
148178 let mut rows = conn
149179 .query(
@@ -157,12 +187,9 @@ pub async fn remove(store: &Store, key: &str) -> Result<()> {
157187 };
158188 let position = store::int(&row, 0)?;
159189 drop(rows);
160- conn.execute(
161- "DELETE FROM services WHERE key = ?1",
162- turso::params![key],
163- )
164- .await
165- .map_err(backend)?;
190+ conn.execute("DELETE FROM services WHERE key = ?1", turso::params![key])
191+ .await
192+ .map_err(backend)?;
166193 conn.execute(
167194 "UPDATE services SET position = position - 1 WHERE position > ?1",
168195 turso::params![position],
@@ -226,6 +253,73 @@ pub async fn move_service(store: &Store, key: &str, up: bool) -> Result<()> {
226253 Ok(())
227254 }
228255
256+/// A row's stored `(url, owner)`, or `None` when no row carries the key.
257+async fn owned_row(store: &Store, key: &str) -> Result<Option<(String, Option<String>)>> {
258+ let conn = store.conn.lock().await;
259+ let mut rows = conn
260+ .query(
261+ "SELECT url, owner FROM services WHERE key = ?1",
262+ turso::params![key],
263+ )
264+ .await
265+ .map_err(backend)?;
266+ let Some(row) = rows.next().await.map_err(backend)? else {
267+ return Ok(None);
268+ };
269+ Ok(Some((store::text(&row, 0)?, store::opt_text(&row, 1)?)))
270+}
271+
272+/// An app writing its own row: im from its `issuer` on every boot, a sibling
273+/// over `POST /family/register` with its client id as the `owner`. A key
274+/// nobody holds is appended (or claimed, keeping the name the seed or the
275+/// panel gave it); a key the caller already holds takes the new address
276+/// only — the name is the admin's after the first insert. A key another app
277+/// keeps is a conflict, never a takeover.
278+pub async fn register(
279+ store: &Store,
280+ key: &str,
281+ name: &str,
282+ url: &str,
283+ owner: &str,
284+) -> Result<Service> {
285+ validate(key, name, url).map_err(StoreError::Invalid)?;
286+ let url = url.trim_end_matches('/').to_string();
287+ match owned_row(store, key).await? {
288+ Some((_, Some(held))) if held != owner => {
289+ return Err(StoreError::Conflict(format!(
290+ "service key {key:?} belongs to another app"
291+ )));
292+ }
293+ Some(_) => {
294+ // Claiming an unowned row or refreshing our own: the address is
295+ // the app's to say, the name stays whatever is stored.
296+ let conn = store.conn.lock().await;
297+ conn.execute(
298+ "UPDATE services SET url = ?2, owner = ?3 WHERE key = ?1",
299+ turso::params![key, url.as_str(), owner],
300+ )
301+ .await
302+ .map_err(backend)?;
303+ }
304+ None => {
305+ let conn = store.conn.lock().await;
306+ conn.execute(
307+ "INSERT INTO services (key, name, url, position, owner) \
308+ VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(position), -1) + 1 FROM services), ?4)",
309+ turso::params![key, name.trim(), url.as_str(), owner],
310+ )
311+ .await
312+ .map_err(backend)?;
313+ }
314+ }
315+ let row = list(store)
316+ .await?
317+ .into_iter()
318+ .find(|service| service.key == key)
319+ .ok_or_else(|| StoreError::Backend(format!("service {key:?} vanished after its write")))?;
320+ Ok(row)
321+}
322+
229323 /// The one-time seed: a database with no services yet takes the config's
230324 /// list as the starting rows, in the order the file names them. After that
231325 /// the panel owns the list and the same config is ignored — the `false`
@@ -269,11 +363,17 @@ mod tests {
269363 key: key.to_string(),
270364 name: name.to_string(),
271365 url: url.to_string(),
366+ owner: None,
272367 }
273368 }
274369
275370 async fn keys(store: &Store) -> Vec<String> {
276- list(store).await.unwrap().into_iter().map(|s| s.key).collect()
371+ list(store)
372+ .await
373+ .unwrap()
374+ .into_iter()
375+ .map(|s| s.key)
376+ .collect()
277377 }
278378
279379 #[tokio::test]
@@ -299,12 +399,9 @@ mod tests {
299399 #[tokio::test]
300400 async fn add_appends_edit_rewrites_and_a_taken_key_is_refused() {
301401 let store = store().await;
302- seed_from(
303- &store,
304- &[service("im", "Account", "http://127.0.0.1:7650")],
305- )
306- .await
307- .unwrap();
402+ seed_from(&store, &[service("im", "Account", "http://127.0.0.1:7650")])
403+ .await
404+ .unwrap();
308405 add(&store, &service("in", "Files", "http://127.0.0.1:7655"))
309406 .await
310407 .unwrap();
@@ -375,7 +472,9 @@ mod tests {
375472 .unwrap();
376473 remove(&store, "im").await.unwrap();
377474 remove(&store, "im").await.unwrap(); // already gone: a no-op
378- add(&store, &service("wiki", "Wiki", "http://wiki")).await.unwrap();
475+ add(&store, &service("wiki", "Wiki", "http://wiki"))
476+ .await
477+ .unwrap();
379478 assert_eq!(
380479 keys(&store).await,
381480 vec!["in".to_string(), "iz".to_string(), "wiki".to_string()]
@@ -385,13 +484,126 @@ mod tests {
385484 #[tokio::test]
386485 async fn the_value_rules_refuse_garbage_before_the_database_sees_it() {
387486 assert!(validate("in", "Files", "http://in.example").is_ok());
388- assert!(validate("In", "Files", "http://in.example").is_err(), "uppercase key");
389- assert!(validate("in!", "Files", "http://in.example").is_err(), "punctuated key");
390- assert!(validate("in", " ", "http://in.example").is_err(), "blank name");
391- assert!(validate("in", "Files", "ftp://in.example").is_err(), "non-http url");
487+ assert!(
488+ validate("In", "Files", "http://in.example").is_err(),
489+ "uppercase key"
490+ );
491+ assert!(
492+ validate("in!", "Files", "http://in.example").is_err(),
493+ "punctuated key"
494+ );
495+ assert!(
496+ validate("in", " ", "http://in.example").is_err(),
497+ "blank name"
498+ );
499+ assert!(
500+ validate("in", "Files", "ftp://in.example").is_err(),
501+ "non-http url"
502+ );
392503 assert!(validate("in", "Files", "http://").is_err(), "hostless url");
393- assert!(validate("in", "Files", "http://in.example/path x").is_err(), "space in url");
504+ assert!(
505+ validate("in", "Files", "http://in.example/path x").is_err(),
506+ "space in url"
507+ );
394508 // A trailing slash is not garbage — it is normalized away.
395509 assert!(validate("in", "Files", "http://in.example/").is_ok());
396510 }
511+
512+ #[tokio::test]
513+ async fn an_app_registers_itself_appending_then_claiming_then_refreshing() {
514+ let store = store().await;
515+ // Nothing on the list yet: the app's own row is appended.
516+ let row = register(
517+ &store,
518+ "im",
519+ "Account",
520+ "http://127.0.0.1:7650/",
521+ SELF_OWNER,
522+ )
523+ .await
524+ .unwrap();
525+ assert_eq!(
526+ row.url, "http://127.0.0.1:7650",
527+ "the slash is normalized off"
528+ );
529+ assert_eq!(row.owner.as_deref(), Some(SELF_OWNER));
530+
531+ // A seeded row belongs to nobody; the app that names it claims it,
532+ // keeping the name the seed (or a later rename) gave it.
533+ add(&store, &service("in", "Dosyalar", "http://127.0.0.1:7655"))
534+ .await
535+ .unwrap();
536+ let row = register(&store, "in", "Files", "https://in.example", "in-client")
537+ .await
538+ .unwrap();
539+ assert_eq!(row.name, "Dosyalar", "the name stays the admin's");
540+ assert_eq!(row.url, "https://in.example");
541+ assert_eq!(row.owner.as_deref(), Some("in-client"));
542+
543+ // The same app's next boot moves the address only.
544+ let row = register(&store, "in", "Whatever", "https://in.dizey.sh", "in-client")
545+ .await
546+ .unwrap();
547+ assert_eq!(row.name, "Dosyalar");
548+ assert_eq!(row.url, "https://in.dizey.sh");
549+ // And no row was duplicated by any of it.
550+ assert_eq!(keys(&store).await, vec!["im".to_string(), "in".to_string()]);
551+ }
552+
553+ #[tokio::test]
554+ async fn a_key_another_app_keeps_is_a_conflict_and_the_row_is_untouched() {
555+ let store = store().await;
556+ register(&store, "in", "Files", "https://in.example", "in-client")
557+ .await
558+ .unwrap();
559+ assert!(matches!(
560+ register(&store, "in", "Files", "https://evil.example", "iz-client").await,
561+ Err(StoreError::Conflict(_))
562+ ));
563+ assert_eq!(list(&store).await.unwrap()[0].url, "https://in.example");
564+ }
565+
566+ #[tokio::test]
567+ async fn the_panel_cannot_remove_an_owned_row_or_move_its_address() {
568+ let store = store().await;
569+ register(&store, "in", "Files", "https://in.example", "in-client")
570+ .await
571+ .unwrap();
572+ assert!(matches!(
573+ remove(&store, "in").await,
574+ Err(StoreError::Invalid(_))
575+ ));
576+ assert!(matches!(
577+ edit(&store, "in", "Dosyalar", "https://elsewhere.example").await,
578+ Err(StoreError::Invalid(_))
579+ ));
580+ // The name is still the admin's, and a name-only edit lands.
581+ edit(&store, "in", "Dosyalar", "https://in.example")
582+ .await
583+ .unwrap();
584+ let row = &list(&store).await.unwrap()[0];
585+ assert_eq!(row.name, "Dosyalar");
586+ assert_eq!(row.url, "https://in.example");
587+ // An unowned row is still the panel's to take.
588+ add(&store, &service("wiki", "Wiki", "http://wiki"))
589+ .await
590+ .unwrap();
591+ remove(&store, "wiki").await.unwrap();
592+ assert_eq!(keys(&store).await, vec!["in".to_string()]);
593+ }
594+
595+ #[tokio::test]
596+ async fn the_family_json_never_carries_the_owner() {
597+ let store = store().await;
598+ register(&store, "im", "Account", "http://127.0.0.1:7650", SELF_OWNER)
599+ .await
600+ .unwrap();
601+ let json = serde_json::to_value(list(&store).await.unwrap()).unwrap();
602+ let row = &json.as_array().unwrap()[0];
603+ assert_eq!(
604+ row.as_object().unwrap().keys().collect::<Vec<_>>(),
605+ vec!["key", "name", "url"],
606+ "the sibling mirrors deserialize this shape: {json}"
607+ );
608+ }
397609 }
crates/im-core/src/store.rsmodified+20 -4
@@ -21,6 +21,10 @@ pub enum StoreError {
2121 /// caller turns it into the page's refusal, never a database problem.
2222 #[error("{0}")]
2323 Invalid(String),
24+ /// The write is well-formed but the row belongs to someone else — the
25+ /// web layer answers 409, not 400.
26+ #[error("{0}")]
27+ Conflict(String),
2428 }
2529
2630 pub type Result<T, E = StoreError> = std::result::Result<T, E>;
@@ -135,7 +139,8 @@ CREATE TABLE IF NOT EXISTS services (
135139 key TEXT PRIMARY KEY,
136140 name TEXT NOT NULL,
137141 url TEXT NOT NULL,
138- position INTEGER NOT NULL
142+ position INTEGER NOT NULL,
143+ owner TEXT
139144 );
140145 ";
141146
@@ -207,9 +212,12 @@ impl Store {
207212 // born before these columns grow them here — TEXT NOT NULL with
208213 // a DEFAULT so every existing row reads the default.
209214 if !has_column(&conn, "users", "theme").await? {
210- conn.execute("ALTER TABLE users ADD COLUMN theme TEXT NOT NULL DEFAULT 'light'", ())
211- .await
212- .map_err(backend)?;
215+ conn.execute(
216+ "ALTER TABLE users ADD COLUMN theme TEXT NOT NULL DEFAULT 'light'",
217+ (),
218+ )
219+ .await
220+ .map_err(backend)?;
213221 }
214222 if !has_column(&conn, "users", "language").await? {
215223 conn.execute(
@@ -229,6 +237,14 @@ impl Store {
229237 }
230238 // What a session remembers about its browser: the listing shows
231239 // these, so old databases grow them the same guarded way.
240+ // The app that keeps a service row: `im` for this app's own
241+ // entry, a client id for a sibling that registers itself, NULL
242+ // for the config seed's and the panel's own rows.
243+ if !has_column(&conn, "services", "owner").await? {
244+ conn.execute("ALTER TABLE services ADD COLUMN owner TEXT", ())
245+ .await
246+ .map_err(backend)?;
247+ }
232248 if !has_column(&conn, "sessions", "ip").await? {
233249 conn.execute("ALTER TABLE sessions ADD COLUMN ip TEXT", ())
234250 .await
crates/im-web/src/admin.rsmodified+46 -17
@@ -420,17 +420,35 @@ async fn services_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::
420420 let key = escape(&service.key);
421421 let name = escape(&service.name);
422422 let url = escape(&service.url);
423- // The edit disclosure: the opened pop carries the name-and-address
424- // form; the key travels hidden, like every row's write.
423+ // A row its app keeps: the address is written on that app's every
424+ // boot, so the panel neither edits it nor takes the row away — the
425+ // name and the order stay the admin's.
426+ let kept = service.owner.is_some();
427+ // The edit disclosure: the opened pop carries the name (and, on an
428+ // unkept row, the address); the key travels hidden, like every
429+ // row's write.
430+ // A kept row posts the stored address back in a hidden field: the
431+ // form's name change is accepted, and the store refuses only a
432+ // *changed* address.
433+ let address_field = if kept {
434+ format!(
435+ r#"<input type="hidden" name="url" value="{url}">"#,
436+ url = url
437+ )
438+ } else {
439+ format!(
440+ r#"<label class="auth-field"><span class="auth-label">{url_label}</span><input class="auth-input auth-input-mono" type="text" name="url" value="{url}" required></label>"#,
441+ url_label = t(lang, Key::AddressLabel),
442+ url = url,
443+ )
444+ };
425445 let edit = format!(
426- r#"<details class="admin-confirm"><summary class="admin-action">{edit_word}</summary><div class="admin-confirm-pop"><div class="admin-confirm-title">{edit_title}</div><form method="post" action="/admin/services_edit" class="admin-form"><input type="hidden" name="key" value="{key}"><label class="auth-field"><span class="auth-label">{name_label}</span><input class="auth-input auth-input-mono" type="text" name="name" value="{name}" required></label><label class="auth-field"><span class="auth-label">{url_label}</span><input class="auth-input auth-input-mono" type="text" name="url" value="{url}" required></label><button class="admin-action" type="submit">{save}</button></form></div></details>"#,
446+ r#"<details class="admin-confirm"><summary class="admin-action">{edit_word}</summary><div class="admin-confirm-pop"><div class="admin-confirm-title">{edit_title}</div><form method="post" action="/admin/services_edit" class="admin-form"><input type="hidden" name="key" value="{key}"><label class="auth-field"><span class="auth-label">{name_label}</span><input class="auth-input auth-input-mono" type="text" name="name" value="{name}" required></label>{address_field}<button class="admin-action" type="submit">{save}</button></form></div></details>"#,
427447 edit_word = t(lang, Key::EditWord),
428448 edit_title = i18n::edit_service_title(lang, &name),
429449 key = key,
430450 name = name,
431- url = url,
432451 name_label = t(lang, Key::NameCol),
433- url_label = t(lang, Key::AddressLabel),
434452 save = t(lang, Key::SaveButton),
435453 );
436454 let up = format!(
@@ -443,16 +461,23 @@ async fn services_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::
443461 key = key,
444462 down_label = t(lang, Key::ServiceMoveDown),
445463 );
446- let remove = confirm_action(
447- "key",
448- &key,
449- "/admin/services_remove",
450- t(lang, Key::Remove),
451- " admin-danger",
452- &i18n::remove_service_title(lang, &name),
453- t(lang, Key::RemoveCost),
454- t(lang, Key::ConfirmRemove),
455- );
464+ let remove = if kept {
465+ format!(
466+ r#"<span class="muted">{kept_word}</span>"#,
467+ kept_word = t(lang, Key::ServiceKept),
468+ )
469+ } else {
470+ confirm_action(
471+ "key",
472+ &key,
473+ "/admin/services_remove",
474+ t(lang, Key::Remove),
475+ " admin-danger",
476+ &i18n::remove_service_title(lang, &name),
477+ t(lang, Key::RemoveCost),
478+ t(lang, Key::ConfirmRemove),
479+ )
480+ };
456481 rows.push_str(&format!(
457482 r#"<tr><td class="mono">{key}</td><td>{name}</td><td class="mono">{url}</td><td class="actions">{edit}{up}{down}{remove}</td></tr>"#,
458483 ));
@@ -502,6 +527,7 @@ async fn services_add(cx: &Cx, Form(input): Form<ServiceForm>) -> Result<Respons
502527 key: input.key,
503528 name: input.name,
504529 url: input.url,
530+ owner: None,
505531 },
506532 )
507533 .await;
@@ -514,7 +540,8 @@ async fn services_edit(cx: &Cx, Form(input): Form<ServiceForm>) -> Result<Respon
514540 Ok(me) => me,
515541 Err(redirect) => return Ok(redirect),
516542 };
517- let outcome = im_core::services::edit(&app(cx).store, &input.key, &input.name, &input.url).await;
543+ let outcome =
544+ im_core::services::edit(&app(cx).store, &input.key, &input.name, &input.url).await;
518545 service_outcome(cx, &me, outcome).await
519546 }
520547
@@ -569,7 +596,9 @@ async fn service_outcome(
569596 server::log_event(cx, "services_updated", Some(&me.email), None).await;
570597 back(cx, "services", "&ok=services")
571598 }
572- Err(im_core::store::StoreError::Invalid(_)) => back(cx, "services", "&error=bad_service"),
599+ Err(im_core::store::StoreError::Invalid(_) | im_core::store::StoreError::Conflict(_)) => {
600+ back(cx, "services", "&error=bad_service")
601+ }
573602 Err(e) => Err(e.into()),
574603 }
575604 }
crates/im-web/src/directory.rsmodified+249 -7
@@ -53,7 +53,9 @@ async fn directory(cx: &Cx) -> topcoat::Result<topcoat::router::response::Respon
5353 /// name, and base URL, in the stored order, as a bare JSON array. Registered
5454 /// apps only, exactly like `/directory`: a sibling copies this into its own
5555 /// database and renders its switcher from that copy, so the family list has
56-/// one home (the admin panel here) and every other surface a cached mirror.
56+/// one home (this table) and every other surface a cached mirror. The rows
57+/// come from the panel and from the apps themselves — see
58+/// `POST /family/register`.
5759 #[route(GET "/family")]
5860 async fn family(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
5961 if !server::valid_app(cx).await {
@@ -68,6 +70,49 @@ async fn family(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response>
6870 Json(serde_json::to_value(services).unwrap()).into_response(cx)
6971 }
7072
73+/// The body a sibling posts to keep its own row: its wordmark key, the
74+/// name a fresh row is born with, and the address it answers on now.
75+#[derive(serde::Deserialize)]
76+struct Registration {
77+ key: String,
78+ name: String,
79+ url: String,
80+}
81+
82+/// `POST /family/register`: an app writes its own row of the family. Same
83+/// Basic pair as `/family`, and the authenticated client id is the owner —
84+/// so a row an app keeps is refreshed on its every boot, never taken over
85+/// by another app (409) and no longer the panel's to remove or re-point.
86+#[route(POST "/family/register")]
87+async fn family_register(
88+ cx: &Cx,
89+ Json(input): Json<Registration>,
90+) -> topcoat::Result<topcoat::router::response::Response> {
91+ let Some(client_id) = server::app_client(cx).await else {
92+ return (
93+ StatusCode::UNAUTHORIZED,
94+ Json(serde_json::json!({ "error": "invalid_client" })),
95+ )
96+ .into_response(cx);
97+ };
98+ let store = server::app(cx).store.clone();
99+ match im_core::services::register(&store, &input.key, &input.name, &input.url, &client_id).await
100+ {
101+ Ok(service) => Json(serde_json::to_value(service).unwrap()).into_response(cx),
102+ Err(im_core::store::StoreError::Conflict(_)) => (
103+ StatusCode::CONFLICT,
104+ Json(serde_json::json!({ "error": "owned" })),
105+ )
106+ .into_response(cx),
107+ Err(im_core::store::StoreError::Invalid(reason)) => (
108+ StatusCode::BAD_REQUEST,
109+ Json(serde_json::json!({ "error": "invalid", "reason": reason })),
110+ )
111+ .into_response(cx),
112+ Err(e) => Err(e.into()),
113+ }
114+}
115+
71116 #[cfg(test)]
72117 mod tests {
73118 use std::path::Path;
@@ -245,6 +290,7 @@ mod tests {
245290 key: service.key.clone(),
246291 name: service.name.clone(),
247292 url: service.url.clone(),
293+ owner: None,
248294 })
249295 .collect()
250296 }
@@ -312,6 +358,29 @@ mod tests {
312358 (parts.status, String::from_utf8(bytes).unwrap())
313359 }
314360
361+ /// `POST /family/register` with a JSON body and (maybe) an app's pair.
362+ async fn post_register(
363+ router: &Router,
364+ authorization: Option<String>,
365+ body: serde_json::Value,
366+ ) -> (StatusCode, serde_json::Value) {
367+ let mut builder = http::Request::builder()
368+ .method(http::Method::POST)
369+ .uri("/family/register")
370+ .header(header::CONTENT_TYPE, "application/json");
371+ if let Some(value) = authorization {
372+ builder = builder.header(header::AUTHORIZATION, value);
373+ }
374+ let response = router
375+ .handle(builder.body(Body::from(body.to_string())).unwrap())
376+ .await;
377+ let (parts, body) = response.into_parts();
378+ let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec();
379+ let text = String::from_utf8(bytes).unwrap();
380+ let json = serde_json::from_str(&text).unwrap_or(serde_json::Value::String(text));
381+ (parts.status, json)
382+ }
383+
315384 /// A page GET as a signed-in browser: the whole document back.
316385 async fn get_page(router: &Router, uri: &str, cookie: &str) -> String {
317386 let response = router
@@ -528,7 +597,10 @@ mod tests {
528597 )
529598 .await;
530599 assert_eq!(status, StatusCode::SEE_OTHER);
531- assert_eq!(location.as_deref(), Some("/admin?section=services&ok=services"));
600+ assert_eq!(
601+ location.as_deref(),
602+ Some("/admin?section=services&ok=services")
603+ );
532604 let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await;
533605 let family = serde_json::from_str::<serde_json::Value>(&body).unwrap();
534606 let family = family.as_array().unwrap();
@@ -567,10 +639,21 @@ mod tests {
567639 Some(&cookie),
568640 )
569641 .await;
570- assert_eq!(location.as_deref(), Some("/admin?section=services&ok=services"));
571- let (_status, location, _) =
572- post_form(&router, "/admin/services_move", "key=wiki&dir=up", Some(&cookie)).await;
573- assert_eq!(location.as_deref(), Some("/admin?section=services&ok=services"));
642+ assert_eq!(
643+ location.as_deref(),
644+ Some("/admin?section=services&ok=services")
645+ );
646+ let (_status, location, _) = post_form(
647+ &router,
648+ "/admin/services_move",
649+ "key=wiki&dir=up",
650+ Some(&cookie),
651+ )
652+ .await;
653+ assert_eq!(
654+ location.as_deref(),
655+ Some("/admin?section=services&ok=services")
656+ );
574657 let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await;
575658 let family = serde_json::from_str::<serde_json::Value>(&body).unwrap();
576659 let family = family.as_array().unwrap();
@@ -599,7 +682,10 @@ mod tests {
599682 // And once the row is gone, the same origin is refused to the door.
600683 let (_status, location, _) =
601684 post_form(&router, "/admin/services_remove", "key=wiki", Some(&cookie)).await;
602- assert_eq!(location.as_deref(), Some("/admin?section=services&ok=services"));
685+ assert_eq!(
686+ location.as_deref(),
687+ Some("/admin?section=services&ok=services")
688+ );
603689 let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await;
604690 let family = serde_json::from_str::<serde_json::Value>(&body).unwrap();
605691 let keys = family
@@ -661,6 +747,7 @@ mod tests {
661747 key: "in".into(),
662748 name: "Files".into(),
663749 url: "http://127.0.0.1:7655".into(),
750+ owner: None,
664751 }];
665752 assert!(!im_core::services::seed_from(&store, &reseed).await.unwrap());
666753 let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await;
@@ -674,4 +761,159 @@ mod tests {
674761 "{body}"
675762 );
676763 }
764+
765+ #[tokio::test]
766+ async fn an_app_registers_its_own_row_and_only_its_own() {
767+ let Setup {
768+ router,
769+ client_id,
770+ secret,
771+ store,
772+ } = setup().await;
773+
774+ // No pair, no write.
775+ let (status, body) = post_register(
776+ &router,
777+ None,
778+ serde_json::json!({"key": "wiki", "name": "Wiki", "url": "http://wiki.example"}),
779+ )
780+ .await;
781+ assert_eq!(status, StatusCode::UNAUTHORIZED);
782+ assert_eq!(body["error"], "invalid_client");
783+
784+ // A fresh key is appended, and /family carries it right away.
785+ let (status, body) = post_register(
786+ &router,
787+ Some(basic(&client_id, &secret)),
788+ serde_json::json!({"key": "wiki", "name": "Wiki", "url": "http://wiki.example/"}),
789+ )
790+ .await;
791+ assert_eq!(status, StatusCode::OK, "{body}");
792+ assert_eq!(body["url"], "http://wiki.example");
793+ assert!(
794+ body.get("owner").is_none(),
795+ "the owner never leaves: {body}"
796+ );
797+ let (_, listed) = get_family(&router, Some(basic(&client_id, &secret))).await;
798+ let listed = serde_json::from_str::<serde_json::Value>(&listed).unwrap();
799+ let keys = listed
800+ .as_array()
801+ .unwrap()
802+ .iter()
803+ .map(|s| s["key"].as_str().unwrap())
804+ .collect::<Vec<_>>();
805+ assert_eq!(keys, vec!["in", "im", "iz", "wiki"]);
806+
807+ // A second app cannot take the key over.
808+ let (other_id, other_secret) =
809+ create_client(&store, "other", vec!["http://other/callback".into()])
810+ .await
811+ .unwrap();
812+ let (status, body) = post_register(
813+ &router,
814+ Some(basic(&other_id.to_string(), other_secret.expose())),
815+ serde_json::json!({"key": "wiki", "name": "Mine", "url": "http://evil.example"}),
816+ )
817+ .await;
818+ assert_eq!(status, StatusCode::CONFLICT);
819+ assert_eq!(body["error"], "owned");
820+
821+ // The keeper's next boot moves the address; the name is the panel's.
822+ im_core::services::edit(&store, "wiki", "Vikipedi", "http://wiki.example")
823+ .await
824+ .unwrap();
825+ let (status, body) = post_register(
826+ &router,
827+ Some(basic(&client_id, &secret)),
828+ serde_json::json!({"key": "wiki", "name": "Wiki", "url": "http://wiki.dizey.sh"}),
829+ )
830+ .await;
831+ assert_eq!(status, StatusCode::OK);
832+ assert_eq!(body["name"], "Vikipedi");
833+ assert_eq!(body["url"], "http://wiki.dizey.sh");
834+
835+ // A value against the rules is a 400 with the store's own reason.
836+ let (status, body) = post_register(
837+ &router,
838+ Some(basic(&client_id, &secret)),
839+ serde_json::json!({"key": "wiki", "name": "Wiki", "url": "ftp://wiki.example"}),
840+ )
841+ .await;
842+ assert_eq!(status, StatusCode::BAD_REQUEST);
843+ assert_eq!(body["error"], "invalid");
844+ assert!(body["reason"].as_str().unwrap().contains("http"), "{body}");
845+ }
846+
847+ #[tokio::test]
848+ async fn the_panel_cannot_remove_a_row_its_app_keeps() {
849+ let Setup {
850+ router,
851+ client_id,
852+ secret,
853+ store,
854+ } = setup().await;
855+ let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
856+ .await
857+ .unwrap()
858+ .unwrap();
859+ let session = im_core::sessions::create_session(&store, &ada.id, &Default::default())
860+ .await
861+ .unwrap();
862+ let cookie = format!("{SESSION_COOKIE}={}", session.expose());
863+
864+ // The app claims the seeded `in` row.
865+ let (status, _) = post_register(
866+ &router,
867+ Some(basic(&client_id, &secret)),
868+ serde_json::json!({"key": "in", "name": "Files", "url": "https://in.dizey.sh"}),
869+ )
870+ .await;
871+ assert_eq!(status, StatusCode::OK);
872+
873+ // The panel's remove is refused and the row stays.
874+ let (_status, location, _) =
875+ post_form(&router, "/admin/services_remove", "key=in", Some(&cookie)).await;
876+ assert_eq!(
877+ location.as_deref(),
878+ Some("/admin?section=services&error=bad_service")
879+ );
880+ // So is a re-point; a rename still lands.
881+ let (_status, location, _) = post_form(
882+ &router,
883+ "/admin/services_edit",
884+ "key=in&name=Dosyalar&url=http%3A%2F%2Felsewhere.example",
885+ Some(&cookie),
886+ )
887+ .await;
888+ assert_eq!(
889+ location.as_deref(),
890+ Some("/admin?section=services&error=bad_service")
891+ );
892+ let (_status, location, _) = post_form(
893+ &router,
894+ "/admin/services_edit",
895+ "key=in&name=Dosyalar&url=https%3A%2F%2Fin.dizey.sh",
896+ Some(&cookie),
897+ )
898+ .await;
899+ assert_eq!(
900+ location.as_deref(),
901+ Some("/admin?section=services&ok=services")
902+ );
903+ let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await;
904+ let family = serde_json::from_str::<serde_json::Value>(&body).unwrap();
905+ assert_eq!(family[0]["key"], "in");
906+ assert_eq!(family[0]["name"], "Dosyalar");
907+ assert_eq!(family[0]["url"], "https://in.dizey.sh");
908+
909+ // And the panel offers no remove form for it — the marker instead.
910+ let panel = get_page(&router, "/admin?section=services", &cookie).await;
911+ assert!(panel.contains("kept by the app"), "the marker is missing");
912+ assert!(
913+ !panel.contains(r#"value="in"><button class="admin-action admin-danger"#),
914+ "an owned row must carry no remove form"
915+ );
916+ // The unowned rows still do.
917+ assert!(panel.contains(r#"action="/admin/services_remove""#));
918+ }
677919 }
crates/im-web/src/i18n.rsmodified+3 -0
@@ -130,6 +130,7 @@ pub enum Key {
130130 ServicesTitle,
131131 ServiceKeyLabel,
132132 ServiceAdd,
133+ ServiceKept,
133134 ServiceMoveUp,
134135 ServiceMoveDown,
135136 SignOutEverywhere,
@@ -470,6 +471,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
470471 (ServiceKeyLabel, Tr) => "Anahtar",
471472 (ServiceAdd, En) => "Add service",
472473 (ServiceAdd, Tr) => "Hizmet ekle",
474+ (ServiceKept, En) => "kept by the app",
475+ (ServiceKept, Tr) => "uygulaması koruyor",
473476 (ServiceMoveUp, En) => "Move up",
474477 (ServiceMoveUp, Tr) => "Yukarı taşı",
475478 (ServiceMoveDown, En) => "Move down",
crates/im-web/src/main.rsmodified+24 -1
@@ -12,8 +12,8 @@ use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, route};
1212
1313 mod admin;
1414 mod auth;
15-mod directory;
1615 mod config;
16+mod directory;
1717 mod dropdown;
1818 mod i18n;
1919 mod layout;
@@ -158,6 +158,7 @@ async fn seed_services(store: &Store, config: &Config) {
158158 key: service.key.clone(),
159159 name: service.name.clone(),
160160 url: service.url.clone(),
161+ owner: None,
161162 })
162163 .collect();
163164 match im_core::services::seed_from(store, &seed).await {
@@ -170,6 +171,27 @@ async fn seed_services(store: &Store, config: &Config) {
170171 }
171172 }
172173
174+/// im's own row of the family, written on every boot from `issuer`: the
175+/// address is the running app's, not a config line someone edits once and
176+/// forgets. A seeded `im` row is claimed here (its name stays the admin's);
177+/// afterwards the panel can rename and reorder it, but not re-point or
178+/// remove it. Never a reason to refuse boot — the family is a convenience,
179+/// the sign-in is not.
180+async fn register_self(store: &Store, config: &Config) {
181+ match im_core::services::register(
182+ store,
183+ im_core::services::SELF_OWNER,
184+ "Account",
185+ &config.issuer,
186+ im_core::services::SELF_OWNER,
187+ )
188+ .await
189+ {
190+ Ok(service) => println!("im registered itself in the family at {}", service.url),
191+ Err(e) => eprintln!("im: registering itself in the family failed: {e}"),
192+ }
193+}
194+
173195 /// `im-web invite <email> [--admin]`: creates the invite, mails it when the
174196 /// panel has configured a sender, prints the link otherwise (dev mode).
175197 ///
@@ -243,6 +265,7 @@ async fn serve(config: Config) {
243265 }
244266 let store = open_store(&config).await;
245267 seed_services(&store, &config).await;
268+ register_self(&store, &config).await;
246269 let (live, _) = tokio::sync::broadcast::channel(64);
247270 // Told when the process is stopping, so the live streams end instead of
248271 // being waited out — see `live::Shutdown`.
crates/im-web/src/server.rsmodified+18 -18
@@ -175,27 +175,27 @@ pub fn opened_pending(cx: &Cx) -> Option<Pending> {
175175 /// registry. Anything unparseable, unknown, or wrong is simply false — the
176176 /// caller answers its one refusal and never says which.
177177 pub async fn valid_app(cx: &Cx) -> bool {
178+ app_client(cx).await.is_some()
179+}
180+
181+/// The same check, answering *which* app it is: the routes that write on a
182+/// caller's behalf (`/family/register`) need the client id the pair
183+/// authenticated, and the ones that only read do not.
184+pub async fn app_client(cx: &Cx) -> Option<String> {
178185 use base64::Engine as _;
179186 use topcoat::router::{header, request::headers as request_headers};
180- let Some(encoded) = request_headers(cx)
187+ let encoded = request_headers(cx)
181188 .get(header::AUTHORIZATION)
182189 .and_then(|value| value.to_str().ok())
183- .and_then(|value| value.strip_prefix("Basic "))
184- else {
185- return false;
186- };
187- let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(encoded) else {
188- return false;
189- };
190- let Ok(pair) = std::str::from_utf8(&decoded) else {
191- return false;
192- };
193- let Some((client_id, secret)) = pair.split_once(':') else {
194- return false;
195- };
190+ .and_then(|value| value.strip_prefix("Basic "))?;
191+ let decoded = base64::engine::general_purpose::STANDARD
192+ .decode(encoded)
193+ .ok()?;
194+ let pair = std::str::from_utf8(&decoded).ok()?;
195+ let (client_id, secret) = pair.split_once(':')?;
196196 let store = app(cx).store.clone();
197- let Ok(Some(client)) = im_core::oidc::client_by_id(&store, client_id).await else {
198- return false;
199- };
200- im_core::oidc::verify_client_secret(&client, secret)
197+ let client = im_core::oidc::client_by_id(&store, client_id)
198+ .await
199+ .ok()??;
200+ im_core::oidc::verify_client_secret(&client, secret).then(|| client_id.to_string())
201201 }