the family list moves into the house: a services table owns the wordmarks, seeded once from the config's [[services]] on first boot and never again, edited instead from the landing's Services card where an admin adds, renames, re-points, reorders or removes entries — members see the same card read-only; a new GET /family answers the list to registered apps behind the same basic client pair as the directory, the trio and the cards render the table, and the logout back-door now trusts only origins the table knows
Browse files at this commitcc56357dc26fb5fce2cf39e09bb460bdeaba76cbParent: b2303079 changed files +964 -35
- crates/im-core/src/lib.rs +2 -0
- crates/im-core/src/services.rs +397 -0
- crates/im-core/src/store.rs +10 -0
- crates/im-web/src/auth.rs +118 -7
- crates/im-web/src/directory.rs +314 -18
- crates/im-web/src/i18n.rs +19 -0
- crates/im-web/src/layout.rs +5 -4
- crates/im-web/src/main.rs +28 -0
- crates/im-web/src/pages.rs +71 -6
crates/im-core/src/lib.rsmodified+2 -0
| @@ -16,6 +16,8 @@ pub mod oidc; | ||
| 16 | 16 | #[cfg(feature = "server")] |
| 17 | 17 | pub mod photos; |
| 18 | 18 | #[cfg(feature = "server")] |
| 19 | +pub mod services; | |
| 20 | +#[cfg(feature = "server")] | |
| 19 | 21 | mod secret; |
| 20 | 22 | #[cfg(feature = "server")] |
| 21 | 23 | pub mod sessions; |
crates/im-core/src/services.rsadded+397 -0
| @@ -0,0 +1,397 @@ | ||
| 1 | +//! 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 landing (add, rename, reorder, remove), and served | |
| 5 | +//! to the sibling apps over `GET /family`, which each mirrors into its own | |
| 6 | +//! database. | |
| 7 | + | |
| 8 | +use serde::Serialize; | |
| 9 | + | |
| 10 | +use crate::store::{self, Result, Store, StoreError, backend}; | |
| 11 | + | |
| 12 | +/// One service of the family: the wordmark `key` ("in", "im", "iz" — or a | |
| 13 | +/// later sibling; the key rules are mechanical, not a fixed trio), the | |
| 14 | +/// human `name`, and the absolute base `url` without a trailing slash. | |
| 15 | +/// `position` is the stored order and never leaves this module — readers | |
| 16 | +/// get the list already ordered. | |
| 17 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] | |
| 18 | +pub struct Service { | |
| 19 | + pub key: String, | |
| 20 | + pub name: String, | |
| 21 | + pub url: String, | |
| 22 | +} | |
| 23 | + | |
| 24 | +/// The form-level rules every stored row obeys: a key of lowercase ASCII | |
| 25 | +/// letters, digits, and dashes; a non-empty name; an absolute http(s) URL. | |
| 26 | +/// Returns the reason a value is refused — the panel shows it as its one | |
| 27 | +/// generic refusal, the exact words stay a store matter. | |
| 28 | +pub fn validate(key: &str, name: &str, url: &str) -> std::result::Result<(), String> { | |
| 29 | + if key.is_empty() | |
| 30 | + || !key | |
| 31 | + .chars() | |
| 32 | + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') | |
| 33 | + { | |
| 34 | + return Err(format!( | |
| 35 | + "key {key:?} must be lowercase letters, digits, or dashes" | |
| 36 | + )); | |
| 37 | + } | |
| 38 | + if name.trim().is_empty() { | |
| 39 | + return Err("name must not be empty".to_string()); | |
| 40 | + } | |
| 41 | + let trimmed = url.trim_end_matches('/'); | |
| 42 | + let Some(rest) = trimmed | |
| 43 | + .strip_prefix("http://") | |
| 44 | + .or_else(|| trimmed.strip_prefix("https://")) | |
| 45 | + else { | |
| 46 | + return Err(format!("url {url:?} must be an http(s) URL")); | |
| 47 | + }; | |
| 48 | + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); | |
| 49 | + if authority.is_empty() { | |
| 50 | + return Err(format!("url {url:?} must name a host")); | |
| 51 | + } | |
| 52 | + if trimmed | |
| 53 | + .chars() | |
| 54 | + .any(|c| c.is_whitespace() || c.is_control()) | |
| 55 | + { | |
| 56 | + return Err(format!( | |
| 57 | + "url {url:?} must not carry spaces or control characters" | |
| 58 | + )); | |
| 59 | + } | |
| 60 | + Ok(()) | |
| 61 | +} | |
| 62 | + | |
| 63 | +/// The one doorway every write passes: [`validate`], with the URL in its | |
| 64 | +/// stored form — no trailing slash. | |
| 65 | +fn checked(service: &Service) -> Result<String> { | |
| 66 | + validate(&service.key, &service.name, &service.url).map_err(StoreError::Invalid)?; | |
| 67 | + Ok(service.url.trim_end_matches('/').to_string()) | |
| 68 | +} | |
| 69 | + | |
| 70 | +/// Every service, in the stored order — the one order the trio, the landing | |
| 71 | +/// cards, and `/family` all render in. | |
| 72 | +pub async fn list(store: &Store) -> Result<Vec<Service>> { | |
| 73 | + let conn = store.conn.lock().await; | |
| 74 | + let mut rows = conn | |
| 75 | + .query( | |
| 76 | + "SELECT key, name, url FROM services ORDER BY position, key", | |
| 77 | + (), | |
| 78 | + ) | |
| 79 | + .await | |
| 80 | + .map_err(backend)?; | |
| 81 | + let mut services = Vec::new(); | |
| 82 | + while let Some(row) = rows.next().await.map_err(backend)? { | |
| 83 | + services.push(Service { | |
| 84 | + key: store::text(&row, 0)?, | |
| 85 | + name: store::text(&row, 1)?, | |
| 86 | + url: store::text(&row, 2)?, | |
| 87 | + }); | |
| 88 | + } | |
| 89 | + Ok(services) | |
| 90 | +} | |
| 91 | + | |
| 92 | +/// Appends a service at the end of the family. A key already on the list is | |
| 93 | +/// refused — the add form is the only writer, and a silent overwrite would | |
| 94 | +/// surprise it. | |
| 95 | +pub async fn add(store: &Store, service: &Service) -> Result<()> { | |
| 96 | + let url = checked(service)?; | |
| 97 | + let conn = store.conn.lock().await; | |
| 98 | + let mut rows = conn | |
| 99 | + .query( | |
| 100 | + "SELECT 1 FROM services WHERE key = ?1", | |
| 101 | + turso::params![service.key.as_str()], | |
| 102 | + ) | |
| 103 | + .await | |
| 104 | + .map_err(backend)?; | |
| 105 | + let taken = rows.next().await.map_err(backend)?.is_some(); | |
| 106 | + drop(rows); | |
| 107 | + if taken { | |
| 108 | + return Err(StoreError::Invalid(format!( | |
| 109 | + "service key {:?} is already on the list", | |
| 110 | + service.key | |
| 111 | + ))); | |
| 112 | + } | |
| 113 | + conn.execute( | |
| 114 | + "INSERT INTO services (key, name, url, position) \ | |
| 115 | + VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(position), -1) + 1 FROM services))", | |
| 116 | + turso::params![service.key.as_str(), service.name.trim(), url.as_str()], | |
| 117 | + ) | |
| 118 | + .await | |
| 119 | + .map_err(backend)?; | |
| 120 | + Ok(()) | |
| 121 | +} | |
| 122 | + | |
| 123 | +/// Rewrites a service's name and address. The key travels in the form's | |
| 124 | +/// hidden field and is not editable; a key not on the list is refused, so a | |
| 125 | +/// form posted against a since-removed row cannot resurrect it. | |
| 126 | +pub async fn edit(store: &Store, key: &str, name: &str, url: &str) -> Result<()> { | |
| 127 | + validate(key, name, url).map_err(StoreError::Invalid)?; | |
| 128 | + let url = url.trim_end_matches('/'); | |
| 129 | + let conn = store.conn.lock().await; | |
| 130 | + let updated = conn | |
| 131 | + .execute( | |
| 132 | + "UPDATE services SET name = ?2, url = ?3 WHERE key = ?1", | |
| 133 | + turso::params![key, name.trim(), url], | |
| 134 | + ) | |
| 135 | + .await | |
| 136 | + .map_err(backend)?; | |
| 137 | + if updated == 0 { | |
| 138 | + return Err(StoreError::Invalid(format!("no service keyed {key:?}"))); | |
| 139 | + } | |
| 140 | + Ok(()) | |
| 141 | +} | |
| 142 | + | |
| 143 | +/// Takes a service off the list and closes the gap: every later row slides | |
| 144 | +/// down one, so positions stay contiguous and the next add appends cleanly. | |
| 145 | +/// A key not on the list is a no-op — the panel only offers existing rows. | |
| 146 | +pub async fn remove(store: &Store, key: &str) -> Result<()> { | |
| 147 | + let conn = store.conn.lock().await; | |
| 148 | + let mut rows = conn | |
| 149 | + .query( | |
| 150 | + "SELECT position FROM services WHERE key = ?1", | |
| 151 | + turso::params![key], | |
| 152 | + ) | |
| 153 | + .await | |
| 154 | + .map_err(backend)?; | |
| 155 | + let Some(row) = rows.next().await.map_err(backend)? else { | |
| 156 | + return Ok(()); | |
| 157 | + }; | |
| 158 | + let position = store::int(&row, 0)?; | |
| 159 | + drop(rows); | |
| 160 | + conn.execute( | |
| 161 | + "DELETE FROM services WHERE key = ?1", | |
| 162 | + turso::params![key], | |
| 163 | + ) | |
| 164 | + .await | |
| 165 | + .map_err(backend)?; | |
| 166 | + conn.execute( | |
| 167 | + "UPDATE services SET position = position - 1 WHERE position > ?1", | |
| 168 | + turso::params![position], | |
| 169 | + ) | |
| 170 | + .await | |
| 171 | + .map_err(backend)?; | |
| 172 | + Ok(()) | |
| 173 | +} | |
| 174 | + | |
| 175 | +/// Swaps a service one slot toward the front (`up`) or the back. An edge | |
| 176 | +/// row has no neighbor in that direction and the list is left alone. | |
| 177 | +pub async fn move_service(store: &Store, key: &str, up: bool) -> Result<()> { | |
| 178 | + let conn = store.conn.lock().await; | |
| 179 | + let mut rows = conn | |
| 180 | + .query( | |
| 181 | + "SELECT position FROM services WHERE key = ?1", | |
| 182 | + turso::params![key], | |
| 183 | + ) | |
| 184 | + .await | |
| 185 | + .map_err(backend)?; | |
| 186 | + let Some(row) = rows.next().await.map_err(backend)? else { | |
| 187 | + return Ok(()); | |
| 188 | + }; | |
| 189 | + let position = store::int(&row, 0)?; | |
| 190 | + drop(rows); | |
| 191 | + let mut neighbor = if up { | |
| 192 | + conn.query( | |
| 193 | + "SELECT key, position FROM services WHERE position < ?1 \ | |
| 194 | + ORDER BY position DESC LIMIT 1", | |
| 195 | + turso::params![position], | |
| 196 | + ) | |
| 197 | + .await | |
| 198 | + .map_err(backend)? | |
| 199 | + } else { | |
| 200 | + conn.query( | |
| 201 | + "SELECT key, position FROM services WHERE position > ?1 \ | |
| 202 | + ORDER BY position ASC LIMIT 1", | |
| 203 | + turso::params![position], | |
| 204 | + ) | |
| 205 | + .await | |
| 206 | + .map_err(backend)? | |
| 207 | + }; | |
| 208 | + let Some(row) = neighbor.next().await.map_err(backend)? else { | |
| 209 | + return Ok(()); | |
| 210 | + }; | |
| 211 | + let other_key = store::text(&row, 0)?; | |
| 212 | + let other_position = store::int(&row, 1)?; | |
| 213 | + drop(neighbor); | |
| 214 | + conn.execute( | |
| 215 | + "UPDATE services SET position = ?1 WHERE key = ?2", | |
| 216 | + turso::params![other_position, key], | |
| 217 | + ) | |
| 218 | + .await | |
| 219 | + .map_err(backend)?; | |
| 220 | + conn.execute( | |
| 221 | + "UPDATE services SET position = ?1 WHERE key = ?2", | |
| 222 | + turso::params![position, other_key], | |
| 223 | + ) | |
| 224 | + .await | |
| 225 | + .map_err(backend)?; | |
| 226 | + Ok(()) | |
| 227 | +} | |
| 228 | + | |
| 229 | +/// The one-time seed: a database with no services yet takes the config's | |
| 230 | +/// list as the starting rows, in the order the file names them. After that | |
| 231 | +/// the panel owns the list and the same config is ignored — the `false` | |
| 232 | +/// return tells the boot it did nothing. | |
| 233 | +pub async fn seed_from(store: &Store, seed: &[Service]) -> Result<bool> { | |
| 234 | + if !list(store).await?.is_empty() { | |
| 235 | + return Ok(false); | |
| 236 | + } | |
| 237 | + let conn = store.conn.lock().await; | |
| 238 | + for (position, service) in seed.iter().enumerate() { | |
| 239 | + let url = checked(service)?; | |
| 240 | + conn.execute( | |
| 241 | + "INSERT OR IGNORE INTO services (key, name, url, position) \ | |
| 242 | + VALUES (?1, ?2, ?3, ?4)", | |
| 243 | + turso::params![ | |
| 244 | + service.key.as_str(), | |
| 245 | + service.name.trim(), | |
| 246 | + url.as_str(), | |
| 247 | + position as i64 | |
| 248 | + ], | |
| 249 | + ) | |
| 250 | + .await | |
| 251 | + .map_err(backend)?; | |
| 252 | + } | |
| 253 | + Ok(true) | |
| 254 | +} | |
| 255 | + | |
| 256 | +#[cfg(test)] | |
| 257 | +mod tests { | |
| 258 | + use std::path::Path; | |
| 259 | + | |
| 260 | + use super::*; | |
| 261 | + use crate::store::StoreError; | |
| 262 | + | |
| 263 | + async fn store() -> Store { | |
| 264 | + Store::open(Path::new(":memory:")).await.unwrap() | |
| 265 | + } | |
| 266 | + | |
| 267 | + fn service(key: &str, name: &str, url: &str) -> Service { | |
| 268 | + Service { | |
| 269 | + key: key.to_string(), | |
| 270 | + name: name.to_string(), | |
| 271 | + url: url.to_string(), | |
| 272 | + } | |
| 273 | + } | |
| 274 | + | |
| 275 | + async fn keys(store: &Store) -> Vec<String> { | |
| 276 | + list(store).await.unwrap().into_iter().map(|s| s.key).collect() | |
| 277 | + } | |
| 278 | + | |
| 279 | + #[tokio::test] | |
| 280 | + async fn the_seed_fills_an_empty_table_once_and_then_hands_over() { | |
| 281 | + let store = store().await; | |
| 282 | + let seed = vec![ | |
| 283 | + service("in", "Files", "http://127.0.0.1:7655/"), | |
| 284 | + service("im", "Account", "http://127.0.0.1:7650"), | |
| 285 | + ]; | |
| 286 | + assert!(seed_from(&store, &seed).await.unwrap()); | |
| 287 | + // A trailing slash in the file is not in the table: the stored form | |
| 288 | + // is slash-free, everywhere. | |
| 289 | + assert_eq!(list(&store).await.unwrap()[0].url, "http://127.0.0.1:7655"); | |
| 290 | + // The panel renamed the first entry; a re-boot with the same config | |
| 291 | + // must not bring the old name back. | |
| 292 | + edit(&store, "in", "Renamed", "http://127.0.0.1:7655") | |
| 293 | + .await | |
| 294 | + .unwrap(); | |
| 295 | + assert!(!seed_from(&store, &seed).await.unwrap()); | |
| 296 | + assert_eq!(list(&store).await.unwrap()[0].name, "Renamed"); | |
| 297 | + } | |
| 298 | + | |
| 299 | + #[tokio::test] | |
| 300 | + async fn add_appends_edit_rewrites_and_a_taken_key_is_refused() { | |
| 301 | + let store = store().await; | |
| 302 | + seed_from( | |
| 303 | + &store, | |
| 304 | + &[service("im", "Account", "http://127.0.0.1:7650")], | |
| 305 | + ) | |
| 306 | + .await | |
| 307 | + .unwrap(); | |
| 308 | + add(&store, &service("in", "Files", "http://127.0.0.1:7655")) | |
| 309 | + .await | |
| 310 | + .unwrap(); | |
| 311 | + add(&store, &service("in", "Again", "http://elsewhere/")) | |
| 312 | + .await | |
| 313 | + .err() | |
| 314 | + .unwrap_or_else(|| panic!("a taken key must be refused")); | |
| 315 | + // The refused add changed nothing. | |
| 316 | + assert_eq!(keys(&store).await, vec!["im".to_string(), "in".to_string()]); | |
| 317 | + edit(&store, "in", "Dosyalar", "https://in.example") | |
| 318 | + .await | |
| 319 | + .unwrap(); | |
| 320 | + let services = list(&store).await.unwrap(); | |
| 321 | + assert_eq!(services[1].name, "Dosyalar"); | |
| 322 | + assert_eq!(services[1].url, "https://in.example"); | |
| 323 | + // A form posted against a since-removed key cannot resurrect it. | |
| 324 | + remove(&store, "in").await.unwrap(); | |
| 325 | + assert!(matches!( | |
| 326 | + edit(&store, "in", "Zombie", "https://in.example").await, | |
| 327 | + Err(StoreError::Invalid(_)) | |
| 328 | + )); | |
| 329 | + assert_eq!(keys(&store).await, vec!["im".to_string()]); | |
| 330 | + } | |
| 331 | + | |
| 332 | + #[tokio::test] | |
| 333 | + async fn moving_swaps_with_the_neighbor_and_edges_stay_put() { | |
| 334 | + let store = store().await; | |
| 335 | + seed_from( | |
| 336 | + &store, | |
| 337 | + &[ | |
| 338 | + service("in", "Files", "http://127.0.0.1:7655"), | |
| 339 | + service("im", "Account", "http://127.0.0.1:7650"), | |
| 340 | + service("iz", "Board", "http://127.0.0.1:7654"), | |
| 341 | + ], | |
| 342 | + ) | |
| 343 | + .await | |
| 344 | + .unwrap(); | |
| 345 | + move_service(&store, "iz", true).await.unwrap(); | |
| 346 | + assert_eq!( | |
| 347 | + keys(&store).await, | |
| 348 | + vec!["in".to_string(), "iz".to_string(), "im".to_string()] | |
| 349 | + ); | |
| 350 | + // The front edge has nothing above it; the list does not move. | |
| 351 | + move_service(&store, "in", true).await.unwrap(); | |
| 352 | + assert_eq!( | |
| 353 | + keys(&store).await, | |
| 354 | + vec!["in".to_string(), "iz".to_string(), "im".to_string()] | |
| 355 | + ); | |
| 356 | + move_service(&store, "in", false).await.unwrap(); | |
| 357 | + assert_eq!( | |
| 358 | + keys(&store).await, | |
| 359 | + vec!["iz".to_string(), "in".to_string(), "im".to_string()] | |
| 360 | + ); | |
| 361 | + } | |
| 362 | + | |
| 363 | + #[tokio::test] | |
| 364 | + async fn removing_closes_the_gap_so_the_next_add_appends_last() { | |
| 365 | + let store = store().await; | |
| 366 | + seed_from( | |
| 367 | + &store, | |
| 368 | + &[ | |
| 369 | + service("in", "Files", "http://127.0.0.1:7655"), | |
| 370 | + service("im", "Account", "http://127.0.0.1:7650"), | |
| 371 | + service("iz", "Board", "http://127.0.0.1:7654"), | |
| 372 | + ], | |
| 373 | + ) | |
| 374 | + .await | |
| 375 | + .unwrap(); | |
| 376 | + remove(&store, "im").await.unwrap(); | |
| 377 | + remove(&store, "im").await.unwrap(); // already gone: a no-op | |
| 378 | + add(&store, &service("wiki", "Wiki", "http://wiki")).await.unwrap(); | |
| 379 | + assert_eq!( | |
| 380 | + keys(&store).await, | |
| 381 | + vec!["in".to_string(), "iz".to_string(), "wiki".to_string()] | |
| 382 | + ); | |
| 383 | + } | |
| 384 | + | |
| 385 | + #[tokio::test] | |
| 386 | + async fn the_value_rules_refuse_garbage_before_the_database_sees_it() { | |
| 387 | + 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"); | |
| 392 | + assert!(validate("in", "Files", "http://").is_err(), "hostless url"); | |
| 393 | + assert!(validate("in", "Files", "http://in.example/path x").is_err(), "space in url"); | |
| 394 | + // A trailing slash is not garbage — it is normalized away. | |
| 395 | + assert!(validate("in", "Files", "http://in.example/").is_ok()); | |
| 396 | + } | |
| 397 | +} |
crates/im-core/src/store.rsmodified+10 -0
| @@ -17,6 +17,10 @@ pub enum StoreError { | ||
| 17 | 17 | Corrupt(String), |
| 18 | 18 | #[error("io: {0}")] |
| 19 | 19 | Io(#[from] std::io::Error), |
| 20 | + /// A value a panel form offered is against the stored rules — the | |
| 21 | + /// caller turns it into the page's refusal, never a database problem. | |
| 22 | + #[error("{0}")] | |
| 23 | + Invalid(String), | |
| 20 | 24 | } |
| 21 | 25 | |
| 22 | 26 | pub type Result<T, E = StoreError> = std::result::Result<T, E>; |
| @@ -127,6 +131,12 @@ CREATE TABLE IF NOT EXISTS settings ( | ||
| 127 | 131 | key TEXT PRIMARY KEY, |
| 128 | 132 | value TEXT NOT NULL |
| 129 | 133 | ); |
| 134 | +CREATE TABLE IF NOT EXISTS services ( | |
| 135 | + key TEXT PRIMARY KEY, | |
| 136 | + name TEXT NOT NULL, | |
| 137 | + url TEXT NOT NULL, | |
| 138 | + position INTEGER NOT NULL | |
| 139 | +); | |
| 130 | 140 | "; |
| 131 | 141 | |
| 132 | 142 | /// One database handle with the at-rest key beside it. Turso is a |
crates/im-web/src/auth.rsmodified+118 -7
| @@ -45,10 +45,10 @@ fn safe_back(raw: &str) -> &str { | ||
| 45 | 45 | |
| 46 | 46 | /// Where a logout sends the browser. A local absolute path always |
| 47 | 47 | /// qualifies — the login `back` rule. An absolute URL qualifies when its |
| 48 | -/// origin is exactly one of the configured services': the sibling app that | |
| 49 | -/// sent the browser here gets it handed back. A foreign origin — and | |
| 48 | +/// origin is exactly one of the family's stored services': the sibling app | |
| 49 | +/// that sent the browser here gets it handed back. A foreign origin — and | |
| 50 | 50 | /// anything unparseable — is refused to the front door. |
| 51 | -fn logout_target(raw: Option<&str>, services: &[crate::config::Service]) -> String { | |
| 51 | +fn logout_target(raw: Option<&str>, services: &[im_core::services::Service]) -> String { | |
| 52 | 52 | let Some(raw) = raw else { |
| 53 | 53 | return "/".to_string(); |
| 54 | 54 | }; |
| @@ -320,10 +320,121 @@ async fn logout_return(cx: &Cx) -> Redirect { | ||
| 320 | 320 | .to_string(); |
| 321 | 321 | let back = crate::pages::query_value(&query, "back"); |
| 322 | 322 | sign_out_everywhere(cx).await?; |
| 323 | - see(logout_target( | |
| 324 | - back.as_deref(), | |
| 325 | - &server::app(cx).config.services, | |
| 326 | - )) | |
| 323 | + let services = im_core::services::list(&server::app(cx).store).await?; | |
| 324 | + see(logout_target(back.as_deref(), &services)) | |
| 325 | +} | |
| 326 | + | |
| 327 | +// --------------------------------------------------------------------------- | |
| 328 | +// The landing Services card's writes | |
| 329 | +// --------------------------------------------------------------------------- | |
| 330 | + | |
| 331 | +/// The admin behind this request, or `None` — the handlers below send a | |
| 332 | +/// non-admin to the front door, where the card carries no forms anyway. | |
| 333 | +/// The admin panel's `require_admin` is the same gate with the same answer. | |
| 334 | +async fn landing_admin(cx: &Cx) -> Option<im_core::model::User> { | |
| 335 | + match server::current_user(cx).await { | |
| 336 | + Some(user) if user.admin => Some(user), | |
| 337 | + _ => None, | |
| 338 | + } | |
| 339 | +} | |
| 340 | + | |
| 341 | +/// One user of the card's forms: key, name, address. The add form fills all | |
| 342 | +/// three; the edit form carries the key in its hidden field. | |
| 343 | +#[derive(Deserialize)] | |
| 344 | +pub struct ServiceForm { | |
| 345 | + key: String, | |
| 346 | + name: String, | |
| 347 | + url: String, | |
| 348 | +} | |
| 349 | + | |
| 350 | +/// The landing answer to a services write: back to the card with the good | |
| 351 | +/// news, or with the card's one refusal when the store said the value is | |
| 352 | +/// against the rules. Anything else is a real failure and travels as one. | |
| 353 | +fn service_outcome(outcome: im_core::store::Result<()>) -> Redirect { | |
| 354 | + match outcome { | |
| 355 | + Ok(()) => see("/?ok=services".to_string()), | |
| 356 | + Err(im_core::store::StoreError::Invalid(_)) => see("/?error=bad_service".to_string()), | |
| 357 | + Err(e) => Err(e.into()), | |
| 358 | + } | |
| 359 | +} | |
| 360 | + | |
| 361 | +#[route(POST "/services/add")] | |
| 362 | +async fn service_add(cx: &Cx, Form(input): Form<ServiceForm>) -> Redirect { | |
| 363 | + let Some(me) = landing_admin(cx).await else { | |
| 364 | + return see("/".to_string()); | |
| 365 | + }; | |
| 366 | + let outcome = im_core::services::add( | |
| 367 | + &server::app(cx).store, | |
| 368 | + &im_core::services::Service { | |
| 369 | + key: input.key, | |
| 370 | + name: input.name, | |
| 371 | + url: input.url, | |
| 372 | + }, | |
| 373 | + ) | |
| 374 | + .await; | |
| 375 | + if outcome.is_ok() { | |
| 376 | + server::log_event(cx, "services_updated", Some(&me.email), None).await; | |
| 377 | + } | |
| 378 | + service_outcome(outcome) | |
| 379 | +} | |
| 380 | + | |
| 381 | +#[route(POST "/services/edit")] | |
| 382 | +async fn service_edit(cx: &Cx, Form(input): Form<ServiceForm>) -> Redirect { | |
| 383 | + let Some(me) = landing_admin(cx).await else { | |
| 384 | + return see("/".to_string()); | |
| 385 | + }; | |
| 386 | + let outcome = im_core::services::edit( | |
| 387 | + &server::app(cx).store, | |
| 388 | + &input.key, | |
| 389 | + &input.name, | |
| 390 | + &input.url, | |
| 391 | + ) | |
| 392 | + .await; | |
| 393 | + if outcome.is_ok() { | |
| 394 | + server::log_event(cx, "services_updated", Some(&me.email), None).await; | |
| 395 | + } | |
| 396 | + service_outcome(outcome) | |
| 397 | +} | |
| 398 | + | |
| 399 | +#[derive(Deserialize)] | |
| 400 | +struct ServiceKeyForm { | |
| 401 | + key: String, | |
| 402 | +} | |
| 403 | + | |
| 404 | +#[route(POST "/services/remove")] | |
| 405 | +async fn service_remove(cx: &Cx, Form(input): Form<ServiceKeyForm>) -> Redirect { | |
| 406 | + let Some(me) = landing_admin(cx).await else { | |
| 407 | + return see("/".to_string()); | |
| 408 | + }; | |
| 409 | + let outcome = im_core::services::remove(&server::app(cx).store, &input.key).await; | |
| 410 | + if outcome.is_ok() { | |
| 411 | + server::log_event(cx, "services_updated", Some(&me.email), None).await; | |
| 412 | + } | |
| 413 | + service_outcome(outcome) | |
| 414 | +} | |
| 415 | + | |
| 416 | +#[derive(Deserialize)] | |
| 417 | +struct ServiceMoveForm { | |
| 418 | + key: String, | |
| 419 | + dir: String, | |
| 420 | +} | |
| 421 | + | |
| 422 | +/// Up or down one slot; anything else in `dir` is the card's refusal. | |
| 423 | +#[route(POST "/services/move")] | |
| 424 | +async fn service_move(cx: &Cx, Form(input): Form<ServiceMoveForm>) -> Redirect { | |
| 425 | + let Some(me) = landing_admin(cx).await else { | |
| 426 | + return see("/".to_string()); | |
| 427 | + }; | |
| 428 | + let up = match input.dir.as_str() { | |
| 429 | + "up" => true, | |
| 430 | + "down" => false, | |
| 431 | + _ => return see("/?error=bad_service".to_string()), | |
| 432 | + }; | |
| 433 | + let outcome = im_core::services::move_service(&server::app(cx).store, &input.key, up).await; | |
| 434 | + if outcome.is_ok() { | |
| 435 | + server::log_event(cx, "services_updated", Some(&me.email), None).await; | |
| 436 | + } | |
| 437 | + service_outcome(outcome) | |
| 327 | 438 | } |
| 328 | 439 | |
| 329 | 440 | #[derive(Deserialize)] |
crates/im-web/src/directory.rsmodified+314 -18
| @@ -46,6 +46,22 @@ async fn directory(cx: &Cx) -> topcoat::Result<topcoat::router::response::Respon | ||
| 46 | 46 | Json(serde_json::to_value(members).unwrap()).into_response(cx) |
| 47 | 47 | } |
| 48 | 48 | |
| 49 | +/// `GET /family`: the app switcher's list — every service with its wordmark, | |
| 50 | +/// name, and base URL, in the stored order, as a bare JSON array. Registered | |
| 51 | +/// apps only, exactly like `/directory`: a sibling copies this into its own | |
| 52 | +/// database and renders its switcher from that copy, so the family list has | |
| 53 | +/// one home (the admin panel here) and every other surface a cached mirror. | |
| 54 | +#[route(GET "/family")] | |
| 55 | +async fn family(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> { | |
| 56 | + if !server::valid_app(cx).await { | |
| 57 | + return (StatusCode::UNAUTHORIZED, Json(serde_json::json!({ "error": "invalid_client" }))) | |
| 58 | + .into_response(cx); | |
| 59 | + } | |
| 60 | + let store = server::app(cx).store.clone(); | |
| 61 | + let services = im_core::services::list(&store).await?; | |
| 62 | + Json(serde_json::to_value(services).unwrap()).into_response(cx) | |
| 63 | +} | |
| 64 | + | |
| 49 | 65 | #[cfg(test)] |
| 50 | 66 | mod tests { |
| 51 | 67 | use std::path::Path; |
| @@ -55,6 +71,7 @@ mod tests { | ||
| 55 | 71 | use im_core::oidc::create_client; |
| 56 | 72 | use im_core::model::ClientId; |
| 57 | 73 | use im_core::store::Store; |
| 74 | + use topcoat::asset::RouterBuilderAssetExt as _; | |
| 58 | 75 | use topcoat::cookie::RouterBuilderCookieExt as _; |
| 59 | 76 | use topcoat::router::{Body, Router, RouterBuilderDiscoverExt as _, StatusCode, header, to_bytes}; |
| 60 | 77 | |
| @@ -94,6 +111,29 @@ mod tests { | ||
| 94 | 111 | im_core::accounts::set_disabled(&store, &gone.id, true) |
| 95 | 112 | .await |
| 96 | 113 | .unwrap(); |
| 114 | + let services = vec![ | |
| 115 | + crate::config::Service { | |
| 116 | + key: "in".into(), | |
| 117 | + name: "Files".into(), | |
| 118 | + url: "http://127.0.0.1:7655".into(), | |
| 119 | + }, | |
| 120 | + crate::config::Service { | |
| 121 | + key: "im".into(), | |
| 122 | + name: "Account".into(), | |
| 123 | + url: "http://127.0.0.1:7650".into(), | |
| 124 | + }, | |
| 125 | + crate::config::Service { | |
| 126 | + key: "iz".into(), | |
| 127 | + name: "Board".into(), | |
| 128 | + url: "http://127.0.0.1:7654".into(), | |
| 129 | + }, | |
| 130 | + ]; | |
| 131 | + // The boot's one-time seed: the config's list becomes the table's | |
| 132 | + // starting rows, which is what every reader — /family, the trio, the | |
| 133 | + // landing card, the logout allowlist — now goes through. | |
| 134 | + im_core::services::seed_from(&store, &core_services(&services)) | |
| 135 | + .await | |
| 136 | + .unwrap(); | |
| 97 | 137 | let (live, _) = tokio::sync::broadcast::channel(64); |
| 98 | 138 | let app = server::App { |
| 99 | 139 | store: store.clone(), |
| @@ -101,29 +141,21 @@ mod tests { | ||
| 101 | 141 | database: ":memory:".into(), |
| 102 | 142 | listen: "127.0.0.1:7650".parse().unwrap(), |
| 103 | 143 | issuer: "http://127.0.0.1:7650".into(), |
| 104 | - services: vec![ | |
| 105 | - crate::config::Service { | |
| 106 | - key: "in".into(), | |
| 107 | - name: "Files".into(), | |
| 108 | - url: "http://127.0.0.1:7655".into(), | |
| 109 | - }, | |
| 110 | - crate::config::Service { | |
| 111 | - key: "im".into(), | |
| 112 | - name: "Account".into(), | |
| 113 | - url: "http://127.0.0.1:7650".into(), | |
| 114 | - }, | |
| 115 | - crate::config::Service { | |
| 116 | - key: "iz".into(), | |
| 117 | - name: "Board".into(), | |
| 118 | - url: "http://127.0.0.1:7654".into(), | |
| 119 | - }, | |
| 120 | - ], | |
| 144 | + services, | |
| 121 | 145 | }, |
| 122 | 146 | live, |
| 123 | 147 | }; |
| 124 | 148 | let router = Router::builder() |
| 125 | 149 | .discover() |
| 126 | 150 | .cookies() |
| 151 | + // The pages shell renders its stylesheet link through the asset | |
| 152 | + // catalog, so the tests render pages against the real bundle — | |
| 153 | + // the same one `serve` loads beside the executable. | |
| 154 | + .assets(topcoat::asset::AssetBundle::load_dir(concat!( | |
| 155 | + env!("CARGO_MANIFEST_DIR"), | |
| 156 | + "/../../target/debug/assets" | |
| 157 | + )) | |
| 158 | + .unwrap()) | |
| 127 | 159 | .app_context(app) |
| 128 | 160 | .build(); |
| 129 | 161 | Setup { |
| @@ -153,6 +185,21 @@ mod tests { | ||
| 153 | 185 | (parts.status, String::from_utf8(bytes).unwrap()) |
| 154 | 186 | } |
| 155 | 187 | |
| 188 | + /// The config's service list as the domain module's own shape — the one | |
| 189 | + /// conversion the boot-time seed needs. | |
| 190 | + fn core_services( | |
| 191 | + config: &[crate::config::Service], | |
| 192 | + ) -> Vec<im_core::services::Service> { | |
| 193 | + config | |
| 194 | + .iter() | |
| 195 | + .map(|service| im_core::services::Service { | |
| 196 | + key: service.key.clone(), | |
| 197 | + name: service.name.clone(), | |
| 198 | + url: service.url.clone(), | |
| 199 | + }) | |
| 200 | + .collect() | |
| 201 | + } | |
| 202 | + | |
| 156 | 203 | /// A form post through the router, answered as (status, Location, body). |
| 157 | 204 | async fn post_form( |
| 158 | 205 | router: &Router, |
| @@ -200,6 +247,34 @@ mod tests { | ||
| 200 | 247 | (parts.status, location) |
| 201 | 248 | } |
| 202 | 249 | |
| 250 | + /// `GET /family` with an app's Basic pair (or without one). | |
| 251 | + async fn get_family(router: &Router, authorization: Option<String>) -> (StatusCode, String) { | |
| 252 | + let mut builder = http::Request::builder().uri("/family"); | |
| 253 | + if let Some(value) = authorization { | |
| 254 | + builder = builder.header(header::AUTHORIZATION, value); | |
| 255 | + } | |
| 256 | + let response = router.handle(builder.body(Body::empty()).unwrap()).await; | |
| 257 | + let (parts, body) = response.into_parts(); | |
| 258 | + let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec(); | |
| 259 | + (parts.status, String::from_utf8(bytes).unwrap()) | |
| 260 | + } | |
| 261 | + | |
| 262 | + /// A page GET as a signed-in browser: the whole document back. | |
| 263 | + async fn get_page(router: &Router, uri: &str, cookie: &str) -> String { | |
| 264 | + let response = router | |
| 265 | + .handle( | |
| 266 | + http::Request::builder() | |
| 267 | + .uri(uri) | |
| 268 | + .header(header::COOKIE, cookie) | |
| 269 | + .body(Body::empty()) | |
| 270 | + .unwrap(), | |
| 271 | + ) | |
| 272 | + .await; | |
| 273 | + let (_, body) = response.into_parts(); | |
| 274 | + let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec(); | |
| 275 | + String::from_utf8(bytes).unwrap() | |
| 276 | + } | |
| 277 | + | |
| 203 | 278 | #[tokio::test] |
| 204 | 279 | async fn the_directory_names_every_non_disabled_user_with_its_admin_flag() { |
| 205 | 280 | let Setup { |
| @@ -255,8 +330,10 @@ mod tests { | ||
| 255 | 330 | .unwrap() |
| 256 | 331 | .unwrap(); |
| 257 | 332 | |
| 258 | - // The RP-initiated exit: `back` naming a configured service's own | |
| 333 | + // The RP-initiated exit: `back` naming a stored service's own | |
| 259 | 334 | // origin is honored verbatim — the sibling gets its browser back. |
| 335 | + // The allowlist is the seeded table now; the config's copy is only | |
| 336 | + // the seed's source. | |
| 260 | 337 | let one = im_core::sessions::create_session(&store, &ada.id, &Default::default()) |
| 261 | 338 | .await |
| 262 | 339 | .unwrap(); |
| @@ -324,4 +401,223 @@ mod tests { | ||
| 324 | 401 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 325 | 402 | assert_eq!(location.as_deref(), Some("/")); |
| 326 | 403 | } |
| 404 | + | |
| 405 | + #[tokio::test] | |
| 406 | + async fn family_serves_the_stored_list_to_registered_apps_only() { | |
| 407 | + let Setup { | |
| 408 | + router, | |
| 409 | + client_id, | |
| 410 | + secret, | |
| 411 | + .. | |
| 412 | + } = setup().await; | |
| 413 | + let (status, body) = get_family(&router, None).await; | |
| 414 | + assert_eq!(status, StatusCode::UNAUTHORIZED); | |
| 415 | + assert_eq!( | |
| 416 | + serde_json::from_str::<serde_json::Value>(&body).unwrap()["error"], | |
| 417 | + "invalid_client" | |
| 418 | + ); | |
| 419 | + let (status, _) = get_family(&router, Some(basic(&client_id, "wrong"))).await; | |
| 420 | + assert_eq!(status, StatusCode::UNAUTHORIZED); | |
| 421 | + | |
| 422 | + // The seeded rows, in stored order, as a bare JSON array. | |
| 423 | + let (status, body) = get_family(&router, Some(basic(&client_id, &secret))).await; | |
| 424 | + assert_eq!(status, StatusCode::OK); | |
| 425 | + let family = serde_json::from_str::<serde_json::Value>(&body).unwrap(); | |
| 426 | + let family = family | |
| 427 | + .as_array() | |
| 428 | + .unwrap() | |
| 429 | + .iter() | |
| 430 | + .map(|s| s["key"].as_str().unwrap()) | |
| 431 | + .collect::<Vec<_>>(); | |
| 432 | + assert_eq!(family, vec!["in", "im", "iz"], "{body}"); | |
| 433 | + } | |
| 434 | + | |
| 435 | + #[tokio::test] | |
| 436 | + async fn the_panel_edits_the_family_and_every_reader_follows_the_table() { | |
| 437 | + let Setup { | |
| 438 | + router, | |
| 439 | + client_id, | |
| 440 | + secret, | |
| 441 | + store, | |
| 442 | + } = setup().await; | |
| 443 | + let ada = im_core::accounts::user_by_email(&store, "ada@example.com") | |
| 444 | + .await | |
| 445 | + .unwrap() | |
| 446 | + .unwrap(); | |
| 447 | + let ben = im_core::accounts::user_by_email(&store, "ben@example.com") | |
| 448 | + .await | |
| 449 | + .unwrap() | |
| 450 | + .unwrap(); | |
| 451 | + | |
| 452 | + // A non-admin's post is sent to the front door and writes nothing. | |
| 453 | + let ben_session = im_core::sessions::create_session(&store, &ben.id, &Default::default()) | |
| 454 | + .await | |
| 455 | + .unwrap(); | |
| 456 | + let (status, location, _) = post_form( | |
| 457 | + &router, | |
| 458 | + "/services/add", | |
| 459 | + "key=wiki&name=Wiki&url=http%3A%2F%2F127.0.0.1%3A99", | |
| 460 | + Some(&format!("{SESSION_COOKIE}={}", ben_session.expose())), | |
| 461 | + ) | |
| 462 | + .await; | |
| 463 | + assert_eq!(status, StatusCode::SEE_OTHER); | |
| 464 | + assert_eq!(location.as_deref(), Some("/")); | |
| 465 | + | |
| 466 | + // The admin's add lands back on the card, and /family carries the | |
| 467 | + // new row at the end — trailing slash stored off, like every URL. | |
| 468 | + let session = im_core::sessions::create_session(&store, &ada.id, &Default::default()) | |
| 469 | + .await | |
| 470 | + .unwrap(); | |
| 471 | + let cookie = format!("{SESSION_COOKIE}={}", session.expose()); | |
| 472 | + let (status, location, _) = post_form( | |
| 473 | + &router, | |
| 474 | + "/services/add", | |
| 475 | + "key=wiki&name=Wiki&url=http%3A%2F%2F127.0.0.1%3A99%2F", | |
| 476 | + Some(&cookie), | |
| 477 | + ) | |
| 478 | + .await; | |
| 479 | + assert_eq!(status, StatusCode::SEE_OTHER); | |
| 480 | + assert_eq!(location.as_deref(), Some("/?ok=services")); | |
| 481 | + let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; | |
| 482 | + let family = serde_json::from_str::<serde_json::Value>(&body).unwrap(); | |
| 483 | + let family = family.as_array().unwrap(); | |
| 484 | + let keys = family | |
| 485 | + .iter() | |
| 486 | + .map(|s| s["key"].as_str().unwrap()) | |
| 487 | + .collect::<Vec<_>>(); | |
| 488 | + assert_eq!(keys, vec!["in", "im", "iz", "wiki"], "{body}"); | |
| 489 | + assert_eq!(family[3]["url"], "http://127.0.0.1:99"); | |
| 490 | + assert!(get_page(&router, "/?section=profile", &cookie) | |
| 491 | + .await | |
| 492 | + .contains(r#"action="/services/add""#)); | |
| 493 | + assert!(!get_page( | |
| 494 | + &router, | |
| 495 | + "/?section=profile", | |
| 496 | + &format!("{SESSION_COOKIE}={}", ben_session.expose()) | |
| 497 | + ) | |
| 498 | + .await | |
| 499 | + .contains(r#"action="/services/add""#)); | |
| 500 | + | |
| 501 | + // Edit rewrites name and address; move up swaps with the neighbor. | |
| 502 | + let (_status, location, _) = post_form( | |
| 503 | + &router, | |
| 504 | + "/services/edit", | |
| 505 | + "key=wiki&name=Docs&url=http%3A%2F%2F127.0.0.1%3A98", | |
| 506 | + Some(&cookie), | |
| 507 | + ) | |
| 508 | + .await; | |
| 509 | + assert_eq!(location.as_deref(), Some("/?ok=services")); | |
| 510 | + let (_status, location, _) = post_form( | |
| 511 | + &router, | |
| 512 | + "/services/move", | |
| 513 | + "key=wiki&dir=up", | |
| 514 | + Some(&cookie), | |
| 515 | + ) | |
| 516 | + .await; | |
| 517 | + assert_eq!(location.as_deref(), Some("/?ok=services")); | |
| 518 | + let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; | |
| 519 | + let family = serde_json::from_str::<serde_json::Value>(&body).unwrap(); | |
| 520 | + let family = family.as_array().unwrap(); | |
| 521 | + let keys = family | |
| 522 | + .iter() | |
| 523 | + .map(|s| s["key"].as_str().unwrap()) | |
| 524 | + .collect::<Vec<_>>(); | |
| 525 | + assert_eq!(keys, vec!["in", "im", "wiki", "iz"], "{body}"); | |
| 526 | + assert_eq!(family[2]["name"], "Docs"); | |
| 527 | + assert_eq!(family[2]["url"], "http://127.0.0.1:98"); | |
| 528 | + | |
| 529 | + // The logout allowlist is the table too: the DB-added origin — one | |
| 530 | + // no config ever named — gets its browser back. | |
| 531 | + let wiki_session = im_core::sessions::create_session(&store, &ada.id, &Default::default()) | |
| 532 | + .await | |
| 533 | + .unwrap(); | |
| 534 | + let (status, location) = get_location( | |
| 535 | + &router, | |
| 536 | + "/logout?back=http%3A%2F%2F127.0.0.1%3A98%2F", | |
| 537 | + &format!("{SESSION_COOKIE}={}", wiki_session.expose()), | |
| 538 | + ) | |
| 539 | + .await; | |
| 540 | + assert_eq!(status, StatusCode::SEE_OTHER); | |
| 541 | + assert_eq!(location.as_deref(), Some("http://127.0.0.1:98/")); | |
| 542 | + | |
| 543 | + // And once the row is gone, the same origin is refused to the door. | |
| 544 | + let (_status, location, _) = post_form( | |
| 545 | + &router, | |
| 546 | + "/services/remove", | |
| 547 | + "key=wiki", | |
| 548 | + Some(&cookie), | |
| 549 | + ) | |
| 550 | + .await; | |
| 551 | + assert_eq!(location.as_deref(), Some("/?ok=services")); | |
| 552 | + let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; | |
| 553 | + let family = serde_json::from_str::<serde_json::Value>(&body).unwrap(); | |
| 554 | + let keys = family | |
| 555 | + .as_array() | |
| 556 | + .unwrap() | |
| 557 | + .iter() | |
| 558 | + .map(|s| s["key"].as_str().unwrap()) | |
| 559 | + .collect::<Vec<_>>(); | |
| 560 | + assert_eq!(keys, vec!["in", "im", "iz"], "{body}"); | |
| 561 | + let gone_session = im_core::sessions::create_session(&store, &ada.id, &Default::default()) | |
| 562 | + .await | |
| 563 | + .unwrap(); | |
| 564 | + let (_status, location) = get_location( | |
| 565 | + &router, | |
| 566 | + "/logout?back=http%3A%2F%2F127.0.0.1%3A98%2F", | |
| 567 | + &format!("{SESSION_COOKIE}={}", gone_session.expose()), | |
| 568 | + ) | |
| 569 | + .await; | |
| 570 | + assert_eq!(location.as_deref(), Some("/")); | |
| 571 | + | |
| 572 | + // A value against the rules is the card's refusal, not a write. | |
| 573 | + let bad_session = im_core::sessions::create_session(&store, &ada.id, &Default::default()) | |
| 574 | + .await | |
| 575 | + .unwrap(); | |
| 576 | + let (_status, location, _) = post_form( | |
| 577 | + &router, | |
| 578 | + "/services/add", | |
| 579 | + "key=Wiki!&name=Wiki&url=http%3A%2F%2F127.0.0.1%3A97", | |
| 580 | + Some(&format!("{SESSION_COOKIE}={}", bad_session.expose())), | |
| 581 | + ) | |
| 582 | + .await; | |
| 583 | + assert_eq!(location.as_deref(), Some("/?error=bad_service")); | |
| 584 | + let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; | |
| 585 | + assert_eq!( | |
| 586 | + serde_json::from_str::<serde_json::Value>(&body) | |
| 587 | + .unwrap() | |
| 588 | + .as_array() | |
| 589 | + .unwrap() | |
| 590 | + .len(), | |
| 591 | + 3, | |
| 592 | + "{body}" | |
| 593 | + ); | |
| 594 | + } | |
| 595 | + | |
| 596 | + #[tokio::test] | |
| 597 | + async fn the_seed_fills_an_empty_table_once_and_never_rewrites_it() { | |
| 598 | + let Setup { | |
| 599 | + router, | |
| 600 | + client_id, | |
| 601 | + secret, | |
| 602 | + store, | |
| 603 | + } = setup().await; | |
| 604 | + // The setup already seeded; a re-boot's seed must be a no-op, even | |
| 605 | + // though `in` is exactly the name the config carries. | |
| 606 | + let reseed = vec![im_core::services::Service { | |
| 607 | + key: "in".into(), | |
| 608 | + name: "Files".into(), | |
| 609 | + url: "http://127.0.0.1:7655".into(), | |
| 610 | + }]; | |
| 611 | + assert!(!im_core::services::seed_from(&store, &reseed).await.unwrap()); | |
| 612 | + let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; | |
| 613 | + assert_eq!( | |
| 614 | + serde_json::from_str::<serde_json::Value>(&body) | |
| 615 | + .unwrap() | |
| 616 | + .as_array() | |
| 617 | + .unwrap() | |
| 618 | + .len(), | |
| 619 | + 3, | |
| 620 | + "{body}" | |
| 621 | + ); | |
| 622 | + } | |
| 327 | 623 | } |
crates/im-web/src/i18n.rsmodified+19 -0
| @@ -65,6 +65,7 @@ pub enum Key { | ||
| 65 | 65 | ErrBadTheme, |
| 66 | 66 | ErrBadUi, |
| 67 | 67 | ErrBadLanguage, |
| 68 | + ErrBadService, | |
| 68 | 69 | ErrFallback, |
| 69 | 70 | |
| 70 | 71 | // Good-news codes (`pages.rs`'s `ok_text`). |
| @@ -127,6 +128,10 @@ pub enum Key { | ||
| 127 | 128 | StatConnectedApps, |
| 128 | 129 | SessionsTitle, |
| 129 | 130 | ServicesTitle, |
| 131 | + ServiceKeyLabel, | |
| 132 | + ServiceAdd, | |
| 133 | + ServiceMoveUp, | |
| 134 | + ServiceMoveDown, | |
| 130 | 135 | SignOutEverywhere, |
| 131 | 136 | AdminPanelLink, |
| 132 | 137 | ViewPhotoAria, |
| @@ -329,6 +334,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | ||
| 329 | 334 | (ErrBadUi, Tr) => "Bu bir arayüz değil.", |
| 330 | 335 | (ErrBadLanguage, En) => "That is not a language.", |
| 331 | 336 | (ErrBadLanguage, Tr) => "Bu bir dil değil.", |
| 337 | + (ErrBadService, En) => { | |
| 338 | + "A service needs a key of lowercase letters, digits, or dashes, a name, and an http(s) address." | |
| 339 | + } | |
| 340 | + (ErrBadService, Tr) => { | |
| 341 | + "Bir hizmet; küçük harf, rakam ya da tire ile yazılmış bir anahtar, bir ad ve http(s) adresi ister." | |
| 342 | + } | |
| 332 | 343 | (ErrFallback, En) => "Something went wrong. Try again.", |
| 333 | 344 | (ErrFallback, Tr) => "Bir şeyler ters gitti. Yeniden dene.", |
| 334 | 345 | |
| @@ -450,6 +461,14 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | ||
| 450 | 461 | (SessionsTitle, Tr) => "Oturumlar", |
| 451 | 462 | (ServicesTitle, En) => "Services", |
| 452 | 463 | (ServicesTitle, Tr) => "Hizmetler", |
| 464 | + (ServiceKeyLabel, En) => "Key", | |
| 465 | + (ServiceKeyLabel, Tr) => "Anahtar", | |
| 466 | + (ServiceAdd, En) => "Add service", | |
| 467 | + (ServiceAdd, Tr) => "Hizmet ekle", | |
| 468 | + (ServiceMoveUp, En) => "Move up", | |
| 469 | + (ServiceMoveUp, Tr) => "Yukarı taşı", | |
| 470 | + (ServiceMoveDown, En) => "Move down", | |
| 471 | + (ServiceMoveDown, Tr) => "Aşağı taşı", | |
| 453 | 472 | (SignOutEverywhere, En) => "Sign out everywhere", |
| 454 | 473 | (SignOutEverywhere, Tr) => "Her yerde oturumu kapat", |
| 455 | 474 | (AdminPanelLink, En) => "Admin panel", |
crates/im-web/src/layout.rsmodified+5 -4
| @@ -24,12 +24,13 @@ pub async fn wordmark(cx: &Cx) -> Result { | ||
| 24 | 24 | } |
| 25 | 25 | } |
| 26 | 26 | |
| 27 | -/// The signed-in chrome's app trio: every configured service's wordmark, | |
| 27 | +/// The signed-in chrome's app trio: every family service's wordmark, | |
| 28 | 28 | /// middots between, the home one (`im`) inked and marked current, its |
| 29 | -/// siblings plain links. A deployment that names no services renders | |
| 30 | -/// nothing — the single mark above stays the whole chrome. | |
| 29 | +/// siblings plain links. A family with no members renders nothing — the | |
| 30 | +/// single mark above stays the whole chrome. The list is the stored one, | |
| 31 | +/// the same rows `/family` serves. | |
| 31 | 32 | pub async fn service_trio(cx: &Cx) -> Result { |
| 32 | - let services = &server::app(cx).config.services; | |
| 33 | + let services = im_core::services::list(&server::app(cx).store).await?; | |
| 33 | 34 | let marks = (!services.is_empty()).then(|| { |
| 34 | 35 | services |
| 35 | 36 | .iter() |
crates/im-web/src/main.rsmodified+28 -0
| @@ -143,6 +143,33 @@ async fn open_store(config: &Config) -> Arc<Store> { | ||
| 143 | 143 | ) |
| 144 | 144 | } |
| 145 | 145 | |
| 146 | +/// The one-time seed: a database with no services yet takes the config's | |
| 147 | +/// `[[services]]` list as the family's starting rows. Afterwards the admin | |
| 148 | +/// panel owns the list and the same file lines are dead letters — the seed | |
| 149 | +/// only fires again if the table is emptied. | |
| 150 | +async fn seed_services(store: &Store, config: &Config) { | |
| 151 | + if config.services.is_empty() { | |
| 152 | + return; | |
| 153 | + } | |
| 154 | + let seed: Vec<im_core::services::Service> = config | |
| 155 | + .services | |
| 156 | + .iter() | |
| 157 | + .map(|service| im_core::services::Service { | |
| 158 | + key: service.key.clone(), | |
| 159 | + name: service.name.clone(), | |
| 160 | + url: service.url.clone(), | |
| 161 | + }) | |
| 162 | + .collect(); | |
| 163 | + match im_core::services::seed_from(store, &seed).await { | |
| 164 | + Ok(true) => println!( | |
| 165 | + "im services seeded from config ({} entries)", | |
| 166 | + seed.len() | |
| 167 | + ), | |
| 168 | + Ok(false) => {} | |
| 169 | + Err(e) => eprintln!("im: seeding services from config failed: {e}"), | |
| 170 | + } | |
| 171 | +} | |
| 172 | + | |
| 146 | 173 | /// `im-web invite <email> [--admin]`: creates the invite, mails it when the |
| 147 | 174 | /// panel has configured a sender, prints the link otherwise (dev mode). |
| 148 | 175 | /// |
| @@ -215,6 +242,7 @@ async fn serve(config: Config) { | ||
| 215 | 242 | println!("im {line}"); |
| 216 | 243 | } |
| 217 | 244 | let store = open_store(&config).await; |
| 245 | + seed_services(&store, &config).await; | |
| 218 | 246 | let (live, _) = tokio::sync::broadcast::channel(64); |
| 219 | 247 | // Told when the process is stopping, so the live streams end instead of |
| 220 | 248 | // being waited out — see `live::Shutdown`. |
crates/im-web/src/pages.rsmodified+71 -6
| @@ -41,6 +41,7 @@ pub fn error_text(code: &str, lang: Lang) -> &'static str { | ||
| 41 | 41 | "bad_theme" => t(lang, Key::ErrBadTheme), |
| 42 | 42 | "bad_ui" => t(lang, Key::ErrBadUi), |
| 43 | 43 | "bad_language" => t(lang, Key::ErrBadLanguage), |
| 44 | + "bad_service" => t(lang, Key::ErrBadService), | |
| 44 | 45 | "empty_subject" => t(lang, Key::ErrEmptySubject), |
| 45 | 46 | "empty_body" => t(lang, Key::ErrEmptyBody), |
| 46 | 47 | "no_such_user" => t(lang, Key::ErrNoSuchUser), |
| @@ -59,6 +60,7 @@ pub fn ok_text(code: &str, lang: Lang) -> &'static str { | ||
| 59 | 60 | "photo_removed" => t(lang, Key::OkPhotoRemoved), |
| 60 | 61 | "session_revoked" => t(lang, Key::OkSessionRevoked), |
| 61 | 62 | "preferences" => t(lang, Key::Saved), |
| 63 | + "services" => t(lang, Key::Saved), | |
| 62 | 64 | "password" => t(lang, Key::PasswordSaved), |
| 63 | 65 | _ => t(lang, Key::OkDone), |
| 64 | 66 | } |
| @@ -601,13 +603,13 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { | ||
| 601 | 603 | ) |
| 602 | 604 | }) |
| 603 | 605 | .collect::<String>(); |
| 604 | - // The services home: one card per configured app — wordmark and name, | |
| 606 | + // The services home: one card per family member — wordmark and name, | |
| 605 | 607 | // the whole card the link. im's own card reads current. Above the |
| 606 | 608 | // profile sections: im is the account center, and its landing is the |
| 607 | - // door to the rest. | |
| 608 | - let services_html = server::app(cx) | |
| 609 | - .config | |
| 610 | - .services | |
| 609 | + // door to the rest. The list is the stored one — the rows `/family` | |
| 610 | + // serves — and an admin gets the handles on it right under the cards. | |
| 611 | + let services = im_core::services::list(&server::app(cx).store).await?; | |
| 612 | + let services_html = services | |
| 611 | 613 | .iter() |
| 612 | 614 | .map(|service| { |
| 613 | 615 | let current = service.key == "im"; |
| @@ -624,6 +626,11 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { | ||
| 624 | 626 | ) |
| 625 | 627 | }) |
| 626 | 628 | .collect::<String>(); |
| 629 | + let services_manage = if user.admin { | |
| 630 | + services_manage_html(&services, lang) | |
| 631 | + } else { | |
| 632 | + String::new() | |
| 633 | + }; | |
| 627 | 634 | let stage = view! { |
| 628 | 635 | cx => |
| 629 | 636 | <main class="auth-stage landing-stage"> |
| @@ -631,10 +638,11 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { | ||
| 631 | 638 | (wordmark(cx).await?) |
| 632 | 639 | (service_trio(cx).await?) |
| 633 | 640 | <nav class="admin-tabs landing-nav">(topcoat::view::Unescaped::new_unchecked(nav))</nav> |
| 634 | - if !services_html.is_empty() { | |
| 641 | + if !services_html.is_empty() || user.admin { | |
| 635 | 642 | <div class="auth-card"> |
| 636 | 643 | <div class="auth-title">(t(lang, Key::ServicesTitle))</div> |
| 637 | 644 | <div class="service-grid">(topcoat::view::Unescaped::new_unchecked(services_html))</div> |
| 645 | + (topcoat::view::Unescaped::new_unchecked(services_manage)) | |
| 638 | 646 | </div> |
| 639 | 647 | } |
| 640 | 648 | if let Some(code) = ok { |
| @@ -846,6 +854,63 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { | ||
| 846 | 854 | shell(cx, "im", Some(user), stage).await |
| 847 | 855 | } |
| 848 | 856 | |
| 857 | +/// The admin's handles under the services grid: a name-and-address edit per | |
| 858 | +/// row, the up/down pair, the remove, and the add form. Every action is a | |
| 859 | +/// plain form post answering a 303 back to this card — the landing idiom — | |
| 860 | +/// wearing the admin panel's quiet row-button skin, laid out by the same | |
| 861 | +/// flex row the panel's invite line uses. | |
| 862 | +fn services_manage_html(services: &[im_core::services::Service], lang: Lang) -> String { | |
| 863 | + let mut rows = String::new(); | |
| 864 | + for service in services { | |
| 865 | + let key = escape(&service.key); | |
| 866 | + rows.push_str(&format!( | |
| 867 | + r#"<div class="admin-invite"> | |
| 868 | + <form method="post" action="/services/edit"> | |
| 869 | + <input type="hidden" name="key" value="{key}"> | |
| 870 | + <input class="auth-input" type="text" name="name" value="{name}" aria-label="{name_label}" required=""> | |
| 871 | + <input class="auth-input" type="text" name="url" value="{url}" aria-label="{url_label}" required=""> | |
| 872 | + <button class="admin-action" type="submit">{save}</button> | |
| 873 | + </form> | |
| 874 | + <form method="post" action="/services/move"> | |
| 875 | + <input type="hidden" name="key" value="{key}"><input type="hidden" name="dir" value="up"> | |
| 876 | + <button class="admin-action" type="submit" aria-label="{up}">↑</button> | |
| 877 | + </form> | |
| 878 | + <form method="post" action="/services/move"> | |
| 879 | + <input type="hidden" name="key" value="{key}"><input type="hidden" name="dir" value="down"> | |
| 880 | + <button class="admin-action" type="submit" aria-label="{down}">↓</button> | |
| 881 | + </form> | |
| 882 | + <form method="post" action="/services/remove"> | |
| 883 | + <input type="hidden" name="key" value="{key}"> | |
| 884 | + <button class="admin-action admin-danger" type="submit">{remove}</button> | |
| 885 | + </form> | |
| 886 | +</div>"#, | |
| 887 | + name = escape(&service.name), | |
| 888 | + url = escape(&service.url), | |
| 889 | + name_label = t(lang, Key::NameCol), | |
| 890 | + url_label = t(lang, Key::AddressLabel), | |
| 891 | + save = t(lang, Key::SaveButton), | |
| 892 | + up = t(lang, Key::ServiceMoveUp), | |
| 893 | + down = t(lang, Key::ServiceMoveDown), | |
| 894 | + remove = t(lang, Key::Remove), | |
| 895 | + )); | |
| 896 | + } | |
| 897 | + rows.push_str(&format!( | |
| 898 | + r#"<div class="admin-invite"> | |
| 899 | + <form method="post" action="/services/add"> | |
| 900 | + <input class="auth-input" type="text" name="key" placeholder="in" aria-label="{key_label}" required=""> | |
| 901 | + <input class="auth-input" type="text" name="name" placeholder="{name_label}" aria-label="{name_label}" required=""> | |
| 902 | + <input class="auth-input" type="text" name="url" placeholder="https://in.dizey.sh" aria-label="{url_label}" required=""> | |
| 903 | + <button class="admin-action" type="submit">{add}</button> | |
| 904 | + </form> | |
| 905 | +</div>"#, | |
| 906 | + key_label = t(lang, Key::ServiceKeyLabel), | |
| 907 | + name_label = t(lang, Key::NameCol), | |
| 908 | + url_label = t(lang, Key::AddressLabel), | |
| 909 | + add = t(lang, Key::ServiceAdd), | |
| 910 | + )); | |
| 911 | + rows | |
| 912 | +} | |
| 913 | + | |
| 849 | 914 | /// "Forgot it?" — the self-serve reset ask. It answers the same whether the |
| 850 | 915 | /// address has an account: one quiet note, the same one for every address. |
| 851 | 916 | #[page("/forgot")] |