A theme, accent or sidebar change reaches every open tab, and a revoked session leaves live
Browse files at this commit00ca6f770b05ec77ac7e6e41c00b284bafe97005Parent: d7d6a17- feat
- a theme, accent or sidebar change reaches every open tab, and a revoked session leaves live
12 changed files +149 -82
- crates/forge-web/assets/nav.js +18 -3
- crates/forge-web/src/auth.rs +4 -4
- crates/forge-web/src/pages/admin_mail.rs +0 -4
- crates/forge-web/src/pages/admin_server.rs +0 -1
- crates/forge-web/src/pages/admin_user_detail.rs +5 -0
- crates/forge-web/src/pages/admin_users.rs +2 -0
- crates/forge-web/src/pages/assets.rs +2 -5
- crates/forge-web/src/pages/ci_tests.rs +3 -14
- crates/forge-web/src/pages/settings_live.rs +111 -47
- crates/forge-web/src/pages/settings_security.rs +1 -0
- crates/forge-web/src/views/mod.rs +1 -3
- docs/architecture.md +2 -1
crates/forge-web/assets/nav.jsmodified+18 -3
| @@ -381,7 +381,10 @@ | |||
| 381 | } | 381 | } |
| 382 | var dest = new URL(res.url.href); | 382 | var dest = new URL(res.url.href); |
| 383 | dest.hash = o.dest.hash; | 383 | 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); | ||
| 385 | }).catch(function () { | 388 | }).catch(function () { |
| 386 | if (mark !== latest || o.how === 'live') { return; } | 389 | if (mark !== latest || o.how === 'live') { return; } |
| 387 | if (o.post) { o.form.submit(); } else { location.assign(o.dest.href); } | 390 | if (o.post) { o.form.submit(); } else { location.assign(o.dest.href); } |
| @@ -461,11 +464,12 @@ | |||
| 461 | // One EventSource that stays open. The browser reconnects by itself, except when a proxy answers | 464 | // One EventSource that stays open. The browser reconnects by itself, except when a proxy answers |
| 462 | // with an error: EventSource then closes for good, so it is opened again here after 1, 2, then 3 s. | 465 | // with an error: EventSource then closes for good, so it is opened again here after 1, 2, then 3 s. |
| 463 | // `restart()` reconnects at once. | 466 | // `restart()` reconnects at once. |
| 464 | - function keepOpen(url, onOpen, onError) { | 467 | + function keepOpen(url, onOpen, onError, onTheme) { |
| 465 | var es = null, delay = 1000, timer = null; | 468 | var es = null, delay = 1000, timer = null; |
| 466 | function connect() { | 469 | function connect() { |
| 467 | timer = null; | 470 | timer = null; |
| 468 | es = new EventSource(url); | 471 | es = new EventSource(url); |
| 472 | + if (onTheme) { es.addEventListener('theme', function (e) { onTheme(e.data); }); } | ||
| 469 | es.onopen = function () { delay = 1000; onOpen(); }; | 473 | es.onopen = function () { delay = 1000; onOpen(); }; |
| 470 | es.onerror = function () { | 474 | es.onerror = function () { |
| 471 | onError(); | 475 | onError(); |
| @@ -488,7 +492,18 @@ | |||
| 488 | 492 | ||
| 489 | // Every page holds one stream to /-/alive (no data, no login). Its error means the server, or the | 493 | // Every page holds one stream to /-/alive (no data, no login). Its error means the server, or the |
| 490 | // proxy in front of it, is down; its open means it is back. | 494 | // 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); } | ||
| 492 | if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(function () {}); } | 507 | if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(function () {}); } |
| 493 | 508 | ||
| 494 | // The form to send a queued change on: the form itself, or after a swap the one with the same action. | 509 | // 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> { | |||
| 102 | 102 | ||
| 103 | /// Deletes the session row and clears the cookie. | 103 | /// Deletes the session row and clears the cookie. |
| 104 | pub async fn logout(cx: &Cx, session: &Session) -> forge_core::Result<()> { | 104 | pub async fn logout(cx: &Cx, session: &Session) -> forge_core::Result<()> { |
| 105 | - app_context::<AppState>(cx) | 105 | + let state = app_context::<AppState>(cx); |
| 106 | - .store | 106 | + state.store.delete_session(&session.id).await?; |
| 107 | - .delete_session(&session.id) | 107 | + // The user's other tabs may show this session (a page that now leaves for the login page). |
| 108 | - .await?; | 108 | + crate::pages::settings_live::bump_account(state, &session.user_id); |
| 109 | session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); | 109 | session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); |
| 110 | Ok(()) | 110 | Ok(()) |
| 111 | } | 111 | } |
crates/forge-web/src/pages/admin_mail.rsmodified+0 -4
| @@ -948,10 +948,6 @@ mod tests { | |||
| 948 | settings.contains(r#"data-live="/admin/mail/events""#), | 948 | settings.contains(r#"data-live="/admin/mail/events""#), |
| 949 | "the settings tab is live too" | 949 | "the settings tab is live too" |
| 950 | ); | 950 | ); |
| 951 | - assert!( | ||
| 952 | - settings.contains(r#"data-live="/settings/theme/events""#), | ||
| 953 | - "the theme follows into the admin pages" | ||
| 954 | - ); | ||
| 955 | assert!( | 951 | assert!( |
| 956 | !settings.contains("Reset your password"), | 952 | !settings.contains("Reset your password"), |
| 957 | "the queue is on its own tab" | 953 | "the queue is on its own tab" |
crates/forge-web/src/pages/admin_server.rsmodified+0 -1
| @@ -886,7 +886,6 @@ mod tests { | |||
| 886 | let page = admin_get(&fx, "/admin/server?restarting=an-older-boot").await; | 886 | let page = admin_get(&fx, "/admin/server?restarting=an-older-boot").await; |
| 887 | assert!(!page.contains("Restarting...")); | 887 | assert!(!page.contains("Restarting...")); |
| 888 | assert!(page.contains(r#"data-live="/admin/server/events""#)); | 888 | assert!(page.contains(r#"data-live="/admin/server/events""#)); |
| 889 | - assert!(page.contains(r#"data-live="/settings/theme/events""#)); | ||
| 890 | assert!(page.contains("The server restarted")); | 889 | assert!(page.contains("The server restarted")); |
| 891 | } | 890 | } |
| 892 | 891 | ||
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, | |||
| 381 | .await | 381 | .await |
| 382 | { | 382 | { |
| 383 | Ok(()) => { | 383 | 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 | + ); | ||
| 384 | audit( | 389 | audit( |
| 385 | AuditAction::UserSuspended, | 390 | AuditAction::UserSuspended, |
| 386 | serde_json::json!({ "reason": form.reason.trim() }), | 391 | 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> | |||
| 410 | let ghost = store.ensure_ghost_user().await?; | 410 | let ghost = store.ensure_ghost_user().await?; |
| 411 | match store.delete_user(&target.id, &ghost.id).await { | 411 | match store.delete_user(&target.id, &ghost.id).await { |
| 412 | Ok(_) => { | 412 | 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); | ||
| 413 | audit::record( | 415 | audit::record( |
| 414 | store, | 416 | store, |
| 415 | Some(cx), | 417 | Some(cx), |
crates/forge-web/src/pages/assets.rsmodified+2 -5
| @@ -3,14 +3,11 @@ | |||
| 3 | 3 | ||
| 4 | use std::sync::OnceLock; | 4 | use std::sync::OnceLock; |
| 5 | 5 | ||
| 6 | -use futures_util::stream; | ||
| 7 | use topcoat::Result; | 6 | use topcoat::Result; |
| 8 | use topcoat::context::Cx; | 7 | use topcoat::context::Cx; |
| 9 | -use topcoat::router::content::sse::Event; | ||
| 10 | use topcoat::router::response::Response; | 8 | use topcoat::router::response::Response; |
| 11 | use topcoat::router::{HeaderMap, StatusCode, header, route}; | 9 | use topcoat::router::{HeaderMap, StatusCode, header, route}; |
| 12 | 10 | ||
| 13 | -use crate::pages::ci_runs::events_response; | ||
| 14 | use crate::render::highlight::highlight_css; | 11 | use crate::render::highlight::highlight_css; |
| 15 | 12 | ||
| 16 | const CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); | 13 | const CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); |
| @@ -123,10 +120,10 @@ async fn offline_js() -> Result<(StatusCode, HeaderMap, &'static str)> { | |||
| 123 | 120 | ||
| 124 | /// The stream every page and the offline page watch to learn that the server is back. It carries | 121 | /// The stream every page and the offline page watch to learn that the server is back. It carries |
| 125 | /// no data and needs no login: it sends `retry`, then holds the connection open with keep-alive | 122 | /// 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. |
| 127 | #[route(GET "/-/alive")] | 124 | #[route(GET "/-/alive")] |
| 128 | async fn alive(cx: &Cx) -> Result<Response> { | 125 | async fn alive(cx: &Cx) -> Result<Response> { |
| 129 | - events_response(cx, stream::pending::<Result<Event>>()) | 126 | + crate::pages::settings_live::alive_response(cx).await |
| 130 | } | 127 | } |
| 131 | 128 | ||
| 132 | // Bundled fonts (style/fonts/). The version is in each file name, so the immutable cache is | 129 | // 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() { | |||
| 340 | finish_job(&fx).await; | 340 | finish_job(&fx).await; |
| 341 | let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; | 341 | let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; |
| 342 | assert!( | 342 | assert!( |
| 343 | - !done | 343 | + !done.text().contains("data-live="), |
| 344 | - .text() | ||
| 345 | - .replace(r#"data-live="/settings/theme/events""#, "") | ||
| 346 | - .contains("data-live="), | ||
| 347 | "job not live when finished" | 344 | "job not live when finished" |
| 348 | ); | 345 | ); |
| 349 | assert!( | 346 | assert!( |
| @@ -507,13 +504,7 @@ async fn run_list_is_live_on_page_one_only() { | |||
| 507 | Some(&cookie_for("tahinli-token")), | 504 | Some(&cookie_for("tahinli-token")), |
| 508 | ) | 505 | ) |
| 509 | .await; | 506 | .await; |
| 510 | - assert!( | 507 | + assert!(!second.text().contains("data-live="), "page 2 is not live"); |
| 511 | - !second | ||
| 512 | - .text() | ||
| 513 | - .replace(r#"data-live="/settings/theme/events""#, "") | ||
| 514 | - .contains("data-live="), | ||
| 515 | - "page 2 is not live" | ||
| 516 | - ); | ||
| 517 | let run = get( | 508 | let run = get( |
| 518 | &fx.app, | 509 | &fx.app, |
| 519 | &format!("{RUN_BASE}/runs/30?page=2"), | 510 | &format!("{RUN_BASE}/runs/30?page=2"), |
| @@ -521,9 +512,7 @@ async fn run_list_is_live_on_page_one_only() { | |||
| 521 | ) | 512 | ) |
| 522 | .await; | 513 | .await; |
| 523 | assert!( | 514 | assert!( |
| 524 | - !run.text() | 515 | + !run.text().contains("data-live="), |
| 525 | - .replace(r#"data-live="/settings/theme/events""#, "") | ||
| 526 | - .contains("data-live="), | ||
| 527 | "a run on page 2 is not live" | 516 | "a run on page 2 is not live" |
| 528 | ); | 517 | ); |
| 529 | } | 518 | } |
crates/forge-web/src/pages/settings_live.rsmodified+111 -47
| @@ -7,21 +7,29 @@ | |||
| 7 | //! - A POST under `/settings/` (a profile, key, token, passkey, session, notification, appearance | 7 | //! - A POST under `/settings/` (a profile, key, token, passkey, session, notification, appearance |
| 8 | //! or security change): [`AccountWriteLayer`] bumps the viewer's topic after the handler ran, so | 8 | //! or security change): [`AccountWriteLayer`] bumps the viewer's topic after the handler ran, so |
| 9 | //! no route calls a bump itself. A refused write bumps too: the page re-reads and agrees. | 9 | //! 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 | 10 | +//! - Anything outside those paths that changes what the pages show: a sign-in (`auth::login`), a |
| 11 | -//! a key or token used by git, the API, SSH or a package client. Those call [`bump_account`]. | 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`]. | ||
| 12 | //! | 13 | //! |
| 13 | -//! The stream sends `changed` on each wake and carries no data: the page re-reads itself. A session | 14 | +//! The settings stream sends `changed` on each wake and carries no data: the page re-reads itself. |
| 14 | -//! revoked elsewhere is caught the same way. The re-read finds no session, so the page leaves for | 15 | +//! A session revoked elsewhere is caught the same way. The re-read finds no session, so the page |
| 15 | -//! the login 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. | ||
| 16 | 21 | ||
| 22 | +use futures_util::stream; | ||
| 17 | use topcoat::Result; | 23 | use topcoat::Result; |
| 18 | use topcoat::context::{Cx, app_context}; | 24 | use topcoat::context::{Cx, app_context}; |
| 25 | +use topcoat::router::content::sse::Event; | ||
| 19 | use topcoat::router::request::{method, uri}; | 26 | use topcoat::router::request::{method, uri}; |
| 20 | use topcoat::router::response::Response; | 27 | use topcoat::router::response::Response; |
| 21 | use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode, route}; | 28 | use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode, route}; |
| 22 | 29 | ||
| 23 | use crate::auth::current_user; | 30 | 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; | ||
| 25 | use crate::state::AppState; | 33 | use crate::state::AppState; |
| 26 | 34 | ||
| 27 | /// Wakes the settings pages of `user_id`. Called after a write that changes what they show. | 35 | /// 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> { | |||
| 42 | stream_wakes(cx, hub, &[Topic::Account(user.id)]) | 50 | stream_wakes(cx, hub, &[Topic::Account(user.id)]) |
| 43 | } | 51 | } |
| 44 | 52 | ||
| 45 | -/// The appearance stream of a signed-in user's tabs. The shell of every signed-in page follows it, | 53 | +/// The appearance of a user's `<html>` as `name=value` pairs joined by `;`. An empty value means |
| 46 | -/// so a theme, accent, base, language or sidebar change made in one tab reaches the others. It | 54 | +/// the attribute is removed (the automatic theme). It mirrors the attributes `views::shell` sets, so |
| 47 | -/// sends `changed` only when the appearance differs from what the page shows. | 55 | +/// a tab that applies it shows what a fresh load of the page would show. |
| 48 | -#[route(GET "/settings/theme/events")] | 56 | +pub async fn appearance_fingerprint(state: &AppState, user_id: &str) -> Result<String> { |
| 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> { | ||
| 68 | let Some(user) = state.store.user_by_id(user_id).await? else { | 57 | let Some(user) = state.store.user_by_id(user_id).await? else { |
| 69 | return Ok(String::new()); | 58 | return Ok(String::new()); |
| 70 | }; | 59 | }; |
| 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 | + }; | ||
| 71 | Ok(format!( | 69 | Ok(format!( |
| 72 | - "{}|{}|{}|{}|{}|{}|{}", | 70 | + "data-theme={theme};data-accent-light={};data-accent-dark={};data-base-light={};data-base-dark={};data-sidebar={sidebar}", |
| 73 | - user.theme, | 71 | + crate::accent::resolve(&user.accent).id, |
| 74 | - user.language, | 72 | + crate::accent::resolve(&user.accent_dark).id, |
| 75 | - user.accent, | 73 | + crate::accent::resolve_base(&user.base_light).id, |
| 76 | - user.accent_dark, | 74 | + crate::accent::resolve_base(&user.base_dark).id, |
| 77 | - user.base_light, | ||
| 78 | - user.base_dark, | ||
| 79 | - user.sidebar_side | ||
| 80 | )) | 75 | )) |
| 81 | } | 76 | } |
| 82 | 77 | ||
| 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 | + | ||
| 83 | /// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router | 117 | /// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router |
| 84 | /// in `boot.rs` and the test router. It sits on a path, so it runs inside the cookie layer (a | 118 | /// in `boot.rs` and the test router. It sits on a path, so it runs inside the cookie layer (a |
| 85 | /// pathless layer would run outside it, where the session cannot be read). | 119 | /// pathless layer would run outside it, where the session cannot be read). |
| @@ -138,7 +172,7 @@ mod tests { | |||
| 138 | } | 172 | } |
| 139 | 173 | ||
| 140 | #[tokio::test] | 174 | #[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() { |
| 142 | let dir = tempfile::tempdir().expect("tempdir"); | 176 | let dir = tempfile::tempdir().expect("tempdir"); |
| 143 | let state = test_state(dir.path()).await; | 177 | let state = test_state(dir.path()).await; |
| 144 | let store = state.store.clone(); | 178 | let store = state.store.clone(); |
| @@ -149,13 +183,6 @@ mod tests { | |||
| 149 | create_session(&store, &owner.id, "owner-token", CSRF).await; | 183 | create_session(&store, &owner.id, "owner-token", CSRF).await; |
| 150 | let router = app_router(state); | 184 | let router = app_router(state); |
| 151 | 185 | ||
| 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 | - | ||
| 159 | let page = Request::builder() | 186 | let page = Request::builder() |
| 160 | .method("GET") | 187 | .method("GET") |
| 161 | .uri("/settings/profile") | 188 | .uri("/settings/profile") |
| @@ -166,8 +193,8 @@ mod tests { | |||
| 166 | let html = | 193 | let html = |
| 167 | String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.expect("body")) | 194 | String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.expect("body")) |
| 168 | .into_owned(); | 195 | .into_owned(); |
| 169 | - assert!(html.contains("<body") && html.contains("data-live=\"/settings/theme/events\"")); | ||
| 170 | assert!(html.contains("data-live=\"/settings/events\"")); | 196 | assert!(html.contains("data-live=\"/settings/events\"")); |
| 197 | + assert!(!html.contains("/settings/theme/events")); | ||
| 171 | } | 198 | } |
| 172 | 199 | ||
| 173 | #[tokio::test] | 200 | #[tokio::test] |
| @@ -205,7 +232,7 @@ mod tests { | |||
| 205 | } | 232 | } |
| 206 | 233 | ||
| 207 | #[tokio::test] | 234 | #[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() { |
| 209 | let dir = tempfile::tempdir().expect("tempdir"); | 236 | let dir = tempfile::tempdir().expect("tempdir"); |
| 210 | let state = test_state(dir.path()).await; | 237 | let state = test_state(dir.path()).await; |
| 211 | let store = state.store.clone(); | 238 | let store = state.store.clone(); |
| @@ -233,4 +260,41 @@ mod tests { | |||
| 233 | let changed = frames.next().await.expect("a frame").expect("data"); | 260 | let changed = frames.next().await.expect("a frame").expect("data"); |
| 234 | assert_eq!(&changed[..], b"event: changed\ndata: 1\n\n"); | 261 | assert_eq!(&changed[..], b"event: changed\ndata: 1\n\n"); |
| 235 | } | 262 | } |
| 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 | + } | ||
| 236 | } | 300 | } |
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< | |||
| 946 | let ghost = state.store.ensure_ghost_user().await?; | 946 | let ghost = state.store.ensure_ghost_user().await?; |
| 947 | match state.store.delete_user(&user_id, &ghost.id).await { | 947 | match state.store.delete_user(&user_id, &ghost.id).await { |
| 948 | Ok(_) => { | 948 | Ok(_) => { |
| 949 | + crate::pages::settings_live::bump_account(state, &user_id); | ||
| 949 | // The account row is gone, so the entry names no actor; the username is kept. | 950 | // The account row is gone, so the entry names no actor; the username is kept. |
| 950 | audit::record( | 951 | audit::record( |
| 951 | &state.store, | 952 | &state.store, |
crates/forge-web/src/views/mod.rsmodified+1 -3
| @@ -165,8 +165,6 @@ pub async fn shell( | |||
| 165 | let back = uri(__cx).path_and_query().map(|p| p.as_str().to_owned()); | 165 | let back = uri(__cx).path_and_query().map(|p| p.as_str().to_owned()); |
| 166 | let lang = i18n::lang(__cx, viewer.map(|(user, _)| user)); | 166 | let lang = i18n::lang(__cx, viewer.map(|(user, _)| user)); |
| 167 | let banner = crate::pages::banner::current(__cx); | 167 | 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"); | ||
| 170 | let banner_back = back.clone().unwrap_or_else(|| "/".to_owned()); | 168 | let banner_back = back.clone().unwrap_or_else(|| "/".to_owned()); |
| 171 | let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss); | 169 | let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss); |
| 172 | // The admin area and the user settings swap the global links for their own list. Signed-in only. | 170 | // 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( | |||
| 269 | } | 267 | } |
| 270 | <script src=(NAV_SCRIPT_HREF) defer="defer"></script> | 268 | <script src=(NAV_SCRIPT_HREF) defer="defer"></script> |
| 271 | </head> | 269 | </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))> |
| 273 | <header class="topbar"> | 271 | <header class="topbar"> |
| 274 | if signed_in { | 272 | if signed_in { |
| 275 | <details class="nav-toggle"> | 273 | <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 | |||
| 272 | | Admin replication `/admin/replication` | `/admin/replication/events` | each copy's status and the database snapshot | | 272 | | Admin replication `/admin/replication` | `/admin/replication/events` | each copy's status and the database snapshot | |
| 273 | | 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 | | 273 | | 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 | |
| 274 | | 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 | | 274 | | 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 | | ||
| 276 | 277 | ||
| 277 | 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. | 278 | 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. |
| 278 | 279 | ||