forge
Explore
Log in

Don't you dare go Hollow

A theme, accent or sidebar change reaches every open tab, and a revoked session leaves live

Browse files at this commit

00ca6f770b05ec77ac7e6e41c00b284bafe97005Ahmet Kaan GümüşParent: d7d6a17
  • feat
    • a theme, accent or sidebar change reaches every open tab, and a revoked session leaves live
Show full message
⚡ feat: a theme, accent or sidebar change reaches every open tab, and a revoked session leaves live
crates/forge-web/assets/nav.jsmodified+18 -3
@@ -381,7 +381,10 @@
381381 }
382382 var dest = new URL(res.url.href);
383383 dest.hash = o.dest.hash;
384- swap(res.html, dest, o.how, !!o.keep && res.url.pathname === o.target.pathname);
384+ // A live refresh that lands on another path (a revoked session sent to the login page) is a
385+ // navigation: it gets a history entry, so the address bar shows where the page now is.
386+ var how = o.how === 'live' && res.url.pathname !== o.target.pathname ? 'nav' : o.how;
387+ swap(res.html, dest, how, !!o.keep && res.url.pathname === o.target.pathname);
385388 }).catch(function () {
386389 if (mark !== latest || o.how === 'live') { return; }
387390 if (o.post) { o.form.submit(); } else { location.assign(o.dest.href); }
@@ -461,11 +464,12 @@
461464 // One EventSource that stays open. The browser reconnects by itself, except when a proxy answers
462465 // with an error: EventSource then closes for good, so it is opened again here after 1, 2, then 3 s.
463466 // `restart()` reconnects at once.
464- function keepOpen(url, onOpen, onError) {
467+ function keepOpen(url, onOpen, onError, onTheme) {
465468 var es = null, delay = 1000, timer = null;
466469 function connect() {
467470 timer = null;
468471 es = new EventSource(url);
472+ if (onTheme) { es.addEventListener('theme', function (e) { onTheme(e.data); }); }
469473 es.onopen = function () { delay = 1000; onOpen(); };
470474 es.onerror = function () {
471475 onError();
@@ -488,7 +492,18 @@
488492
489493 // Every page holds one stream to /-/alive (no data, no login). Its error means the server, or the
490494 // proxy in front of it, is down; its open means it is back.
491- if (window.EventSource) { alive = keepOpen('/-/alive', linkBack, linkDown); }
495+ // A `theme` event carries the signed-in user's appearance as `name=value` pairs joined by `;`
496+ // (the `<html>` attributes). An empty value removes the attribute. Only data-* names are applied.
497+ function applyAppearance(data) {
498+ String(data).split(';').forEach(function (pair) {
499+ var i = pair.indexOf('=');
500+ if (i < 0) { return; }
501+ var name = pair.slice(0, i), value = pair.slice(i + 1);
502+ if (name.indexOf('data-') !== 0) { return; }
503+ if (value) { root.setAttribute(name, value); } else { root.removeAttribute(name); }
504+ });
505+ }
506+ if (window.EventSource) { alive = keepOpen('/-/alive', linkBack, linkDown, applyAppearance); }
492507 if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(function () {}); }
493508
494509 // The form to send a queued change on: the form itself, or after a swap the one with the same action.
crates/forge-web/src/auth.rsmodified+4 -4
@@ -102,10 +102,10 @@ pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> {
102102
103103 /// Deletes the session row and clears the cookie.
104104 pub async fn logout(cx: &Cx, session: &Session) -> forge_core::Result<()> {
105- app_context::<AppState>(cx)
106- .store
107- .delete_session(&session.id)
108- .await?;
105+ let state = app_context::<AppState>(cx);
106+ state.store.delete_session(&session.id).await?;
107+ // The user's other tabs may show this session (a page that now leaves for the login page).
108+ crate::pages::settings_live::bump_account(state, &session.user_id);
109109 session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/"));
110110 Ok(())
111111 }
crates/forge-web/src/pages/admin_mail.rsmodified+0 -4
@@ -948,10 +948,6 @@ mod tests {
948948 settings.contains(r#"data-live="/admin/mail/events""#),
949949 "the settings tab is live too"
950950 );
951- assert!(
952- settings.contains(r#"data-live="/settings/theme/events""#),
953- "the theme follows into the admin pages"
954- );
955951 assert!(
956952 !settings.contains("Reset your password"),
957953 "the queue is on its own tab"
crates/forge-web/src/pages/admin_server.rsmodified+0 -1
@@ -886,7 +886,6 @@ mod tests {
886886 let page = admin_get(&fx, "/admin/server?restarting=an-older-boot").await;
887887 assert!(!page.contains("Restarting..."));
888888 assert!(page.contains(r#"data-live="/admin/server/events""#));
889- assert!(page.contains(r#"data-live="/settings/theme/events""#));
890889 assert!(page.contains("The server restarted"));
891890 }
892891
crates/forge-web/src/pages/admin_user_detail.rsmodified+5 -0
@@ -381,6 +381,11 @@ async fn perform(cx: &Cx, form: &ActionForm, action: Action) -> Result<(Outcome,
381381 .await
382382 {
383383 Ok(()) => {
384+ // A suspension ends the user's sessions: their open tabs must see it.
385+ crate::pages::settings_live::bump_account(
386+ app_context::<AppState>(cx),
387+ &target.id,
388+ );
384389 audit(
385390 AuditAction::UserSuspended,
386391 serde_json::json!({ "reason": form.reason.trim() }),
crates/forge-web/src/pages/admin_users.rsmodified+2 -0
@@ -410,6 +410,8 @@ async fn user_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl View>
410410 let ghost = store.ensure_ghost_user().await?;
411411 match store.delete_user(&target.id, &ghost.id).await {
412412 Ok(_) => {
413+ // Their sessions and keys are gone: any open tab of theirs must leave.
414+ crate::pages::settings_live::bump_account(app_context::<AppState>(cx), &target.id);
413415 audit::record(
414416 store,
415417 Some(cx),
crates/forge-web/src/pages/assets.rsmodified+2 -5
@@ -3,14 +3,11 @@
33
44 use std::sync::OnceLock;
55
6-use futures_util::stream;
76 use topcoat::Result;
87 use topcoat::context::Cx;
9-use topcoat::router::content::sse::Event;
108 use topcoat::router::response::Response;
119 use topcoat::router::{HeaderMap, StatusCode, header, route};
1210
13-use crate::pages::ci_runs::events_response;
1411 use crate::render::highlight::highlight_css;
1512
1613 const CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css"));
@@ -123,10 +120,10 @@ async fn offline_js() -> Result<(StatusCode, HeaderMap, &'static str)> {
123120
124121 /// The stream every page and the offline page watch to learn that the server is back. It carries
125122 /// no data and needs no login: it sends `retry`, then holds the connection open with keep-alive
126-/// comments. A dropped connection (or a proxy's 502 while forge restarts) is what the pages watch for.
123+/// comments. A signed-in viewer also gets `theme` events (see `settings_live::alive_response`). A dropped connection (or a proxy's 502 while forge restarts) is what the pages watch for.
127124 #[route(GET "/-/alive")]
128125 async fn alive(cx: &Cx) -> Result<Response> {
129- events_response(cx, stream::pending::<Result<Event>>())
126+ crate::pages::settings_live::alive_response(cx).await
130127 }
131128
132129 // Bundled fonts (style/fonts/). The version is in each file name, so the immutable cache is
crates/forge-web/src/pages/ci_tests.rsmodified+3 -14
@@ -340,10 +340,7 @@ async fn pages_are_live_while_not_finished_and_never_meta_refresh() {
340340 finish_job(&fx).await;
341341 let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await;
342342 assert!(
343- !done
344- .text()
345- .replace(r#"data-live="/settings/theme/events""#, "")
346- .contains("data-live="),
343+ !done.text().contains("data-live="),
347344 "job not live when finished"
348345 );
349346 assert!(
@@ -507,13 +504,7 @@ async fn run_list_is_live_on_page_one_only() {
507504 Some(&cookie_for("tahinli-token")),
508505 )
509506 .await;
510- assert!(
511- !second
512- .text()
513- .replace(r#"data-live="/settings/theme/events""#, "")
514- .contains("data-live="),
515- "page 2 is not live"
516- );
507+ assert!(!second.text().contains("data-live="), "page 2 is not live");
517508 let run = get(
518509 &fx.app,
519510 &format!("{RUN_BASE}/runs/30?page=2"),
@@ -521,9 +512,7 @@ async fn run_list_is_live_on_page_one_only() {
521512 )
522513 .await;
523514 assert!(
524- !run.text()
525- .replace(r#"data-live="/settings/theme/events""#, "")
526- .contains("data-live="),
515+ !run.text().contains("data-live="),
527516 "a run on page 2 is not live"
528517 );
529518 }
crates/forge-web/src/pages/settings_live.rsmodified+111 -47
@@ -7,21 +7,29 @@
77 //! - A POST under `/settings/` (a profile, key, token, passkey, session, notification, appearance
88 //! or security change): [`AccountWriteLayer`] bumps the viewer's topic after the handler ran, so
99 //! no route calls a bump itself. A refused write bumps too: the page re-reads and agrees.
10-//! - Anything outside those paths that changes what the pages show: a sign-in (`auth::login`), and
11-//! a key or token used by git, the API, SSH or a package client. Those call [`bump_account`].
10+//! - Anything outside those paths that changes what the pages show: a sign-in (`auth::login`), a
11+//! key or token used by git, the API, SSH or a package client, and an admin action that ends
12+//! sessions. Those call [`bump_account`].
1213 //!
13-//! The stream sends `changed` on each wake and carries no data: the page re-reads itself. A session
14-//! revoked elsewhere is caught the same way. The re-read finds no session, so the page leaves for
15-//! the login page.
14+//! The settings stream sends `changed` on each wake and carries no data: the page re-reads itself.
15+//! A session revoked elsewhere is caught the same way. The re-read finds no session, so the page
16+//! leaves for the login page.
17+//!
18+//! Every page also holds `/-/alive` (see [`alive_response`]). For a signed-in viewer that stream
19+//! sends a `theme` event with the appearance attributes when they change, so a tab applies a theme,
20+//! accent or sidebar change made elsewhere without a reload.
1621
22+use futures_util::stream;
1723 use topcoat::Result;
1824 use topcoat::context::{Cx, app_context};
25+use topcoat::router::content::sse::Event;
1926 use topcoat::router::request::{method, uri};
2027 use topcoat::router::response::Response;
2128 use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode, route};
2229
2330 use crate::auth::current_user;
24-use crate::live::{LiveHub, Topic, stream_changes, stream_wakes};
31+use crate::live::{LiveHub, Topic, stream_wakes};
32+use crate::pages::ci_runs::events_response;
2533 use crate::state::AppState;
2634
2735 /// Wakes the settings pages of `user_id`. Called after a write that changes what they show.
@@ -42,44 +50,70 @@ async fn settings_events(cx: &Cx) -> Result<Response> {
4250 stream_wakes(cx, hub, &[Topic::Account(user.id)])
4351 }
4452
45-/// The appearance stream of a signed-in user's tabs. The shell of every signed-in page follows it,
46-/// so a theme, accent, base, language or sidebar change made in one tab reaches the others. It
47-/// sends `changed` only when the appearance differs from what the page shows.
48-#[route(GET "/settings/theme/events")]
49-async fn theme_events(cx: &Cx) -> Result<Response> {
50- let Some((user, _)) = current_user(cx).await? else {
51- let mut res = Response::new(Body::empty());
52- *res.status_mut() = StatusCode::UNAUTHORIZED;
53- return Ok(res);
54- };
55- let state = app_context::<AppState>(cx).clone();
56- let topics = [Topic::Account(user.id.clone())];
57- let user_id = user.id;
58- stream_changes(cx, &state.live.clone(), &topics, move || {
59- let state = state.clone();
60- let user_id = user_id.clone();
61- async move { appearance_fingerprint(&state, &user_id).await }
62- })
63- .await
64-}
65-
66-/// The appearance fields of a user, as one line. Compared, never sent.
67-async fn appearance_fingerprint(state: &AppState, user_id: &str) -> Result<String> {
53+/// The appearance of a user's `<html>` as `name=value` pairs joined by `;`. An empty value means
54+/// the attribute is removed (the automatic theme). It mirrors the attributes `views::shell` sets, so
55+/// a tab that applies it shows what a fresh load of the page would show.
56+pub async fn appearance_fingerprint(state: &AppState, user_id: &str) -> Result<String> {
6857 let Some(user) = state.store.user_by_id(user_id).await? else {
6958 return Ok(String::new());
7059 };
60+ let theme = match crate::theme::resolve_preference(&user.theme) {
61+ "auto" => "",
62+ theme => theme,
63+ };
64+ let sidebar = if user.sidebar_side == "right" {
65+ "right"
66+ } else {
67+ "left"
68+ };
7169 Ok(format!(
72- "{}|{}|{}|{}|{}|{}|{}",
73- user.theme,
74- user.language,
75- user.accent,
76- user.accent_dark,
77- user.base_light,
78- user.base_dark,
79- user.sidebar_side
70+ "data-theme={theme};data-accent-light={};data-accent-dark={};data-base-light={};data-base-dark={};data-sidebar={sidebar}",
71+ crate::accent::resolve(&user.accent).id,
72+ crate::accent::resolve(&user.accent_dark).id,
73+ crate::accent::resolve_base(&user.base_light).id,
74+ crate::accent::resolve_base(&user.base_dark).id,
8075 ))
8176 }
8277
78+/// The response of `GET /-/alive`, the stream every page holds. Anonymous: it only stays open, as
79+/// before. A signed-in viewer also follows their account topic, and each time the appearance differs
80+/// from the last one sent it gets a `theme` event carrying the new attributes (see `nav.js`). The
81+/// stream still opens with `retry`, and its open still means the server is back.
82+pub async fn alive_response(cx: &Cx) -> Result<Response> {
83+ let Some((user, _)) = current_user(cx).await? else {
84+ return events_response(cx, stream::pending::<Result<Event>>());
85+ };
86+ let state = app_context::<AppState>(cx).clone();
87+ let user_id = user.id;
88+ // Subscribed before the baseline is read, so a change in between is not lost.
89+ let wake = state.live.subscribe(&Topic::Account(user_id.clone()));
90+ let last = appearance_fingerprint(&state, &user_id).await?;
91+ let events = stream::unfold(
92+ (wake, last, state, user_id),
93+ |(mut wake, mut last, state, user_id)| async move {
94+ loop {
95+ if wake.changed().await.is_err() {
96+ return None;
97+ }
98+ let now = match appearance_fingerprint(&state, &user_id).await {
99+ Ok(now) => now,
100+ Err(e) => {
101+ tracing::error!(error = %e, "live: could not read the appearance");
102+ return None;
103+ }
104+ };
105+ if now == last {
106+ continue;
107+ }
108+ last = now.clone();
109+ let event = Event::new().event("theme").data(now);
110+ return Some((Ok(event), (wake, last, state, user_id)));
111+ }
112+ },
113+ );
114+ events_response(cx, events)
115+}
116+
83117 /// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router
84118 /// in `boot.rs` and the test router. It sits on a path, so it runs inside the cookie layer (a
85119 /// pathless layer would run outside it, where the session cannot be read).
@@ -138,7 +172,7 @@ mod tests {
138172 }
139173
140174 #[tokio::test]
141- async fn the_theme_stream_needs_a_session_and_the_settings_name_their_streams() {
175+ async fn the_settings_sidebar_names_the_settings_stream() {
142176 let dir = tempfile::tempdir().expect("tempdir");
143177 let state = test_state(dir.path()).await;
144178 let store = state.store.clone();
@@ -149,13 +183,6 @@ mod tests {
149183 create_session(&store, &owner.id, "owner-token", CSRF).await;
150184 let router = app_router(state);
151185
152- let anon = Request::builder()
153- .method("GET")
154- .uri("/settings/theme/events")
155- .body(Body::empty())
156- .expect("request");
157- assert_eq!(router.handle(anon).await.status().as_u16(), 401);
158-
159186 let page = Request::builder()
160187 .method("GET")
161188 .uri("/settings/profile")
@@ -166,8 +193,8 @@ mod tests {
166193 let html =
167194 String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.expect("body"))
168195 .into_owned();
169- assert!(html.contains("<body") && html.contains("data-live=\"/settings/theme/events\""));
170196 assert!(html.contains("data-live=\"/settings/events\""));
197+ assert!(!html.contains("/settings/theme/events"));
171198 }
172199
173200 #[tokio::test]
@@ -205,7 +232,7 @@ mod tests {
205232 }
206233
207234 #[tokio::test]
208- async fn the_stream_sends_a_changed_event_per_write() {
235+ async fn the_settings_stream_sends_a_changed_event_per_write() {
209236 let dir = tempfile::tempdir().expect("tempdir");
210237 let state = test_state(dir.path()).await;
211238 let store = state.store.clone();
@@ -233,4 +260,41 @@ mod tests {
233260 let changed = frames.next().await.expect("a frame").expect("data");
234261 assert_eq!(&changed[..], b"event: changed\ndata: 1\n\n");
235262 }
263+
264+ #[tokio::test]
265+ async fn the_alive_stream_sends_the_appearance_only_when_it_changes() {
266+ let dir = tempfile::tempdir().expect("tempdir");
267+ let state = test_state(dir.path()).await;
268+ let store = state.store.clone();
269+ let live = state.live.clone();
270+ let owner = store
271+ .create_user("tahinli", None, "h", false)
272+ .await
273+ .expect("user");
274+ create_session(&store, &owner.id, "owner-token", CSRF).await;
275+ let router = app_router(state);
276+
277+ let request = Request::builder()
278+ .method("GET")
279+ .uri("/-/alive")
280+ .header("cookie", format!("__Host-{SESSION_COOKIE}=owner-token"))
281+ .body(Body::empty())
282+ .expect("request");
283+ let res = router.handle(request).await;
284+ let mut frames = res.into_body().into_data_stream();
285+ let retry = frames.next().await.expect("a frame").expect("data");
286+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
287+
288+ // A bump that changes no appearance sends nothing; the next change is the theme event.
289+ live.bump(&Topic::Account(owner.id.clone()));
290+ store
291+ .set_ui_prefs(&owner.id, "dark", "en")
292+ .await
293+ .expect("prefs");
294+ live.bump(&Topic::Account(owner.id.clone()));
295+ let event = frames.next().await.expect("a frame").expect("data");
296+ let text = String::from_utf8_lossy(&event).into_owned();
297+ assert!(text.starts_with("event: theme\n"), "{text}");
298+ assert!(text.contains("data-theme=dark;"), "{text}");
299+ }
236300 }
crates/forge-web/src/pages/settings_security.rsmodified+1 -0
@@ -946,6 +946,7 @@ async fn account_delete(cx: &Cx, Form(form): Form<DeleteAccountForm>) -> Result<
946946 let ghost = state.store.ensure_ghost_user().await?;
947947 match state.store.delete_user(&user_id, &ghost.id).await {
948948 Ok(_) => {
949+ crate::pages::settings_live::bump_account(state, &user_id);
949950 // The account row is gone, so the entry names no actor; the username is kept.
950951 audit::record(
951952 &state.store,
crates/forge-web/src/views/mod.rsmodified+1 -3
@@ -165,8 +165,6 @@ pub async fn shell(
165165 let back = uri(__cx).path_and_query().map(|p| p.as_str().to_owned());
166166 let lang = i18n::lang(__cx, viewer.map(|(user, _)| user));
167167 let banner = crate::pages::banner::current(__cx);
168- // A signed-in tab follows its appearance, so a change in another tab applies here too.
169- let theme_live = signed_in.then_some("/settings/theme/events");
170168 let banner_back = back.clone().unwrap_or_else(|| "/".to_owned());
171169 let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss);
172170 // The admin area and the user settings swap the global links for their own list. Signed-in only.
@@ -269,7 +267,7 @@ pub async fn shell(
269267 }
270268 <script src=(NAV_SCRIPT_HREF) defer="defer"></script>
271269 </head>
272- <body data-link-restarting=(lk::t(lang, LinkKey::Restarting)) data-link-back=(lk::t(lang, LinkKey::BackSubmit)) data-live=(theme_live)>
270+ <body data-link-restarting=(lk::t(lang, LinkKey::Restarting)) data-link-back=(lk::t(lang, LinkKey::BackSubmit))>
273271 <header class="topbar">
274272 if signed_in {
275273 <details class="nav-toggle">
docs/architecture.mdmodified+2 -1
@@ -272,7 +272,8 @@ Pages update without a reload. A write that changes what a page shows calls `Liv
272272 | Admin replication `/admin/replication` | `/admin/replication/events` | each copy's status and the database snapshot |
273273 | Admin health `/admin/health` | `/admin/health/events` | the alerts, the counts and the mail queue. The disk and tree probes are read when the page renders, not on each change |
274274 | Admin server `/admin/server` | `/admin/server/events` | saved or reset settings. A page waiting for a restart gets one event when a new process answers |
275-| Settings `/settings/...` (profile, keys, GPG, tokens, sessions, security, passkeys, notifications, appearance, export) | `/settings/events` (the section sidebar), `/settings/theme/events` (every signed-in page) | the viewer's own account topic: a setting, key, token, passkey or session changed, or a sign-in or key use happened. The theme stream sends only when the appearance (theme, accents, base, language, sidebar side) differs. A revoked current session leaves for the login page on the next re-read |
275+| Settings `/settings/...` (profile, keys, GPG, tokens, sessions, security, passkeys, notifications, appearance, export) | `/settings/events` (the section sidebar) | the viewer's own account topic: a setting, key, token, passkey or session changed, a sign-in or key use happened, or a suspension or account deletion. A revoked current session leaves for the login page on the next re-read |
276+| Every signed-in page (`/-/alive`, the stream every page holds) | the viewer's account topic. A `theme` event carries the appearance attributes (theme, accents, base, sidebar side) when they change, and `nav.js` applies them with no reload. The stream is one connection, shared with the restart check |
276277
277278 The org streams follow the same access as their pages: a non-member gets 404, and a member who is not an owner gets 403 on the settings stream. A team page names only the linked repos the viewer may read. Each org write (a POST under `/org/{org}/members`, `teams` or `settings`) wakes the org's streams. The org notices (for example "Member added.") are carried in the redirect's `?notice=` query, not a cookie, so a live refresh of the page shows the same notice again.
278279