forge
Explore
Log in

Don't you dare go Hollow

iz: live session-revocation logout

Browse files at this commit

f4152e1951a04a198d6c73c815bbd6d4d2a4a069Ahmet Kaan GümüşParent: 66ac686
- Topic::Revoked(local_id); /api/live names the killed user's own
  connections then ends the stream; enable publishes Members only
- iz-owned /directory/live parser (pin untouched): unknown kinds skipped,
  CRLF-straddle safe (cr_ended), revoked{sub} -> Members announce,
  disabled reconciled both directions
- client: revoked frame or /api/me 401 on SSE error -> hard navigate to /
- new GET /api/me (204/401)
crates/iz-core/src/live.rsmodified+8 -0
@@ -24,6 +24,12 @@ pub enum Topic {
2424 Task(String),
2525 /// Users, roles, invites, sessions, photos, profile.
2626 Members,
27+ /// One account was killed at the provider — disabled, or gone. The id
28+ /// is the local row's, and the frame names it to exactly one reader:
29+ /// the connection whose own id it is. A session revocation does not
30+ /// ride here — which session died is the provider's knowledge, and a
31+ /// tab whose other session survived must not be sent away.
32+ Revoked(String),
2733 /// The mail queue: `mail_send` rows.
2834 Queue,
2935 /// Mail rules and the decisions they made.
@@ -45,6 +51,7 @@ impl Topic {
4551 Topic::Board => "board",
4652 Topic::Task(_) => "task",
4753 Topic::Members => "members",
54+ Topic::Revoked(_) => "revoked",
4855 Topic::Queue => "queue",
4956 Topic::Rules => "rules",
5057 Topic::Tags => "tags",
@@ -57,6 +64,7 @@ impl Topic {
5764 pub fn id(&self) -> Option<&str> {
5865 match self {
5966 Topic::Task(id) => Some(id),
67+ Topic::Revoked(id) => Some(id),
6068 _ => None,
6169 }
6270 }
crates/iz-core/src/store/mod.rsmodified+12 -0
@@ -756,6 +756,13 @@ pub trait Store: BoardReads + DetailReads + 'static {
756756 /// role-gated route. Sending to zero subscribers is normal and silent,
757757 /// and a slow subscriber's overflow is the client's cue to resync.
758758 fn subscribe(&self) -> tokio::sync::broadcast::Receiver<crate::live::Change>;
759+
760+ /// Announces topics with no write behind them — the door for facts that
761+ /// arrive from outside this database, such as a revoked session heard on
762+ /// im's directory stream. This only wakes the subscribers, exactly as a
763+ /// committed write would; which connection is told remains the live
764+ /// channel's own role decision.
765+ fn announce(&self, topics: &[crate::live::Topic]);
759766 // -- workspace ---------------------------------------------------------
760767
761768 /// The account that claimed the workspace, if it has been claimed.
@@ -888,6 +895,11 @@ pub trait Store: BoardReads + DetailReads + 'static {
888895 /// an address has an account.
889896 async fn user_by_email(&self, workspace_id: &str, email: &str) -> Result<Option<User>>;
890897
898+ /// Lookup by provider subject — the key im's directory stream names when
899+ /// it announces a revoked or disabled member. `None` is a subject this
900+ /// workspace has never provisioned.
901+ async fn user_by_sub(&self, sub: &str) -> Result<Option<User>>;
902+
891903 async fn users(&self, workspace_id: &str) -> Result<Vec<User>>;
892904
893905 async fn count_users(&self, workspace_id: &str) -> Result<u64>;
crates/iz-core/src/store/turso_store.rsmodified+70 -49
@@ -74,7 +74,7 @@ impl TursoStore {
7474 /// of a server nobody is looking at. It is dropped on purpose: an
7575 /// announcement nobody is waiting for is not a problem, and logging it
7676 /// would fill the log with the sound of an idle app.
77- fn announce(&self, topics: impl IntoIterator<Item = Topic>) {
77+ fn publish(&self, topics: impl IntoIterator<Item = Topic>) {
7878 for topic in topics {
7979 let _ = self.live.send(Change {
8080 topic,
@@ -1403,6 +1403,10 @@ impl Store for TursoStore {
14031403 self.live.subscribe()
14041404 }
14051405
1406+ fn announce(&self, topics: &[crate::live::Topic]) {
1407+ self.publish(topics.iter().cloned())
1408+ }
1409+
14061410 async fn provision_user(
14071411 &self,
14081412 sub: &str,
@@ -1592,7 +1596,7 @@ impl Store for TursoStore {
15921596 // provider-side rename or role flip, an owner claim. Anything louder
15931597 // would re-render every members-watching tab on every request.
15941598 if changed {
1595- self.announce([Topic::Members]);
1599+ self.publish([Topic::Members]);
15961600 }
15971601 self.user(&id).await?.ok_or(StoreError::NotFound)
15981602 }
@@ -1752,7 +1756,7 @@ impl Store for TursoStore {
17521756 tx.commit().await.map_err(backend)?;
17531757 drop(conn);
17541758 if sync != MemberSync::Untouched {
1755- self.announce([Topic::Members]);
1759+ self.publish([Topic::Members]);
17561760 }
17571761 Ok(sync)
17581762 }
@@ -1820,7 +1824,7 @@ impl Store for TursoStore {
18201824 Err(e) => return Err(backend(e)),
18211825 }
18221826 drop(conn);
1823- self.announce([Topic::Members]);
1827+ self.publish([Topic::Members]);
18241828 self.user(&id).await?.ok_or(StoreError::NotFound)
18251829 }
18261830
@@ -1879,7 +1883,7 @@ impl Store for TursoStore {
18791883 .await
18801884 .map_err(backend)?;
18811885 drop(conn);
1882- self.announce([Topic::Settings]);
1886+ self.publish([Topic::Settings]);
18831887 Ok(())
18841888 }
18851889
@@ -1898,7 +1902,7 @@ impl Store for TursoStore {
18981902 .await
18991903 .map_err(backend)?;
19001904 drop(conn);
1901- self.announce([Topic::Settings]);
1905+ self.publish([Topic::Settings]);
19021906 Ok(())
19031907 }
19041908
@@ -1917,7 +1921,7 @@ impl Store for TursoStore {
19171921 .await
19181922 .map_err(backend)?;
19191923 drop(conn);
1920- self.announce([Topic::Settings]);
1924+ self.publish([Topic::Settings]);
19211925 Ok(())
19221926 }
19231927
@@ -1951,7 +1955,7 @@ impl Store for TursoStore {
19511955 .await
19521956 .map_err(backend)?;
19531957 drop(conn);
1954- self.announce([Topic::Settings]);
1958+ self.publish([Topic::Settings]);
19551959 Ok(())
19561960 }
19571961
@@ -2003,7 +2007,7 @@ impl Store for TursoStore {
20032007 .await
20042008 .map_err(backend)?;
20052009 drop(conn);
2006- self.announce([Topic::Settings]);
2010+ self.publish([Topic::Settings]);
20072011 Ok(())
20082012 }
20092013
@@ -2026,6 +2030,14 @@ impl Store for TursoStore {
20262030 }
20272031 }
20282032
2033+ async fn user_by_sub(&self, sub: &str) -> Result<Option<User>> {
2034+ let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE oidc_sub = ?1");
2035+ match self.one_row(&sql, params![sub]).await? {
2036+ Some(row) => Ok(Some(user_from(&row)?)),
2037+ None => Ok(None),
2038+ }
2039+ }
2040+
20292041 async fn users(&self, workspace_id: &str) -> Result<Vec<User>> {
20302042 let conn = self.conn.lock().await;
20312043 let sql = format!(
@@ -2115,7 +2127,7 @@ impl Store for TursoStore {
21152127 Err(StoreError::NotFound)
21162128 } else {
21172129 drop(conn);
2118- self.announce([Topic::Members]);
2130+ self.publish([Topic::Members]);
21192131 Ok(())
21202132 }
21212133 }
@@ -2164,7 +2176,7 @@ impl Store for TursoStore {
21642176 }
21652177 tx.commit().await.map_err(backend)?;
21662178 drop(conn);
2167- self.announce(topics);
2179+ self.publish(topics);
21682180 Ok(())
21692181 }
21702182
@@ -2181,7 +2193,16 @@ impl Store for TursoStore {
21812193 Err(StoreError::NotFound)
21822194 } else {
21832195 drop(conn);
2184- self.announce([Topic::Members]);
2196+ // The member list moves either way. The kill naming is one
2197+ // directional: only a disable names the account's own open tabs
2198+ // so they can leave — an enable is a homecoming, and a frame
2199+ // saying "you were revoked" as the door reopens would send
2200+ // somebody away at the wrong moment.
2201+ if disabled {
2202+ self.publish([Topic::Members, Topic::Revoked(user_id.to_string())]);
2203+ } else {
2204+ self.publish([Topic::Members]);
2205+ }
21852206 Ok(())
21862207 }
21872208 }
@@ -2205,7 +2226,7 @@ impl Store for TursoStore {
22052226 .await
22062227 .map_err(backend)?;
22072228 drop(conn);
2208- self.announce([Topic::Board]);
2229+ self.publish([Topic::Board]);
22092230 Ok(Column {
22102231 id,
22112232 name: name.to_string(),
@@ -2393,7 +2414,7 @@ impl Store for TursoStore {
23932414 if reminded {
23942415 topics.push(Topic::Queue);
23952416 }
2396- self.announce(topics);
2417+ self.publish(topics);
23972418 let (task_key, position) = written;
23982419 Ok(TaskCreated {
23992420 row: TaskRow {
@@ -2495,7 +2516,7 @@ impl Store for TursoStore {
24952516 match outcome {
24962517 Ok(Ok(())) => {
24972518 tx.commit().await.map_err(backend)?;
2498- self.announce([Topic::Board, Topic::Task(task_id.to_string())]);
2519+ self.publish([Topic::Board, Topic::Task(task_id.to_string())]);
24992520 Ok(())
25002521 }
25012522 Ok(Err(refused)) => {
@@ -2575,7 +2596,7 @@ impl Store for TursoStore {
25752596 if reminded {
25762597 topics.push(Topic::Queue);
25772598 }
2578- self.announce(topics);
2599+ self.publish(topics);
25792600 }
25802601 Ok(())
25812602 }
@@ -2615,7 +2636,7 @@ impl Store for TursoStore {
26152636 if reminded {
26162637 topics.push(Topic::Queue);
26172638 }
2618- self.announce(topics);
2639+ self.publish(topics);
26192640 }
26202641 Ok(())
26212642 }
@@ -2721,7 +2742,7 @@ impl Store for TursoStore {
27212742 Ok(true) => {
27222743 tx.commit().await.map_err(backend)?;
27232744 // An edge is visible from both endpoints and on the board.
2724- self.announce([
2745+ self.publish([
27252746 Topic::Board,
27262747 Topic::Task(blocked_task_id.to_string()),
27272748 Topic::Task(blocking_task_id.to_string()),
@@ -2756,7 +2777,7 @@ impl Store for TursoStore {
27562777 .map_err(backend)?;
27572778 drop(conn);
27582779 if n > 0 {
2759- self.announce([
2780+ self.publish([
27602781 Topic::Board,
27612782 Topic::Task(blocked_task_id.to_string()),
27622783 Topic::Task(blocking_task_id.to_string()),
@@ -2811,7 +2832,7 @@ impl Store for TursoStore {
28112832 }
28122833 tx.commit().await.map_err(backend)?;
28132834
2814- self.announce([Topic::Task(task_id.to_string()), Topic::Activity]);
2835+ self.publish([Topic::Task(task_id.to_string()), Topic::Activity]);
28152836 Ok(CommentWritten {
28162837 comment_id,
28172838 activity_id,
@@ -2852,7 +2873,7 @@ impl Store for TursoStore {
28522873 return Err(backend(e));
28532874 }
28542875 drop(conn);
2855- self.announce([Topic::Task(new.task_id.to_string())]);
2876+ self.publish([Topic::Task(new.task_id.to_string())]);
28562877 Ok(id)
28572878 }
28582879
@@ -2932,7 +2953,7 @@ impl Store for TursoStore {
29322953 // the boot sweep collects.
29332954 let _ = std::fs::remove_file(attachment_file(&self.storage, id));
29342955 if let Some(task_id) = owner {
2935- self.announce([Topic::Task(task_id)]);
2956+ self.publish([Topic::Task(task_id)]);
29362957 }
29372958 }
29382959 Ok(gone > 0)
@@ -2951,7 +2972,7 @@ impl Store for TursoStore {
29512972 .await
29522973 .map_err(backend)?;
29532974 drop(conn);
2954- self.announce([Topic::Settings]);
2975+ self.publish([Topic::Settings]);
29552976 Ok(())
29562977 }
29572978
@@ -2986,7 +3007,7 @@ impl Store for TursoStore {
29863007 .await
29873008 .map_err(backend)?;
29883009 drop(conn);
2989- self.announce([Topic::Task(new.task_id.to_string())]);
3010+ self.publish([Topic::Task(new.task_id.to_string())]);
29903011 Ok(new.id)
29913012 }
29923013
@@ -3033,7 +3054,7 @@ impl Store for TursoStore {
30333054 // orphaned bytes the boot sweep collects.
30343055 let _ = std::fs::remove_file(attachment_file(&self.storage, id));
30353056 if let Some(task_id) = owner {
3036- self.announce([Topic::Task(task_id)]);
3057+ self.publish([Topic::Task(task_id)]);
30373058 }
30383059 }
30393060 Ok(moved > 0)
@@ -3055,7 +3076,7 @@ impl Store for TursoStore {
30553076 }
30563077
30573078 async fn announce_storage(&self) -> Result<()> {
3058- self.announce([Topic::Settings]);
3079+ self.publish([Topic::Settings]);
30593080 Ok(())
30603081 }
30613082
@@ -3171,7 +3192,7 @@ impl Store for TursoStore {
31713192 if reminded {
31723193 topics.push(Topic::Queue);
31733194 }
3174- self.announce(topics);
3195+ self.publish(topics);
31753196 Ok(ids)
31763197 }
31773198 Ok(None) => {
@@ -3374,7 +3395,7 @@ impl Store for TursoStore {
33743395 if reminded {
33753396 topics.push(Topic::Queue);
33763397 }
3377- self.announce(topics);
3398+ self.publish(topics);
33783399 Ok(Moved::Recorded(Transition {
33793400 id: transition_id,
33803401 task_id: task_id.to_string(),
@@ -3578,7 +3599,7 @@ impl Store for TursoStore {
35783599 if reminded {
35793600 topics.push(Topic::Queue);
35803601 }
3581- self.announce(topics);
3602+ self.publish(topics);
35823603 Ok(deletion)
35833604 }
35843605 Ok(None) => {
@@ -3694,7 +3715,7 @@ impl Store for TursoStore {
36943715 .map_err(backend)?;
36953716 drop(conn);
36963717 // Task-scoped: the task's own trail and the workspace feed both grew.
3697- self.announce([Topic::Activity, Topic::Task(task_id.to_string())]);
3718+ self.publish([Topic::Activity, Topic::Task(task_id.to_string())]);
36983719 Ok(id)
36993720 }
37003721
@@ -3716,7 +3737,7 @@ impl Store for TursoStore {
37163737 .map_err(backend)?;
37173738 drop(conn);
37183739 // Workspace-wide, belonging to no task — the feed only.
3719- self.announce([Topic::Activity]);
3740+ self.publish([Topic::Activity]);
37203741 Ok(id)
37213742 }
37223743
@@ -3754,7 +3775,7 @@ impl Store for TursoStore {
37543775 )
37553776 .await
37563777 .map_err(backend)?;
3757- self.announce([Topic::Rules]);
3778+ self.publish([Topic::Rules]);
37583779 let sql = format!("SELECT {RULE_COLUMNS} FROM mail_rule WHERE id = ?1");
37593780 match self.one_row(&sql, params![id]).await? {
37603781 Some(row) => rule_from(&row),
@@ -3804,7 +3825,7 @@ impl Store for TursoStore {
38043825 return Err(StoreError::NotFound);
38053826 }
38063827 drop(conn);
3807- self.announce([Topic::Rules]);
3828+ self.publish([Topic::Rules]);
38083829 Ok(())
38093830 }
38103831
@@ -3898,7 +3919,7 @@ impl Store for TursoStore {
38983919 return Err(StoreError::NotFound);
38993920 }
39003921 drop(conn);
3901- self.announce([Topic::Rules]);
3922+ self.publish([Topic::Rules]);
39023923 Ok(())
39033924 }
39043925
@@ -3915,7 +3936,7 @@ impl Store for TursoStore {
39153936 }
39163937 drop(conn);
39173938 // The rule's queued mail cascaded away with it, so the queue moved too.
3918- self.announce([Topic::Rules, Topic::Queue]);
3939+ self.publish([Topic::Rules, Topic::Queue]);
39193940 Ok(())
39203941 }
39213942
@@ -3979,7 +4000,7 @@ impl Store for TursoStore {
39794000 return Ok(None);
39804001 }
39814002 // A mail joined the queue, so the queue panel is out of date.
3982- self.announce([Topic::Queue]);
4003+ self.publish([Topic::Queue]);
39834004 let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1");
39844005 match self.one_row(&sql, params![id]).await? {
39854006 Some(row) => send_from(&row).map(ClaimedSend::taken).map(Some),
@@ -4009,7 +4030,7 @@ impl Store for TursoStore {
40094030 .map_err(backend)?;
40104031 // Two surfaces at once: the invite is a queued mail, and an invited
40114032 // person shows up in the members list before they ever sign in.
4012- self.announce([Topic::Queue, Topic::Members]);
4033+ self.publish([Topic::Queue, Topic::Members]);
40134034 let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1");
40144035 match self.one_row(&sql, params![id]).await? {
40154036 Some(row) => send_from(&row),
@@ -4037,7 +4058,7 @@ impl Store for TursoStore {
40374058 )
40384059 .await
40394060 .map_err(backend)?;
4040- self.announce([Topic::Queue]);
4061+ self.publish([Topic::Queue]);
40414062 let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1");
40424063 match self.one_row(&sql, params![id]).await? {
40434064 Some(row) => send_from(&row),
@@ -4064,7 +4085,7 @@ impl Store for TursoStore {
40644085 // whose subscribers may turn round and read this store, and holding
40654086 // the single connection while they do is how that deadlocks.
40664087 drop(conn);
4067- self.announce([Topic::Queue]);
4088+ self.publish([Topic::Queue]);
40684089 Ok(())
40694090 }
40704091
@@ -4103,7 +4124,7 @@ impl Store for TursoStore {
41034124 drop(conn);
41044125 // The attempt counter and the next-try time both just moved, and the
41054126 // queue panel renders both.
4106- self.announce([Topic::Queue]);
4127+ self.publish([Topic::Queue]);
41074128 Ok(())
41084129 }
41094130
@@ -4131,7 +4152,7 @@ impl Store for TursoStore {
41314152 return Err(StoreError::NotFound);
41324153 }
41334154 drop(conn);
4134- self.announce([Topic::Queue]);
4155+ self.publish([Topic::Queue]);
41354156 Ok(())
41364157 }
41374158
@@ -4261,7 +4282,7 @@ impl Store for TursoStore {
42614282 .await
42624283 .map_err(backend)?;
42634284 drop(conn);
4264- self.announce([Topic::Queue]);
4285+ self.publish([Topic::Queue]);
42654286 Ok(())
42664287 }
42674288
@@ -4297,7 +4318,7 @@ impl Store for TursoStore {
42974318 .map_err(backend)?;
42984319 drop(conn);
42994320 // A decision is what the rules page's decisions tab renders.
4300- self.announce([Topic::Rules]);
4321+ self.publish([Topic::Rules]);
43014322 Ok(())
43024323 }
43034324
@@ -4721,7 +4742,7 @@ impl Store for TursoStore {
47214742 .map_err(backend)?;
47224743 }
47234744 drop(conn);
4724- self.announce([Topic::Queue]);
4745+ self.publish([Topic::Queue]);
47254746 Ok(())
47264747 }
47274748
@@ -4840,7 +4861,7 @@ impl Store for TursoStore {
48404861 };
48414862 tx.commit().await.map_err(backend)?;
48424863
4843- self.announce([Topic::Board, Topic::Tags]);
4864+ self.publish([Topic::Board, Topic::Tags]);
48444865 Ok(Tag {
48454866 id,
48464867 board_id: board_id.to_string(),
@@ -4869,7 +4890,7 @@ impl Store for TursoStore {
48694890 return Err(StoreError::NotFound);
48704891 }
48714892 drop(conn);
4872- self.announce([Topic::Board, Topic::Tags]);
4893+ self.publish([Topic::Board, Topic::Tags]);
48734894 Ok(())
48744895 }
48754896
@@ -4941,7 +4962,7 @@ impl Store for TursoStore {
49414962 }
49424963 }
49434964 tx.commit().await.map_err(backend)?;
4944- self.announce([Topic::Board, Topic::Tags]);
4965+ self.publish([Topic::Board, Topic::Tags]);
49454966 Ok(())
49464967 }
49474968
@@ -5003,7 +5024,7 @@ impl Store for TursoStore {
50035024 }
50045025 }
50055026 tx.commit().await.map_err(backend)?;
5006- self.announce([Topic::Board, Topic::Tags]);
5027+ self.publish([Topic::Board, Topic::Tags]);
50075028 Ok(())
50085029 }
50095030
@@ -5032,7 +5053,7 @@ impl Store for TursoStore {
50325053 return Err(StoreError::NotFound);
50335054 }
50345055 drop(conn);
5035- self.announce([Topic::Board, Topic::Task(task_id.to_string()), Topic::Tags]);
5056+ self.publish([Topic::Board, Topic::Task(task_id.to_string()), Topic::Tags]);
50365057 Ok(())
50375058 }
50385059 }
crates/iz-core/tests/store.rsmodified+7 -3
@@ -5593,7 +5593,11 @@ fn every_writing_method_announces_or_is_named_here() {
55935593 || chunk.contains("INSERT OR ")
55945594 || chunk.contains("UPDATE ")
55955595 || chunk.contains("DELETE FROM");
5596- if writes && !chunk.contains("announce(") && !SILENT_ON_PURPOSE.contains(&name) {
5596+ if writes
5597+ && !chunk.contains("publish(")
5598+ && !chunk.contains("announce(")
5599+ && !SILENT_ON_PURPOSE.contains(&name)
5600+ {
55975601 silent.push(name.to_string());
55985602 }
55995603 }
@@ -5602,8 +5606,8 @@ fn every_writing_method_announces_or_is_named_here() {
56025606 silent.is_empty(),
56035607 "these methods change rows without announcing it, so the screens \
56045608 showing those rows will go stale until someone reloads by hand: {silent:?}. \
5605- Either call `self.announce(..)` after the write commits, or add the \
5606- method to SILENT_ON_PURPOSE with the reason."
5609+ Either call `self.publish(..)` (or the trait's `self.announce(..)`) after \
5610+ the write commits, or add the method to SILENT_ON_PURPOSE with the reason."
56075611 );
56085612 }
56095613
crates/iz-web/src/directory.rsmodified+431 -2
@@ -1,5 +1,9 @@
1-//! How the identity mirror stands against im — the facts the Settings
2-//! Connection card renders. The mirror task writes; the page reads.
1+//! How the identity mirror stands against im. Two halves: the facts the
2+//! Settings Connection card renders (the mirror task writes, the page
3+//! reads), and the live connection itself — held and parsed here rather
4+//! than through the pinned `im-client`, whose frame reader drops every
5+//! event kind it was not built for, and the feed now carries kinds this
6+//! app must hear.
37 //!
48 //! Deliberately dumb: one mutex over four plain fields, because the card
59 //! renders once per view and the stream updates a few times a minute. The
@@ -7,10 +11,14 @@
711 //! comes near this struct, so the render path cannot leak what it was never
812 //! given.
913
14+use std::collections::VecDeque;
1015 use std::sync::Arc;
1116 use std::time::{Duration, Instant};
1217
18+use iz_core::Topic;
19+use iz_core::store::Store;
1320 use parking_lot::Mutex;
21+use serde::Deserialize;
1422 use topcoat::context::{Cx, try_app_context};
1523
1624 /// The mirror's health, shared between the stream task and the renderer.
@@ -97,3 +105,424 @@ pub fn age_text(age: Option<Duration>) -> String {
97105 None => String::new(),
98106 }
99107 }
108+
109+/// Where the live half of the mirror connects. The same issuer and Basic
110+/// pair the roster client holds, kept apart from it because the stream is
111+/// read here, frame by frame, rather than through the pinned `im-client` —
112+/// whose parser drops every event kind it was not built for, and this feed
113+/// now carries kinds this app must hear.
114+#[derive(Clone)]
115+pub struct StreamSource {
116+ http: reqwest::Client,
117+ issuer: String,
118+ client_id: String,
119+ client_secret: String,
120+}
121+
122+impl StreamSource {
123+ pub fn new(
124+ issuer: impl Into<String>,
125+ client_id: impl Into<String>,
126+ client_secret: impl Into<String>,
127+ ) -> Self {
128+ Self {
129+ http: reqwest::Client::new(),
130+ issuer: issuer.into(),
131+ client_id: client_id.into(),
132+ client_secret: client_secret.into(),
133+ }
134+ }
135+
136+ /// `GET /directory/live`, the connection held with no timeout: a change
137+ /// feed is *supposed* to sit idle, and its liveness is im's keep-alive
138+ /// comment.
139+ pub async fn open_stream(&self) -> Result<DirectoryStream, String> {
140+ let response = self
141+ .http
142+ .get(format!("{}/directory/live", self.issuer))
143+ .basic_auth(&self.client_id, Some(&self.client_secret))
144+ .send()
145+ .await
146+ .map_err(|e| e.to_string())?
147+ .error_for_status()
148+ .map_err(|e| e.to_string())?;
149+ Ok(DirectoryStream {
150+ response,
151+ reader: FrameReader::default(),
152+ })
153+ }
154+}
155+
156+/// One member's row exactly as the stream carries it: the roster's shape
157+/// plus the `disabled` fact the roster itself never shows — im's
158+/// `/directory` lists nobody disabled, so the flag travels only here.
159+/// Unknown fields are ignored, so an im newer than this build can grow the
160+/// row without a breaking change.
161+#[derive(Debug, Clone, PartialEq, Deserialize)]
162+pub struct StreamMember {
163+ pub sub: String,
164+ pub email: String,
165+ pub name: String,
166+ #[serde(default)]
167+ pub admin: bool,
168+ #[serde(default)]
169+ pub photo_version: u64,
170+ #[serde(default = "default_timezone")]
171+ pub timezone: String,
172+ #[serde(default)]
173+ pub disabled: bool,
174+}
175+
176+/// The timezone im starts every account on, and the one a mirrored row
177+/// predating the field reads as.
178+fn default_timezone() -> String {
179+ "UTC+03:00".to_string()
180+}
181+
182+/// One event off im's `/directory/live`, parsed here rather than in the
183+/// pinned client because the consumer owes the wire more than the pin
184+/// knows: a `revoked` frame says a session died in im, and a `profile`
185+/// frame may now carry `disabled`.
186+#[derive(Debug, Clone, PartialEq)]
187+pub enum StreamFrame {
188+ /// The named member's row as it now stands.
189+ Profile(StreamMember),
190+ /// At least one of the member's sessions was revoked. Which one is
191+ /// im's knowledge alone; the consumer treats the fact workspace-wide.
192+ Revoked { sub: String },
193+}
194+
195+/// An open `/directory/live` connection. `next` mirrors the pinned
196+/// client's shape: `Some(Err)` on a wire failure — then the stream is
197+/// over — and `None` when im closed a healthy one. Either way the caller
198+/// re-lists and redials.
199+pub struct DirectoryStream {
200+ response: reqwest::Response,
201+ reader: FrameReader,
202+}
203+
204+impl DirectoryStream {
205+ pub async fn next(&mut self) -> Option<Result<StreamFrame, String>> {
206+ loop {
207+ if let Some(frame) = self.reader.ready.pop_front() {
208+ return Some(Ok(frame));
209+ }
210+ match self.response.chunk().await {
211+ Ok(Some(bytes)) => self.reader.feed(&bytes),
212+ Ok(None) => return None,
213+ Err(e) => return Some(Err(e.to_string())),
214+ }
215+ }
216+ }
217+}
218+
219+/// The hand-rolled `text/event-stream` reader. Frames accumulate field by
220+/// field and dispatch on the blank line, per the SSE grammar; the fields
221+/// this feed carries are `event`, `data`, and comments, but the parser
222+/// honors the whole shape — including `data` split over several lines,
223+/// which the spec joins with `\n`.
224+#[derive(Default)]
225+struct FrameReader {
226+ /// Bytes read but not yet through a line terminator.
227+ pending: Vec<u8>,
228+ /// The previous read ended on a bare `\r`, so the next read's leading
229+ /// `\n` — if that is what comes — completes that terminator rather
230+ /// than opening a blank line.
231+ cr_ended: bool,
232+ /// The current frame's `event:` field, if it named one.
233+ event: Option<String>,
234+ /// The current frame's `data:`, joined back into one string.
235+ data: String,
236+ /// Frames completed and waiting to be read.
237+ ready: VecDeque<StreamFrame>,
238+}
239+
240+impl FrameReader {
241+ /// Feeds the next bytes from the wire and queues every frame they
242+ /// completed. Bytes trailing their terminator wait for the rest — a
243+ /// field or a UTF-8 character may straddle two reads.
244+ fn feed(&mut self, bytes: &[u8]) {
245+ // The previous read stopped on a bare `\r`. A `\r\n` split across
246+ // two reads is ONE terminator: the pair's `\n` arriving here
247+ // completes the old one instead of opening a blank line and
248+ // dispatching a frame that has not ended.
249+ let bytes = if self.cr_ended {
250+ self.cr_ended = false;
251+ if bytes.first() == Some(&b'\n') {
252+ &bytes[1..]
253+ } else {
254+ bytes
255+ }
256+ } else {
257+ bytes
258+ };
259+ self.pending.extend_from_slice(bytes);
260+ let Some(at) = self
261+ .pending
262+ .iter()
263+ .rposition(|&b| b == b'\n' || b == b'\r')
264+ .map(|at| at + 1)
265+ else {
266+ return;
267+ };
268+ let block: Vec<u8> = self.pending.drain(..at).collect();
269+ self.cr_ended = block.last() == Some(&b'\r');
270+ for line in split_lines(&block) {
271+ if line.is_empty() {
272+ // The blank line dispatches whatever accumulated.
273+ if let Some(frame) = self.take() {
274+ self.ready.push_back(frame);
275+ }
276+ } else if line[0] == b':' {
277+ // A comment — im's keep-alives and retry hint live here.
278+ } else {
279+ let (name, value) = match line.iter().position(|&b| b == b':') {
280+ Some(at) => (&line[..at], &line[at + 1..]),
281+ None => (&line[..], &b""[..]),
282+ };
283+ // One optional space after the colon is not part of the
284+ // value.
285+ let value = value.strip_prefix(b" ").unwrap_or(value);
286+ match name {
287+ b"event" => self.event = Some(String::from_utf8_lossy(value).into_owned()),
288+ b"data" => {
289+ if !self.data.is_empty() {
290+ self.data.push('\n');
291+ }
292+ self.data.push_str(&String::from_utf8_lossy(value));
293+ }
294+ // `id` and `retry` mean nothing to a change feed.
295+ _ => {}
296+ }
297+ }
298+ }
299+ }
300+
301+ /// Ends the current frame and decides what it was. A frame whose kind
302+ /// this build does not know is skipped, not fatal: im may grow the
303+ /// feed, and one strange frame must not end a healthy connection. A
304+ /// known kind whose payload will not parse is logged and dropped for
305+ /// the same reason.
306+ fn take(&mut self) -> Option<StreamFrame> {
307+ let data = std::mem::take(&mut self.data);
308+ let event = self.event.take();
309+ match event.as_deref() {
310+ // A frame with no kind at all is an older im's bare member
311+ // announcement; it parses exactly as it always did.
312+ None | Some("profile") => match serde_json::from_str::<StreamMember>(&data) {
313+ Ok(member) => Some(StreamFrame::Profile(member)),
314+ Err(problem) => {
315+ eprintln!("directory stream: unreadable profile frame ({problem})");
316+ None
317+ }
318+ },
319+ Some("revoked") => match serde_json::from_str::<RevokedFrame>(&data) {
320+ Ok(frame) => Some(StreamFrame::Revoked { sub: frame.sub }),
321+ Err(problem) => {
322+ eprintln!("directory stream: unreadable revoked frame ({problem})");
323+ None
324+ }
325+ },
326+ // A kind from an im newer than this build.
327+ Some(_) => None,
328+ }
329+ }
330+}
331+
332+/// The `{"sub": ...}` payload a `revoked` frame carries.
333+#[derive(Deserialize)]
334+struct RevokedFrame {
335+ sub: String,
336+}
337+
338+/// Splits a block that ends at a line terminator into lines, accepting the
339+/// three SSE terminators: `\n`, `\r\n`, and a bare `\r`. A blank line is a
340+/// frame's dispatch, so it is kept — only the terminator run itself
341+/// disappears.
342+fn split_lines(block: &[u8]) -> Vec<Vec<u8>> {
343+ let mut lines = Vec::new();
344+ let mut start = 0usize;
345+ let mut at = 0usize;
346+ while at < block.len() {
347+ if block[at] == b'\n' || block[at] == b'\r' {
348+ lines.push(block[start..at].to_vec());
349+ if block[at] == b'\r' && block.get(at + 1) == Some(&b'\n') {
350+ at += 1;
351+ }
352+ at += 1;
353+ start = at;
354+ } else {
355+ at += 1;
356+ }
357+ }
358+ if start < block.len() {
359+ lines.push(block[start..].to_vec());
360+ }
361+ lines
362+}
363+
364+/// Carries one consumed frame into the local mirror — the one door both
365+/// the stream task and the tests use, so a frame means the same thing no
366+/// matter who fed it.
367+///
368+/// * A profile syncs the row the way the roster pass does, and im owns the
369+/// account's life: a profile whose `disabled` disagrees with the local
370+/// row flips it through the same store path an admin's hand uses —
371+/// `true` is a user-level kill whose store announcement names the
372+/// account's own open tabs, `false` is the homecoming that signs the
373+/// row back in.
374+/// * A revoked frame is a session fact — which session died is im's
375+/// knowledge alone, and a tab whose *other* session survived must not be
376+/// sent away — so it only announces the member surface. Every tab's
377+/// refetch re-introspects per request, and that is what sorts out who is
378+/// still signed in.
379+pub async fn apply_frame(store: &Arc<dyn Store>, frame: StreamFrame) {
380+ match frame {
381+ StreamFrame::Profile(member) => {
382+ if let Err(problem) = store
383+ .sync_member(
384+ &member.sub,
385+ &member.email,
386+ &member.name,
387+ member.admin,
388+ member.photo_version,
389+ &member.timezone,
390+ )
391+ .await
392+ {
393+ eprintln!("directory stream: {}: {problem}", member.email);
394+ }
395+ match store.user_by_sub(&member.sub).await {
396+ Ok(Some(user)) if user.disabled != member.disabled => {
397+ if let Err(problem) = store.set_user_disabled(&user.id, member.disabled).await
398+ {
399+ eprintln!("directory stream: {}: {problem}", member.email);
400+ }
401+ }
402+ Ok(_) => {}
403+ Err(problem) => {
404+ eprintln!("directory stream: {}: {problem}", member.email);
405+ }
406+ }
407+ }
408+ StreamFrame::Revoked { .. } => {
409+ store.announce(&[Topic::Members]);
410+ }
411+ }
412+}
413+
414+#[cfg(test)]
415+mod tests {
416+ use super::*;
417+
418+ fn frames(wire: &str) -> Vec<StreamFrame> {
419+ let mut reader = FrameReader::default();
420+ reader.feed(wire.as_bytes());
421+ reader.ready.drain(..).collect()
422+ }
423+
424+ fn member(sub: &str, email: &str, name: &str, disabled: bool) -> StreamMember {
425+ StreamMember {
426+ sub: sub.into(),
427+ email: email.into(),
428+ name: name.into(),
429+ admin: false,
430+ photo_version: 0,
431+ timezone: "UTC+03:00".into(),
432+ disabled,
433+ }
434+ }
435+
436+ /// A kind this build has never heard of is skipped where it stands —
437+ /// the frames on either side of it still land, and the reader is alive
438+ /// for the next bytes.
439+ #[test]
440+ fn an_unknown_event_kind_is_skipped_and_the_stream_lives_on() {
441+ let wire = concat!(
442+ ": keep-alive\n",
443+ "event: profile\n",
444+ "data: {\"sub\":\"s1\",\"email\":\"a@iz.sh\",\"name\":\"A\"}\n",
445+ "\n",
446+ "event: logrollover\n",
447+ "data: {\"whatever\":true}\n",
448+ "\n",
449+ "event: revoked\n",
450+ "data: {\"sub\":\"s1\"}\n",
451+ "\n",
452+ "event: profile\n",
453+ "data: {\"sub\":\"s2\",\"email\":\"b@iz.sh\",\"name\":\"B\",\"disabled\":true}\n",
454+ "\n",
455+ );
456+ assert_eq!(
457+ frames(wire),
458+ vec![
459+ StreamFrame::Profile(member("s1", "a@iz.sh", "A", false)),
460+ StreamFrame::Revoked { sub: "s1".into() },
461+ StreamFrame::Profile(member("s2", "b@iz.sh", "B", true)),
462+ ]
463+ );
464+ }
465+
466+ /// im predating the `event:` field altogether announces bare member
467+ /// frames; unknown fields on a known frame are ignored, so a newer im
468+ /// may grow the row without a breaking change.
469+ #[test]
470+ fn a_bare_frame_from_an_older_im_still_parses() {
471+ let wire = concat!(
472+ "data: {\"sub\":\"s1\",\"email\":\"a@iz.sh\",\"name\":\"A\",\"voltage\":9}\n",
473+ "\n",
474+ );
475+ let seen = frames(wire);
476+ assert_eq!(
477+ seen,
478+ vec![StreamFrame::Profile(member("s1", "a@iz.sh", "A", false))]
479+ );
480+ }
481+
482+ /// A frame cut in the middle of its JSON is held until its rest
483+ /// arrives; nothing is lost and nothing is dispatched early.
484+ #[test]
485+ fn a_frame_straddling_two_reads_is_not_lost() {
486+ let mut reader = FrameReader::default();
487+ reader.feed(b"event: revoked\ndata: {\"su");
488+ assert!(reader.ready.is_empty());
489+ reader.feed(b"b\":\"s9\"}\n\n");
490+ assert_eq!(
491+ reader.ready.drain(..).collect::<Vec<_>>(),
492+ vec![StreamFrame::Revoked { sub: "s9".into() }]
493+ );
494+ }
495+
496+ /// A `\r\n` pair split across two reads stays one terminator: the
497+ /// trailing `\r` of a read must not let the next read's leading `\n`
498+ /// arrive as a blank line and dispatch a frame that has not ended.
499+ /// The cut here is exactly at the terminator of the one data line;
500+ /// the blank line that follows in the next read is what dispatches.
501+ #[test]
502+ fn a_crlf_pair_split_across_reads_is_one_terminator() {
503+ let mut reader = FrameReader::default();
504+ reader.feed(b"data: {\"sub\":\"s1\",\"email\":\"a@iz.sh\",\"name\":\"A\"}\r");
505+ assert!(reader.ready.is_empty(), "a cut terminator dispatched early");
506+ reader.feed(b"\n\r\n");
507+ assert_eq!(
508+ reader.ready.drain(..).collect::<Vec<_>>(),
509+ vec![StreamFrame::Profile(member("s1", "a@iz.sh", "A", false))]
510+ );
511+ }
512+
513+ /// The same hold with a named kind: the `\r` after `event: revoked` is
514+ /// a field line's end, not the frame's — draining it would let the
515+ /// next read open with a blank line and burn the frame on an empty
516+ /// payload, losing the revocation for good.
517+ #[test]
518+ fn a_trailing_cr_after_the_event_field_does_not_burn_the_frame() {
519+ let mut reader = FrameReader::default();
520+ reader.feed(b"event: revoked\r");
521+ assert!(reader.ready.is_empty());
522+ reader.feed(b"\ndata: {\"sub\":\"s9\"}\r\n\r\n");
523+ assert_eq!(
524+ reader.ready.drain(..).collect::<Vec<_>>(),
525+ vec![StreamFrame::Revoked { sub: "s9".into() }]
526+ );
527+ }
528+}
crates/iz-web/src/layout.rsmodified+14 -0
@@ -896,6 +896,14 @@ pub async fn soft_nav_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> {
896896 /// disagree with it — the tick re-fetches, and the server stays the only thing
897897 /// that decides what a moment reads as. It runs only on pages carrying a
898898 /// `data-tick` element, so a page with no clock-driven text is silent.
899+/// The channel also carries one goodbye: a `revoked` frame means this
900+/// tab's account was killed at the provider, and the answer is a hard
901+/// redirect to the front door, not a morph. A dropped stream is the other
902+/// way a tab learns it may be alone: the error path asks `/api/me`, and a
903+/// `401` there is the same redirect. A merely restarting server answers
904+/// 204, so a signed-in tab loses nothing — the `EventSource` reconnects
905+/// on its own.
906+///
899907 pub async fn live_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> {
900908 const JS: &str = "\
901909 (function () { \
@@ -925,8 +933,14 @@ pub async fn live_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> {
925933 src.onmessage = function (e) { \
926934 var frame; \
927935 try { frame = JSON.parse(e.data); } catch (err) { return; } \
936+ if (frame && frame.topic === 'revoked') { window.location.href = '/'; return; } \
928937 if (frame && wanted(frame.topic)) { schedule(); } \
929938 }; \
939+ src.onerror = function () { \
940+ fetch('/api/me', { cache: 'no-store' }).then(function (r) { \
941+ if (r.status === 401) { window.location.href = '/'; } \
942+ }).catch(function () { }); \
943+ }; \
930944 } catch (err) { } \
931945 setInterval(function () { \
932946 if (document.querySelector('[data-tick]')) { refresh(); } \
crates/iz-web/src/live.rsmodified+29 -7
@@ -47,18 +47,24 @@ impl Default for LiveWindow {
4747 #[derive(Clone)]
4848 pub struct Shutdown(pub tokio::sync::watch::Receiver<bool>);
4949
50-/// Whether a reader of this role may be told that this surface moved.
50+/// Whether a reader may be told that this surface moved.
5151 ///
5252 /// The board, a task and the member list are what every signed-in person
5353 /// already sees. The queue, the rules, the settings and the activity log are
5454 /// admin screens, and CLAUDE.md's rule — a role that cannot act on a surface
5555 /// does not see it — reaches the channel too: a member is not told the queue
5656 /// moved, because being told is itself knowing something about the queue.
57-fn may_hear(topic: &Topic, admin: bool) -> bool {
57+///
58+/// The one topic that is neither surface nor role is [`Topic::Revoked`]: the
59+/// account it names was killed at the provider, and the only reader it may be
60+/// named to is the reader it names — hearing it says nothing about anybody
61+/// else.
62+fn may_hear(topic: &Topic, reader_id: &str, admin: bool) -> bool {
5863 match topic {
5964 // Tags ride with the board: every member sees a card's tag, so being
6065 // told the tags moved tells them nothing they cannot already read.
6166 Topic::Board | Topic::Task(_) | Topic::Members | Topic::Tags => true,
67+ Topic::Revoked(id) => id == reader_id,
6268 Topic::Queue | Topic::Rules | Topic::Settings | Topic::Activity => admin,
6369 }
6470 }
@@ -92,9 +98,15 @@ async fn live(cx: &Cx) -> topcoat::Result<Response> {
9298 let deadline = Instant::now() + try_app_context::<LiveWindow>(cx).copied().unwrap_or_default().0;
9399
94100 let events = futures_util::stream::unfold(
95- (rx, admin, deadline, stopping),
96- |(mut rx, admin, deadline, mut stopping)| async move {
101+ (rx, admin, deadline, stopping, user.id.clone(), false),
102+ |(mut rx, admin, deadline, mut stopping, reader_id, mut done)| async move {
97103 loop {
104+ // The goodbye frame went out with the last pass: the account
105+ // this reader signed in as was named killed, and there is
106+ // nothing left to say.
107+ if done {
108+ return None;
109+ }
98110 // Already going down: say nothing and end, so this connection
99111 // is not one the shutdown has to sit and wait out.
100112 if stopping.as_ref().is_some_and(|watch| *watch.borrow()) {
@@ -130,21 +142,31 @@ async fn live(cx: &Cx) -> topcoat::Result<Response> {
130142 // after. The stream stays open — a slow moment is not a fault.
131143 Ok(Some(Err(RecvError::Lagged(_)))) => Event::new().data(RESYNC),
132144 Ok(Some(Ok(Change { topic, seq }))) => {
133- if !may_hear(&topic, admin) {
145+ if !may_hear(&topic, &reader_id, admin) {
134146 // Not merely unsent: never named. A member's
135147 // connection carries no evidence the queue exists.
136148 continue;
137149 }
150+ // The reader's own account was named: this frame is
151+ // the goodbye, and the stream ends right behind it —
152+ // the tab leaves for the front door rather than
153+ // morphing a workspace it can no longer read.
154+ if matches!(topic, Topic::Revoked(_)) {
155+ done = true;
156+ }
138157 let frame = Frame { topic: topic.kind(), id: topic.id(), seq };
139158 match Event::new().json_data(&frame) {
140159 Ok(event) => event,
141160 Err(problem) => {
142- return Some((Err(problem), (rx, admin, deadline, stopping)));
161+ return Some((
162+ Err(problem),
163+ (rx, admin, deadline, stopping, reader_id, done),
164+ ));
143165 }
144166 }
145167 }
146168 };
147- return Some((Ok(frame), (rx, admin, deadline, stopping)));
169+ return Some((Ok(frame), (rx, admin, deadline, stopping, reader_id, done)));
148170 }
149171 },
150172 );
crates/iz-web/src/main.rsmodified+15 -6
@@ -189,6 +189,11 @@ async fn main() {
189189 tokio::spawn(directory_stream(
190190 store.clone(),
191191 directory.clone(),
192+ iz_web::directory::StreamSource::new(
193+ config.oidc.issuer.clone(),
194+ config.oidc.client_id.clone(),
195+ config.oidc.client_secret.clone(),
196+ ),
192197 health.clone(),
193198 ));
194199 // The storage mirror's watchdog: follows the family to wherever in
@@ -487,7 +492,10 @@ async fn apply_member(
487492 }
488493
489494 /// The live half of the mirror: im's `/directory/live`, one event per
490-/// changed member. Forever, in this shape: a full pass, then the stream;
495+/// changed member — plus the `revoked` kind the pinned client's parser
496+/// drops, which is why the connection and its frames are
497+/// [`iz_web::directory`]'s and only the roster pass still rides the
498+/// pinned client. Forever, in this shape: a full pass, then the stream;
491499 /// whenever the stream ends — im restarting, or its fifty-minute window
492500 /// closing — wait out a backoff that doubles from one second to thirty,
493501 /// replay a full pass (the resync that heals whatever the dead stream
@@ -499,20 +507,21 @@ async fn apply_member(
499507 async fn directory_stream(
500508 store: Arc<dyn iz_core::store::Store>,
501509 directory: im_client::directory::DirectoryClient,
510+ source: iz_web::directory::StreamSource,
502511 health: iz_web::directory::DirectoryHealth,
503512 ) {
504513 let mut backoff = std::time::Duration::from_secs(1);
505514 loop {
506515 mirror_directory(&store, &directory, &health).await;
507- match directory.open_stream().await {
516+ match source.open_stream().await {
508517 Ok(mut stream) => {
509518 health.connected();
510519 backoff = std::time::Duration::from_secs(1);
511- while let Some(event) = stream.next().await {
512- match event {
513- Ok(im_client::directory::DirectoryEvent::Profile(member)) => {
520+ while let Some(frame) = stream.next().await {
521+ match frame {
522+ Ok(frame) => {
514523 health.event();
515- apply_member(&store, &member).await;
524+ iz_web::directory::apply_frame(&store, frame).await;
516525 }
517526 Err(problem) => {
518527 eprintln!("directory stream: {problem}; re-listing");
crates/iz-web/src/server.rsmodified+18 -1
@@ -20,7 +20,10 @@ use topcoat::asset::AssetBundle;
2020 use topcoat::context::{Cx, app_context, memoize, try_app_context};
2121 use topcoat::cookie::{Cookies, cookies};
2222 use topcoat::router::request::headers;
23-use topcoat::router::{Body, HeaderValue, Next, StatusCode, header, response::Response, to_bytes};
23+use topcoat::router::{
24+ route, Body, HeaderValue, Next, StatusCode, header, response::IntoResponse, response::Response,
25+ to_bytes,
26+};
2427
2528 /// The workspace store, put into context by the router.
2629 pub fn store(cx: &Cx) -> Arc<dyn Store> {
@@ -328,6 +331,20 @@ pub async fn require_writer(cx: &Cx) -> Result<User, Refusal> {
328331 }
329332 }
330333
334+/// The lightweight am-I-signed-in probe the live script's error path asks:
335+/// `204` with no body when the caller carries a live session, `401` when
336+/// anything about the caller — no cookie, a revoked or disabled one, a
337+/// store that cannot answer — says otherwise. It exists so a dropped live
338+/// stream can tell "the server restarted" from "I was signed out" without
339+/// fetching a page of HTML to learn it.
340+#[route(GET "/api/me")]
341+async fn me(cx: &Cx) -> topcoat::Result<Response> {
342+ match current_user(cx).await {
343+ Ok(Some(_)) => StatusCode::NO_CONTENT.into_response(cx),
344+ _ => (StatusCode::UNAUTHORIZED, "").into_response(cx),
345+ }
346+}
347+
331348 impl From<StoreError> for Refusal {
332349 fn from(error: StoreError) -> Self {
333350 eprintln!("store error: {error}");
crates/iz-web/tests/http.rsmodified+175 -0
@@ -28,6 +28,7 @@ use http::{HeaderValue, Request, StatusCode, header};
2828 use iz_core::Role;
2929 use iz_core::board::Moved;
3030 use iz_core::store::{Audience, MailOutcome, SendKind, SendState, Store, Trigger, TursoStore};
31+use iz_web::directory::{StreamFrame, StreamMember, apply_frame};
3132 use iz_web::server::Mail;
3233 use topcoat::asset::{AssetBundle, RouterBuilderAssetExt};
3334 use topcoat::cookie::RouterBuilderCookieExt;
@@ -7532,6 +7533,180 @@ async fn a_queued_mails_next_try_is_marked_for_the_tick() {
75327533 );
75337534 }
75347535
7536+/// The lightweight probe the live script's error path asks. A live session
7537+/// gets a bodyless yes; no cookie, or a session im no longer vouches for,
7538+/// gets a plain 401 — so a dropped stream can be told apart from a signed-
7539+/// out tab without fetching a page of HTML to learn it.
7540+#[tokio::test]
7541+async fn the_me_probe_answers_yes_only_to_a_live_session() {
7542+ let app = App::open().await;
7543+ let boss = admin(&app).await;
7544+
7545+ let live = app.get("/api/me", Some(&boss)).await;
7546+ assert_eq!(live.status, StatusCode::NO_CONTENT);
7547+ assert!(live.bytes.is_empty(), "the probe answered a body");
7548+
7549+ let stranger = app.get("/api/me", None).await;
7550+ assert_eq!(stranger.status, StatusCode::UNAUTHORIZED);
7551+
7552+ // The session revoked in im: once the fake stops vouching for the
7553+ // token, the probe refuses with no page to fetch first.
7554+ app.fake.tokens.lock().clear();
7555+ let revoked = app.get("/api/me", Some(&boss)).await;
7556+ assert_eq!(revoked.status, StatusCode::UNAUTHORIZED);
7557+}
7558+
7559+/// A session revocation heard off the directory stream is told to the whole
7560+/// workspace — which session died is im's knowledge alone, so no connection
7561+/// is named and no tab is sent away; every tab's own refetch, which
7562+/// re-introspects per request, is what sorts out who is still signed in.
7563+/// A tab whose other session survived therefore keeps its place.
7564+#[tokio::test]
7565+async fn a_session_revocation_announces_the_member_surface_to_everyone() {
7566+ let app = App::open().await;
7567+ let boss = admin(&app).await;
7568+ let bo = invited(&app, &boss, "bo@iz.sh", "Bo", Role::Member).await;
7569+
7570+ let member_feed = app.live_open(Some(&bo)).await;
7571+ let admin_feed = app.live_open(Some(&boss)).await;
7572+
7573+ apply_frame(
7574+ &app.store,
7575+ StreamFrame::Revoked {
7576+ sub: "im-bo@iz.sh".into(),
7577+ },
7578+ )
7579+ .await;
7580+
7581+ let heard_by_admin =
7582+ live_until(admin_feed, "members", std::time::Duration::from_secs(10)).await;
7583+ assert!(
7584+ heard_by_admin.contains("members"),
7585+ "no members announcement: {heard_by_admin}"
7586+ );
7587+ let heard_by_member = live_until(
7588+ member_feed,
7589+ "members",
7590+ std::time::Duration::from_millis(500),
7591+ )
7592+ .await;
7593+ assert!(
7594+ heard_by_member.contains("members"),
7595+ "the member was not told the member surface moved: {heard_by_member}"
7596+ );
7597+ assert!(
7598+ !heard_by_admin.contains("revoked") && !heard_by_member.contains("revoked"),
7599+ "a session revocation named a connection: {heard_by_admin} / {heard_by_member}"
7600+ );
7601+}
7602+
7603+/// A profile arriving `disabled` is a user-level kill: the local row is
7604+/// disabled through the same store path an admin's hand uses, the
7605+/// account's own tab is named with the `revoked` topic — and only that
7606+/// tab — and the row's next probe reads as signed out, exactly as any
7607+/// refetch would find it.
7608+#[tokio::test]
7609+async fn a_disabled_member_is_named_once_and_signed_out_everywhere() {
7610+ let app = App::open().await;
7611+ let boss = admin(&app).await;
7612+ let bo = invited(&app, &boss, "bo@iz.sh", "Bo", Role::Member).await;
7613+
7614+ let member_feed = app.live_open(Some(&bo)).await;
7615+ let admin_feed = app.live_open(Some(&boss)).await;
7616+
7617+ apply_frame(
7618+ &app.store,
7619+ StreamFrame::Profile(StreamMember {
7620+ sub: "im-bo@iz.sh".into(),
7621+ email: "bo@iz.sh".into(),
7622+ name: "Bo".into(),
7623+ admin: false,
7624+ photo_version: 0,
7625+ timezone: "UTC+03:00".into(),
7626+ disabled: true,
7627+ }),
7628+ )
7629+ .await;
7630+
7631+ // The account's own connection is named — the goodbye frame the client
7632+ // answers with a hard redirect.
7633+ let goodbye = live_until(member_feed, "revoked", std::time::Duration::from_secs(10)).await;
7634+ assert!(
7635+ goodbye.contains("revoked"),
7636+ "the disabled member's tab was not named: {goodbye}"
7637+ );
7638+
7639+ // The workspace heard the member surface move; nobody else was named.
7640+ let heard_by_admin =
7641+ live_until(admin_feed, "members", std::time::Duration::from_secs(10)).await;
7642+ assert!(
7643+ heard_by_admin.contains("members"),
7644+ "no members announcement: {heard_by_admin}"
7645+ );
7646+ assert!(
7647+ !heard_by_admin.contains("revoked"),
7648+ "an uninvolved tab was named: {heard_by_admin}"
7649+ );
7650+
7651+ // The row itself, and the seam every refetch would hit.
7652+ let user = app
7653+ .store
7654+ .user_by_sub("im-bo@iz.sh")
7655+ .await
7656+ .unwrap()
7657+ .expect("the disabled member had no local row");
7658+ assert!(user.disabled);
7659+ assert_eq!(
7660+ app.get("/api/me", Some(&bo)).await.status,
7661+ StatusCode::UNAUTHORIZED
7662+ );
7663+}
7664+
7665+/// im owns the account's life both ways: the same stream that kills the
7666+/// row brings it back. A disable lands, then a re-enable — the local flag
7667+/// follows each, and the member's own probe reads signed-in again, with
7668+/// no revoked naming on the way back in.
7669+#[tokio::test]
7670+async fn a_reenabled_member_is_signed_back_in() {
7671+ let app = App::open().await;
7672+ let _boss = admin(&app).await;
7673+ let bo = member(&app, "bo@iz.sh", "Bo").await;
7674+
7675+ let disabled = StreamMember {
7676+ sub: "im-bo@iz.sh".into(),
7677+ email: "bo@iz.sh".into(),
7678+ name: "Bo".into(),
7679+ admin: false,
7680+ photo_version: 0,
7681+ timezone: "UTC+03:00".into(),
7682+ disabled: true,
7683+ };
7684+ apply_frame(&app.store, StreamFrame::Profile(disabled.clone())).await;
7685+ assert!(
7686+ app.store
7687+ .user_by_sub("im-bo@iz.sh")
7688+ .await
7689+ .unwrap()
7690+ .expect("no local row")
7691+ .disabled,
7692+ "the stream did not disable the row"
7693+ );
7694+
7695+ let enabled = StreamMember { disabled: false, ..disabled };
7696+ apply_frame(&app.store, StreamFrame::Profile(enabled)).await;
7697+ assert!(
7698+ !app
7699+ .store
7700+ .user_by_sub("im-bo@iz.sh")
7701+ .await
7702+ .unwrap()
7703+ .expect("no local row")
7704+ .disabled,
7705+ "the stream did not re-enable the row"
7706+ );
7707+ assert_eq!(app.get("/api/me", Some(&bo)).await.status, StatusCode::NO_CONTENT);
7708+}
7709+
75357710 /// A live update changes only what actually changed. It morphs the fetched
75367711 /// document onto the live one instead of replacing the body, which is what
75377712 /// leaves an open dropdown open, a caret where it was and a half-typed comment