From 00ca6f770b05ec77ac7e6e41c00b284bafe97005 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 22 Oct 2026 08:21:07 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20feat:=20a=20theme,=20accent=20or=20?= =?UTF-8?q?sidebar=20change=20reaches=20every=20open=20tab,=20and=20a=20re?= =?UTF-8?q?voked=20session=20leaves=20live?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-web/assets/nav.js | 21 ++- crates/forge-web/src/auth.rs | 8 +- crates/forge-web/src/pages/admin_mail.rs | 4 - crates/forge-web/src/pages/admin_server.rs | 1 - .../forge-web/src/pages/admin_user_detail.rs | 5 + crates/forge-web/src/pages/admin_users.rs | 2 + crates/forge-web/src/pages/assets.rs | 7 +- crates/forge-web/src/pages/ci_tests.rs | 17 +- crates/forge-web/src/pages/settings_live.rs | 158 ++++++++++++------ .../forge-web/src/pages/settings_security.rs | 1 + crates/forge-web/src/views/mod.rs | 4 +- docs/architecture.md | 3 +- 12 files changed, 149 insertions(+), 82 deletions(-) diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 4172d83..20397bb 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -381,7 +381,10 @@ } var dest = new URL(res.url.href); dest.hash = o.dest.hash; - swap(res.html, dest, o.how, !!o.keep && res.url.pathname === o.target.pathname); + // A live refresh that lands on another path (a revoked session sent to the login page) is a + // navigation: it gets a history entry, so the address bar shows where the page now is. + var how = o.how === 'live' && res.url.pathname !== o.target.pathname ? 'nav' : o.how; + swap(res.html, dest, how, !!o.keep && res.url.pathname === o.target.pathname); }).catch(function () { if (mark !== latest || o.how === 'live') { return; } if (o.post) { o.form.submit(); } else { location.assign(o.dest.href); } @@ -461,11 +464,12 @@ // One EventSource that stays open. The browser reconnects by itself, except when a proxy answers // with an error: EventSource then closes for good, so it is opened again here after 1, 2, then 3 s. // `restart()` reconnects at once. - function keepOpen(url, onOpen, onError) { + function keepOpen(url, onOpen, onError, onTheme) { var es = null, delay = 1000, timer = null; function connect() { timer = null; es = new EventSource(url); + if (onTheme) { es.addEventListener('theme', function (e) { onTheme(e.data); }); } es.onopen = function () { delay = 1000; onOpen(); }; es.onerror = function () { onError(); @@ -488,7 +492,18 @@ // Every page holds one stream to /-/alive (no data, no login). Its error means the server, or the // proxy in front of it, is down; its open means it is back. - if (window.EventSource) { alive = keepOpen('/-/alive', linkBack, linkDown); } + // A `theme` event carries the signed-in user's appearance as `name=value` pairs joined by `;` + // (the `` attributes). An empty value removes the attribute. Only data-* names are applied. + function applyAppearance(data) { + String(data).split(';').forEach(function (pair) { + var i = pair.indexOf('='); + if (i < 0) { return; } + var name = pair.slice(0, i), value = pair.slice(i + 1); + if (name.indexOf('data-') !== 0) { return; } + if (value) { root.setAttribute(name, value); } else { root.removeAttribute(name); } + }); + } + if (window.EventSource) { alive = keepOpen('/-/alive', linkBack, linkDown, applyAppearance); } if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(function () {}); } // The form to send a queued change on: the form itself, or after a swap the one with the same action. diff --git a/crates/forge-web/src/auth.rs b/crates/forge-web/src/auth.rs index 6bcf2a7..48fcd1d 100644 --- a/crates/forge-web/src/auth.rs +++ b/crates/forge-web/src/auth.rs @@ -102,10 +102,10 @@ pub async fn login(cx: &Cx, user: &User) -> forge_core::Result { /// Deletes the session row and clears the cookie. pub async fn logout(cx: &Cx, session: &Session) -> forge_core::Result<()> { - app_context::(cx) - .store - .delete_session(&session.id) - .await?; + let state = app_context::(cx); + state.store.delete_session(&session.id).await?; + // The user's other tabs may show this session (a page that now leaves for the login page). + crate::pages::settings_live::bump_account(state, &session.user_id); session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); Ok(()) } diff --git a/crates/forge-web/src/pages/admin_mail.rs b/crates/forge-web/src/pages/admin_mail.rs index e353987..86fdc02 100644 --- a/crates/forge-web/src/pages/admin_mail.rs +++ b/crates/forge-web/src/pages/admin_mail.rs @@ -948,10 +948,6 @@ mod tests { settings.contains(r#"data-live="/admin/mail/events""#), "the settings tab is live too" ); - assert!( - settings.contains(r#"data-live="/settings/theme/events""#), - "the theme follows into the admin pages" - ); assert!( !settings.contains("Reset your password"), "the queue is on its own tab" diff --git a/crates/forge-web/src/pages/admin_server.rs b/crates/forge-web/src/pages/admin_server.rs index b871825..83d6be8 100644 --- a/crates/forge-web/src/pages/admin_server.rs +++ b/crates/forge-web/src/pages/admin_server.rs @@ -886,7 +886,6 @@ mod tests { let page = admin_get(&fx, "/admin/server?restarting=an-older-boot").await; assert!(!page.contains("Restarting...")); assert!(page.contains(r#"data-live="/admin/server/events""#)); - assert!(page.contains(r#"data-live="/settings/theme/events""#)); assert!(page.contains("The server restarted")); } diff --git a/crates/forge-web/src/pages/admin_user_detail.rs b/crates/forge-web/src/pages/admin_user_detail.rs index 3b627a3..49d1f35 100644 --- a/crates/forge-web/src/pages/admin_user_detail.rs +++ b/crates/forge-web/src/pages/admin_user_detail.rs @@ -381,6 +381,11 @@ async fn perform(cx: &Cx, form: &ActionForm, action: Action) -> Result<(Outcome, .await { Ok(()) => { + // A suspension ends the user's sessions: their open tabs must see it. + crate::pages::settings_live::bump_account( + app_context::(cx), + &target.id, + ); audit( AuditAction::UserSuspended, serde_json::json!({ "reason": form.reason.trim() }), diff --git a/crates/forge-web/src/pages/admin_users.rs b/crates/forge-web/src/pages/admin_users.rs index a4294f3..8f411ea 100644 --- a/crates/forge-web/src/pages/admin_users.rs +++ b/crates/forge-web/src/pages/admin_users.rs @@ -410,6 +410,8 @@ async fn user_delete(cx: &Cx, Form(form): Form) -> Result let ghost = store.ensure_ghost_user().await?; match store.delete_user(&target.id, &ghost.id).await { Ok(_) => { + // Their sessions and keys are gone: any open tab of theirs must leave. + crate::pages::settings_live::bump_account(app_context::(cx), &target.id); audit::record( store, Some(cx), diff --git a/crates/forge-web/src/pages/assets.rs b/crates/forge-web/src/pages/assets.rs index d6d213f..a6f4dea 100644 --- a/crates/forge-web/src/pages/assets.rs +++ b/crates/forge-web/src/pages/assets.rs @@ -3,14 +3,11 @@ use std::sync::OnceLock; -use futures_util::stream; use topcoat::Result; use topcoat::context::Cx; -use topcoat::router::content::sse::Event; use topcoat::router::response::Response; use topcoat::router::{HeaderMap, StatusCode, header, route}; -use crate::pages::ci_runs::events_response; use crate::render::highlight::highlight_css; const CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); @@ -123,10 +120,10 @@ async fn offline_js() -> Result<(StatusCode, HeaderMap, &'static str)> { /// The stream every page and the offline page watch to learn that the server is back. It carries /// no data and needs no login: it sends `retry`, then holds the connection open with keep-alive -/// comments. A dropped connection (or a proxy's 502 while forge restarts) is what the pages watch for. +/// 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. #[route(GET "/-/alive")] async fn alive(cx: &Cx) -> Result { - events_response(cx, stream::pending::>()) + crate::pages::settings_live::alive_response(cx).await } // Bundled fonts (style/fonts/). The version is in each file name, so the immutable cache is diff --git a/crates/forge-web/src/pages/ci_tests.rs b/crates/forge-web/src/pages/ci_tests.rs index e0d1102..66f6d3a 100644 --- a/crates/forge-web/src/pages/ci_tests.rs +++ b/crates/forge-web/src/pages/ci_tests.rs @@ -340,10 +340,7 @@ async fn pages_are_live_while_not_finished_and_never_meta_refresh() { finish_job(&fx).await; let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; assert!( - !done - .text() - .replace(r#"data-live="/settings/theme/events""#, "") - .contains("data-live="), + !done.text().contains("data-live="), "job not live when finished" ); assert!( @@ -507,13 +504,7 @@ async fn run_list_is_live_on_page_one_only() { Some(&cookie_for("tahinli-token")), ) .await; - assert!( - !second - .text() - .replace(r#"data-live="/settings/theme/events""#, "") - .contains("data-live="), - "page 2 is not live" - ); + assert!(!second.text().contains("data-live="), "page 2 is not live"); let run = get( &fx.app, &format!("{RUN_BASE}/runs/30?page=2"), @@ -521,9 +512,7 @@ async fn run_list_is_live_on_page_one_only() { ) .await; assert!( - !run.text() - .replace(r#"data-live="/settings/theme/events""#, "") - .contains("data-live="), + !run.text().contains("data-live="), "a run on page 2 is not live" ); } diff --git a/crates/forge-web/src/pages/settings_live.rs b/crates/forge-web/src/pages/settings_live.rs index b8d862e..f95b9c4 100644 --- a/crates/forge-web/src/pages/settings_live.rs +++ b/crates/forge-web/src/pages/settings_live.rs @@ -7,21 +7,29 @@ //! - A POST under `/settings/` (a profile, key, token, passkey, session, notification, appearance //! or security change): [`AccountWriteLayer`] bumps the viewer's topic after the handler ran, so //! no route calls a bump itself. A refused write bumps too: the page re-reads and agrees. -//! - Anything outside those paths that changes what the pages show: a sign-in (`auth::login`), and -//! a key or token used by git, the API, SSH or a package client. Those call [`bump_account`]. +//! - Anything outside those paths that changes what the pages show: a sign-in (`auth::login`), a +//! key or token used by git, the API, SSH or a package client, and an admin action that ends +//! sessions. Those call [`bump_account`]. //! -//! The stream sends `changed` on each wake and carries no data: the page re-reads itself. A session -//! revoked elsewhere is caught the same way. The re-read finds no session, so the page leaves for -//! the login page. +//! The settings stream sends `changed` on each wake and carries no data: the page re-reads itself. +//! A session revoked elsewhere is caught the same way. The re-read finds no session, so the page +//! leaves for the login page. +//! +//! Every page also holds `/-/alive` (see [`alive_response`]). For a signed-in viewer that stream +//! sends a `theme` event with the appearance attributes when they change, so a tab applies a theme, +//! accent or sidebar change made elsewhere without a reload. +use futures_util::stream; use topcoat::Result; use topcoat::context::{Cx, app_context}; +use topcoat::router::content::sse::Event; use topcoat::router::request::{method, uri}; use topcoat::router::response::Response; use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode, route}; use crate::auth::current_user; -use crate::live::{LiveHub, Topic, stream_changes, stream_wakes}; +use crate::live::{LiveHub, Topic, stream_wakes}; +use crate::pages::ci_runs::events_response; use crate::state::AppState; /// 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 { stream_wakes(cx, hub, &[Topic::Account(user.id)]) } -/// The appearance stream of a signed-in user's tabs. The shell of every signed-in page follows it, -/// so a theme, accent, base, language or sidebar change made in one tab reaches the others. It -/// sends `changed` only when the appearance differs from what the page shows. -#[route(GET "/settings/theme/events")] -async fn theme_events(cx: &Cx) -> Result { - let Some((user, _)) = current_user(cx).await? else { - let mut res = Response::new(Body::empty()); - *res.status_mut() = StatusCode::UNAUTHORIZED; - return Ok(res); - }; - let state = app_context::(cx).clone(); - let topics = [Topic::Account(user.id.clone())]; - let user_id = user.id; - stream_changes(cx, &state.live.clone(), &topics, move || { - let state = state.clone(); - let user_id = user_id.clone(); - async move { appearance_fingerprint(&state, &user_id).await } - }) - .await -} - -/// The appearance fields of a user, as one line. Compared, never sent. -async fn appearance_fingerprint(state: &AppState, user_id: &str) -> Result { +/// The appearance of a user's `` as `name=value` pairs joined by `;`. An empty value means +/// the attribute is removed (the automatic theme). It mirrors the attributes `views::shell` sets, so +/// a tab that applies it shows what a fresh load of the page would show. +pub async fn appearance_fingerprint(state: &AppState, user_id: &str) -> Result { let Some(user) = state.store.user_by_id(user_id).await? else { return Ok(String::new()); }; + let theme = match crate::theme::resolve_preference(&user.theme) { + "auto" => "", + theme => theme, + }; + let sidebar = if user.sidebar_side == "right" { + "right" + } else { + "left" + }; Ok(format!( - "{}|{}|{}|{}|{}|{}|{}", - user.theme, - user.language, - user.accent, - user.accent_dark, - user.base_light, - user.base_dark, - user.sidebar_side + "data-theme={theme};data-accent-light={};data-accent-dark={};data-base-light={};data-base-dark={};data-sidebar={sidebar}", + crate::accent::resolve(&user.accent).id, + crate::accent::resolve(&user.accent_dark).id, + crate::accent::resolve_base(&user.base_light).id, + crate::accent::resolve_base(&user.base_dark).id, )) } +/// The response of `GET /-/alive`, the stream every page holds. Anonymous: it only stays open, as +/// before. A signed-in viewer also follows their account topic, and each time the appearance differs +/// from the last one sent it gets a `theme` event carrying the new attributes (see `nav.js`). The +/// stream still opens with `retry`, and its open still means the server is back. +pub async fn alive_response(cx: &Cx) -> Result { + let Some((user, _)) = current_user(cx).await? else { + return events_response(cx, stream::pending::>()); + }; + let state = app_context::(cx).clone(); + let user_id = user.id; + // Subscribed before the baseline is read, so a change in between is not lost. + let wake = state.live.subscribe(&Topic::Account(user_id.clone())); + let last = appearance_fingerprint(&state, &user_id).await?; + let events = stream::unfold( + (wake, last, state, user_id), + |(mut wake, mut last, state, user_id)| async move { + loop { + if wake.changed().await.is_err() { + return None; + } + let now = match appearance_fingerprint(&state, &user_id).await { + Ok(now) => now, + Err(e) => { + tracing::error!(error = %e, "live: could not read the appearance"); + return None; + } + }; + if now == last { + continue; + } + last = now.clone(); + let event = Event::new().event("theme").data(now); + return Some((Ok(event), (wake, last, state, user_id))); + } + }, + ); + events_response(cx, events) +} + /// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router /// in `boot.rs` and the test router. It sits on a path, so it runs inside the cookie layer (a /// pathless layer would run outside it, where the session cannot be read). @@ -138,7 +172,7 @@ mod tests { } #[tokio::test] - async fn the_theme_stream_needs_a_session_and_the_settings_name_their_streams() { + async fn the_settings_sidebar_names_the_settings_stream() { let dir = tempfile::tempdir().expect("tempdir"); let state = test_state(dir.path()).await; let store = state.store.clone(); @@ -149,13 +183,6 @@ mod tests { create_session(&store, &owner.id, "owner-token", CSRF).await; let router = app_router(state); - let anon = Request::builder() - .method("GET") - .uri("/settings/theme/events") - .body(Body::empty()) - .expect("request"); - assert_eq!(router.handle(anon).await.status().as_u16(), 401); - let page = Request::builder() .method("GET") .uri("/settings/profile") @@ -166,8 +193,8 @@ mod tests { let html = String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.expect("body")) .into_owned(); - assert!(html.contains(") -> Result< let ghost = state.store.ensure_ghost_user().await?; match state.store.delete_user(&user_id, &ghost.id).await { Ok(_) => { + crate::pages::settings_live::bump_account(state, &user_id); // The account row is gone, so the entry names no actor; the username is kept. audit::record( &state.store, diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index 04800e0..f34f1a8 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -165,8 +165,6 @@ pub async fn shell( let back = uri(__cx).path_and_query().map(|p| p.as_str().to_owned()); let lang = i18n::lang(__cx, viewer.map(|(user, _)| user)); let banner = crate::pages::banner::current(__cx); - // A signed-in tab follows its appearance, so a change in another tab applies here too. - let theme_live = signed_in.then_some("/settings/theme/events"); let banner_back = back.clone().unwrap_or_else(|| "/".to_owned()); let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss); // 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( } - +
if signed_in {