forge
Explore
Log in

Don't you dare go Hollow

Confirm disclosures, split From name, and the live channel — iz parity

Browse files at this commit

794c3a4ba91fcccf6a6ea568c8b9a0c94428a5a6Ahmet Kaan GümüşParent: 5e196bf
  • feat
    • confirm disclosures, split From name, and the live channel — iz parity
Show full message
feat: confirm disclosures, split From name, and the live channel — iz parity

- Row actions are two-step disclosures now (iz's confirm-details idiom):
  Disable/Enable and Delete open a panel naming the cost, and only the
  button inside it acts. No script required; outside-click/Escape closing
  rides the live script.
- The sender's From splits into name + address like iz's; the header is
  built from the two, never hand-typed as one string.
- The live channel, ported from iz: /admin/live SSE ticks (no data on the
  wire, ever), a 50-minute window so reconnects re-authenticate, and a
  shutdown watch so one open tab per admin cannot stall a restart. The
  client refetches and swaps the panel column, suspending while a field
  has focus. Every event log ticks it, so Users and Logs update the
  moment anything happens — including the mail chip after a save's
  background probe.

Verified: suite 39 green; driven with two tabs — an invite's row and an
accepted member appear without a reload, Logs grows 21→22 on a triggered
check, and Delete needs its confirm step.
Cargo.lockmodified+1 -0
@@ -1823,6 +1823,7 @@ version = "0.1.0"
18231823 dependencies = [
18241824 "base64 0.22.1",
18251825 "data-encoding",
1826+ "futures-util",
18261827 "grass",
18271828 "http",
18281829 "im-core",
crates/im-core/src/settings.rsmodified+23 -3
@@ -13,7 +13,12 @@ pub struct Smtp {
1313 pub host: String,
1414 pub port: u16,
1515 pub username: String,
16+ /// The address mail goes out as.
1617 pub from: String,
18+ /// The name the address wears in a mail client's list — iz keeps the two
19+ /// apart, and so do we: "im <auth@…>" is a header built from two settings,
20+ /// not one string somebody has to get right.
21+ pub from_name: String,
1722 pub password: Option<String>,
1823 }
1924
@@ -21,6 +26,15 @@ impl Smtp {
2126 pub fn configured(&self) -> bool {
2227 !self.host.is_empty() && self.port > 0 && !self.from.is_empty()
2328 }
29+
30+ /// The From header: `Name <address>` when a name is set, the bare
31+ /// address otherwise.
32+ pub fn from_header(&self) -> String {
33+ match self.from_name.trim() {
34+ "" => self.from.clone(),
35+ name => format!("{name} <{}>", self.from),
36+ }
37+ }
2438 }
2539
2640 async fn get(store: &Store, key: &str) -> Result<Option<String>> {
@@ -62,6 +76,7 @@ pub async fn smtp(store: &Store) -> Result<Smtp> {
6276 .unwrap_or(587);
6377 let username = get(store, "smtp_username").await?.unwrap_or_default();
6478 let from = get(store, "smtp_from").await?.unwrap_or_default();
79+ let from_name = get(store, "smtp_from_name").await?.unwrap_or_default();
6580 let password = get(store, "smtp_password")
6681 .await?
6782 .and_then(|sealed| secret::open(store.key(), &sealed))
@@ -71,6 +86,7 @@ pub async fn smtp(store: &Store) -> Result<Smtp> {
7186 port,
7287 username,
7388 from,
89+ from_name,
7490 password,
7591 })
7692 }
@@ -180,7 +196,7 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res
180196 "smtp_port",
181197 "smtp_username",
182198 "smtp_from",
183- "smtp_password",
199+ "smtp_from_name",
184200 "smtp_check_at",
185201 "smtp_check_ms",
186202 "smtp_check_error",
@@ -199,6 +215,7 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res
199215 set(store, "smtp_port", &smtp.port.to_string()).await?;
200216 set(store, "smtp_username", &smtp.username).await?;
201217 set(store, "smtp_from", &smtp.from).await?;
218+ set(store, "smtp_from_name", &smtp.from_name).await?;
202219 if let Some(password) = password {
203220 if !password.is_empty() {
204221 set(
@@ -227,7 +244,8 @@ mod tests {
227244 host: "smtp.example.com".into(),
228245 port: 465,
229246 username: "im".into(),
230- from: "im <auth@example.com>".into(),
247+ from: "auth@example.com".into(),
248+ from_name: "im".into(),
231249 password: None,
232250 };
233251 set_smtp(&store, &value, Some("s3cret")).await.unwrap();
@@ -259,6 +277,7 @@ mod tests {
259277 port: 465,
260278 username: String::new(),
261279 from: "a@b.c".into(),
280+ from_name: String::new(),
262281 password: None,
263282 };
264283 set_smtp(&store, &value, Some("s3cret")).await.unwrap();
@@ -282,7 +301,8 @@ mod tests {
282301 host: "smtp.example.com".into(),
283302 port: 587,
284303 username: "auth@example.com".into(),
285- from: "im <auth@example.com>".into(),
304+ from: "auth@example.com".into(),
305+ from_name: "im".into(),
286306 password: None,
287307 };
288308 set_smtp(&store, &value, Some("s3cret")).await.unwrap();
crates/im-web/Cargo.tomlmodified+2 -0
@@ -17,7 +17,9 @@ topcoat = { version = "0.6.2", default-features = false, features = [
1717 "discover",
1818 "serve",
1919 "compression",
20+ "sse",
2021 ] }
22+futures-util = { version = "0.3", default-features = false }
2123 im-core = { workspace = true, features = ["server"] }
2224 serde.workspace = true
2325 serde_json.workspace = true
crates/im-web/assets/main.cssmodified+38 -0
@@ -546,6 +546,44 @@ body:has(.admin-shell) {
546546 background: var(--danger-tint-alt);
547547 }
548548
549+.admin-confirm {
550+ position: relative;
551+}
552+.admin-confirm summary {
553+ list-style: none;
554+}
555+.admin-confirm summary::-webkit-details-marker {
556+ display: none;
557+}
558+.admin-confirm[open] summary {
559+ background: var(--panel-sunken);
560+}
561+
562+.admin-confirm-pop {
563+ position: absolute;
564+ right: 0;
565+ top: calc(100% + 6px);
566+ z-index: 30;
567+ width: 240px;
568+ padding: 12px;
569+ background: var(--surface);
570+ border: 1px solid var(--border-strong);
571+ border-radius: var(--radius);
572+ display: flex;
573+ flex-direction: column;
574+ gap: 8px;
575+ font-size: 12px;
576+}
577+.admin-confirm-pop .admin-action {
578+ width: 100%;
579+ height: 30px;
580+}
581+
582+.admin-confirm-title {
583+ font-weight: 600;
584+ color: var(--ink);
585+}
586+
549587 input[type=checkbox] {
550588 accent-color: var(--accent);
551589 }
crates/im-web/src/admin.rsmodified+119 -24
@@ -45,6 +45,63 @@ fn escape(raw: &str) -> String {
4545 .replace('"', "&quot;")
4646 }
4747
48+/// One row action as a two-step disclosure — iz's `confirm-details` idiom:
49+/// the summary is the word ("Delete"), the opened panel says what it costs
50+/// and holds the button that actually does it. Works with no script at all;
51+/// the live script adds outside-click closing.
52+fn confirm_action(
53+ id: &str,
54+ action: &str,
55+ word: &str,
56+ extra_class: &str,
57+ title: &str,
58+ cost: &str,
59+ confirm: &str,
60+) -> String {
61+ format!(
62+ r#"<details class="admin-confirm"><summary class="admin-action{extra_class}">{word}</summary><div class="admin-confirm-pop"><div class="admin-confirm-title">{title}</div><div class="muted">{cost}</div><form method="post" action="{action}"><input type="hidden" name="user" value="{id}"><button class="admin-action{extra_class}" type="submit">{confirm}</button></form></div></details>"#
63+ )
64+}
65+/// The panel's live wiring, the client half of `live.rs`. One EventSource
66+/// per tab; a tick re-fetches the page and swaps the panel's body. iz's
67+/// lesson is honored in miniature: the swap must not throw away what someone
68+/// is doing, so a focused field suspends the refresh until the next tick,
69+/// and the morph is one innerHTML swap of the column — small DOM, no diffing
70+/// library needed.
71+///
72+/// The same script closes an open confirm disclosure on outside click and
73+/// Escape — the one bit of behavior the no-script markup cannot do itself.
74+const LIVE_SCRIPT: &str = r#"<script>(function () {
75+ if (window.__imLive) { return; }
76+ window.__imLive = true;
77+ var timer = null;
78+ function refresh() {
79+ timer = null;
80+ var active = document.activeElement;
81+ if (active && /^(INPUT|SELECT|TEXTAREA)$/.test(active.tagName)) { return; }
82+ fetch(location.href).then(function (r) { return r.text(); }).then(function (html) {
83+ var fresh = new DOMParser().parseFromString(html, 'text/html');
84+ var here = document.querySelector('.admin-column');
85+ var there = fresh.querySelector('.admin-column');
86+ if (here && there) { here.innerHTML = there.innerHTML; }
87+ }).catch(function () {});
88+ }
89+ var source = new EventSource('/admin/live');
90+ source.onmessage = function () {
91+ if (timer) { return; }
92+ timer = setTimeout(refresh, 200);
93+ };
94+ document.addEventListener('click', function (e) {
95+ document.querySelectorAll('.admin-confirm[open]').forEach(function (d) {
96+ if (!d.contains(e.target)) { d.removeAttribute('open'); }
97+ });
98+ }, true);
99+ document.addEventListener('keydown', function (e) {
100+ if (e.key !== 'Escape') { return; }
101+ document.querySelectorAll('.admin-confirm[open]').forEach(function (d) { d.removeAttribute('open'); });
102+ }, true);
103+})();</script>"#;
104+
48105 fn back(cx: &Cx, section: &str, extra: &str) -> Result<Response> {
49106 (
50107 StatusCode::SEE_OTHER,
@@ -136,6 +193,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> {
136193 (topcoat::view::Unescaped::new_unchecked(banner))
137194 }
138195 (topcoat::view::Unescaped::new_unchecked(section_html))
196+ (topcoat::view::Unescaped::new_unchecked(LIVE_SCRIPT.to_string()))
139197 </div>
140198 </main>
141199 };
@@ -191,17 +249,43 @@ async fn users_section(
191249 r#"<span class="muted">you</span>"#.to_string()
192250 } else {
193251 let id = escape(&user.id.to_string());
252+ let email = escape(&user.email);
253+ // Every row action is a two-step disclosure — iz's
254+ // confirm-details idiom: the summary is the word, the panel holds
255+ // the button that actually does it. No script required; the live
256+ // script adds outside-click closing on top.
194257 let toggle = if user.disabled {
195- format!(
196- r#"<form method="post" action="/admin/enable"><input type="hidden" name="user" value="{id}"><button class="admin-action" type="submit">Enable</button></form>"#
258+ confirm_action(
259+ &id,
260+ "/admin/enable",
261+ "Enable",
262+ "",
263+ &format!("Enable {email}?"),
264+ "They can sign in again.",
265+ "Confirm enable",
197266 )
198267 } else {
199- format!(
200- r#"<form method="post" action="/admin/disable"><input type="hidden" name="user" value="{id}"><button class="admin-action" type="submit">Disable</button></form>"#
268+ confirm_action(
269+ &id,
270+ "/admin/disable",
271+ "Disable",
272+ "",
273+ &format!("Disable {email}?"),
274+ "They cannot sign in, and every live session ends.",
275+ "Confirm disable",
201276 )
202277 };
278+ let remove = confirm_action(
279+ &id,
280+ "/admin/delete",
281+ "Delete",
282+ " admin-danger",
283+ &format!("Delete {email}?"),
284+ "The account, its sessions and every app token go with it. The address can be invited again, as somebody new.",
285+ "Confirm delete",
286+ );
203287 format!(
204- r#"{toggle}<form method="post" action="/admin/revoke"><input type="hidden" name="user" value="{id}"><button class="admin-action" type="submit">Sign out everywhere</button></form><form method="post" action="/admin/delete"><input type="hidden" name="user" value="{id}"><button class="admin-action admin-danger" type="submit">Delete</button></form>"#
288+ r#"{toggle}<form method="post" action="/admin/revoke"><input type="hidden" name="user" value="{id}"><button class="admin-action" type="submit">Sign out everywhere</button></form>{remove}"#
205289 )
206290 };
207291 rows.push_str(&format!(
@@ -322,8 +406,10 @@ async fn mail_section(cx: &Cx) -> Result<String, topcoat::Error> {
322406 <input class="auth-input auth-input-mono" type="text" name="username" value="{}"></label>
323407 <label class="auth-field"><span class="auth-label">Password</span>
324408 <input class="auth-input auth-input-mono" type="password" name="password" placeholder="{password_note}" autocomplete="off"></label>
325- <label class="auth-field"><span class="auth-label">From</span>
326- <input class="auth-input auth-input-mono" type="text" name="from" value="{}" placeholder="im &lt;auth@example.com&gt;"></label>
409+ <label class="auth-field"><span class="auth-label">From name</span>
410+ <input class="auth-input auth-input-mono" type="text" name="from_name" value="{}" placeholder="im"></label>
411+ <label class="auth-field"><span class="auth-label">From address</span>
412+ <input class="auth-input auth-input-mono" type="text" name="from" value="{}" placeholder="auth@example.com"></label>
327413 <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">Save</span></button>
328414 </form>
329415 {lede_html}
@@ -335,6 +421,7 @@ async fn mail_section(cx: &Cx) -> Result<String, topcoat::Error> {
335421 escape(&smtp.host),
336422 smtp.port,
337423 escape(&smtp.username),
424+ escape(&smtp.from_name),
338425 escape(&smtp.from)
339426 ))
340427 }
@@ -393,8 +480,8 @@ async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Result<Response> {
393480 let mailed = mailer::send_invite(store, &app(cx).config.issuer, &email, token.expose())
394481 .await
395482 .is_ok();
396- events::log(
397- store,
483+ server::log_event(
484+ cx,
398485 "invite_created",
399486 Some(&me.email),
400487 Some(&format!(
@@ -429,7 +516,7 @@ async fn uninvite(cx: &Cx, Form(input): Form<InviteAction>) -> Result<Response>
429516 };
430517 let store = &app(cx).store;
431518 let email = accounts::revoke_invite(store, &input.invite).await?;
432- events::log(store, "invite_revoked", Some(&me.email), email.as_deref()).await;
519+ server::log_event(cx, "invite_revoked", Some(&me.email), email.as_deref()).await;
433520 back(cx, "users", "&ok=uninvited")
434521 }
435522
@@ -448,7 +535,7 @@ async fn delete(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> {
448535 .await?
449536 .map(|u| u.email);
450537 accounts::delete_user(store, &user_id).await?;
451- events::log(store, "user_deleted", Some(&me.email), email.as_deref()).await;
538+ server::log_event(cx, "user_deleted", Some(&me.email), email.as_deref()).await;
452539 back(cx, "users", "&ok=deleted")
453540 }
454541
@@ -488,7 +575,7 @@ async fn password(cx: &Cx, Form(input): Form<PasswordForm>) -> Result<Response>
488575 if let Some(token) = server::presented_session(cx) {
489576 im_core::sessions::revoke_user_sessions_except(store, &me.id, &token).await?;
490577 }
491- events::log(store, "password_changed", Some(&me.email), None).await;
578+ server::log_event(cx, "password_changed", Some(&me.email), None).await;
492579 back(cx, "account", "&ok=password")
493580 }
494581 #[derive(Deserialize)]
@@ -508,8 +595,8 @@ async fn revoke(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> {
508595 let email = accounts::user_by_id(store, &user_id)
509596 .await?
510597 .map(|u| u.email);
511- events::log(
512- store,
598+ server::log_event(
599+ cx,
513600 "sessions_revoked",
514601 Some(&me.email),
515602 Some(&format!(
@@ -546,8 +633,8 @@ async fn set_disabled(cx: &Cx, input: UserAction, disabled: bool) -> Result<Resp
546633 let email = accounts::user_by_id(store, &user_id)
547634 .await?
548635 .map(|u| u.email);
549- events::log(
550- store,
636+ server::log_event(
637+ cx,
551638 if disabled {
552639 "user_disabled"
553640 } else {
@@ -574,6 +661,8 @@ struct SmtpForm {
574661 port: u16,
575662 username: String,
576663 password: Option<String>,
664+ #[serde(default)]
665+ from_name: String,
577666 from: String,
578667 }
579668
@@ -589,13 +678,14 @@ async fn smtp_save(cx: &Cx, Form(input): Form<SmtpForm>) -> Result<Response> {
589678 port: input.port,
590679 username: input.username.trim().to_string(),
591680 from: input.from.trim().to_string(),
681+ from_name: input.from_name.trim().to_string(),
592682 password: None,
593683 };
594684 settings::set_smtp(store, &value, input.password.as_deref()).await?;
595- events::log(store, "smtp_updated", Some(&me.email), None).await;
685+ server::log_event(cx, "smtp_updated", Some(&me.email), None).await;
596686 // The saved sender gets re-probed in the background — the standing line
597687 // on the Mail section catches up on the next view, like izlek's panel.
598- tokio::spawn(probe(store_of(cx)));
688+ tokio::spawn(probe(store_of(cx), app(cx).live.clone()));
599689 back(cx, "mail", "&ok=smtp")
600690 }
601691
@@ -607,12 +697,12 @@ async fn smtp_test(cx: &Cx) -> Result<Response> {
607697 };
608698 match mailer::send_test(&app(cx).store, &me.email).await {
609699 Ok(()) => {
610- events::log(&app(cx).store, "smtp_test_sent", Some(&me.email), None).await;
700+ server::log_event(cx, "smtp_test_sent", Some(&me.email), None).await;
611701 back(cx, "mail", "&ok=smtp_test")
612702 }
613703 Err(e) => {
614- events::log(
615- &app(cx).store,
704+ server::log_event(
705+ cx,
616706 "smtp_test_failed",
617707 Some(&me.email),
618708 Some(&e.to_string()),
@@ -638,8 +728,8 @@ async fn smtp_check(cx: &Cx) -> Result<Response> {
638728 Ok(me) => me,
639729 Err(redirect) => return Ok(redirect),
640730 };
641- probe(store_of(cx)).await;
642- events::log(&app(cx).store, "smtp_checked", Some(&me.email), None).await;
731+ probe(store_of(cx), app(cx).live.clone()).await;
732+ server::log_event(cx, "smtp_checked", Some(&me.email), None).await;
643733 back(cx, "mail", "")
644734 }
645735
@@ -651,7 +741,10 @@ fn store_of(cx: &Cx) -> std::sync::Arc<im_core::store::Store> {
651741 /// and the after-save probe: a saved sender is re-probed in the background,
652742 /// so the standing line catches up on the next view without making the save
653743 /// itself wait on a mail server.
654-async fn probe(store: std::sync::Arc<im_core::store::Store>) {
744+async fn probe(
745+ store: std::sync::Arc<im_core::store::Store>,
746+ live: tokio::sync::broadcast::Sender<()>,
747+) {
655748 let check = match mailer::check(&store).await {
656749 Ok(took_ms) => settings::SenderCheck {
657750 at: time::OffsetDateTime::now_utc(),
@@ -667,4 +760,6 @@ async fn probe(store: std::sync::Arc<im_core::store::Store>) {
667760 if let Err(problem) = settings::record_check(&store, &check).await {
668761 eprintln!("im: failed to record the sender check: {problem}");
669762 }
763+ // The chip changed; watching tabs re-read it on the next tick.
764+ let _ = live.send(());
670765 }
crates/im-web/src/auth.rsmodified+6 -6
@@ -76,7 +76,7 @@ async fn login(cx: &Cx, Form(input): Form<LoginForm>) -> Redirect {
7676 Err(_) => {
7777 // The failure is logged against the address tried, never the
7878 // password — and never whether the address exists.
79- im_core::events::log(store, "login_fail", Some(&input.email), None).await;
79+ server::log_event(cx, "login_fail", Some(&input.email), None).await;
8080 see(format!("/login?error=bad_login&back={}", urlencode(&back)))
8181 }
8282 }
@@ -112,14 +112,14 @@ async fn login_totp(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect {
112112 None => false,
113113 };
114114 if !ok {
115- im_core::events::log(store, "totp_fail", None, Some("login")).await;
115+ server::log_event(cx, "totp_fail", None, Some("login")).await;
116116 return see("/login/totp?error=bad_code".to_string());
117117 }
118118 let token = im_core::sessions::create_session(store, &user_id).await?;
119119 let email = accounts::user_by_id(store, &user_id)
120120 .await?
121121 .map(|u| u.email);
122- im_core::events::log(store, "login_ok", email.as_deref(), Some("2fa")).await;
122+ server::log_event(cx, "login_ok", email.as_deref(), Some("2fa")).await;
123123 server::clear_pending_cookie(cx);
124124 server::set_session_cookie(cx, token.expose());
125125 see(pending.back)
@@ -175,7 +175,7 @@ async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Redirect {
175175 im_core::totp::set_totp(store, &user.id, &secret).await?;
176176 let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, "/".to_string());
177177 server::set_pending_cookie(cx, sealed);
178- im_core::events::log(store, "invite_accepted", Some(&user.email), None).await;
178+ server::log_event(cx, "invite_accepted", Some(&user.email), None).await;
179179 see("/enroll".to_string())
180180 }
181181
@@ -200,7 +200,7 @@ async fn enroll(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect {
200200 let email = accounts::user_by_id(store, &user_id)
201201 .await?
202202 .map(|u| u.email);
203- im_core::events::log(store, "enrolled", email.as_deref(), None).await;
203+ server::log_event(cx, "enrolled", email.as_deref(), None).await;
204204 server::clear_pending_cookie(cx);
205205 server::set_session_cookie(cx, token.expose());
206206 // A migrated user who was mid-`/authorize` continues to their app; a
@@ -221,7 +221,7 @@ async fn logout(cx: &Cx) -> Redirect {
221221 .await?
222222 .map(|u| u.email);
223223 im_core::sessions::revoke_session(&server::app(cx).store, &token).await?;
224- im_core::events::log(&server::app(cx).store, "logout", email.as_deref(), None).await;
224+ server::log_event(cx, "logout", email.as_deref(), None).await;
225225 }
226226 server::clear_session_cookie(cx);
227227 see("/".to_string())
crates/im-web/src/live.rsadded+104 -0
@@ -0,0 +1,104 @@
1+//! The live channel: one long-lived connection per open admin tab, carrying
2+//! the news that something changed — ported from iz's `live.rs`.
3+//!
4+//! What travels here is a bare tick and nothing else — never a row, never a
5+//! name. The client is told only *that* the panel moved, and re-fetches it
6+//! through the ordinary route, where the ordinary admin gate answers. The
7+//! route itself is admin-gated, and the whole panel behind it is admin-only,
8+//! so there is no per-topic filtering to get wrong.
9+
10+use std::time::{Duration, Instant};
11+
12+use futures_util::StreamExt;
13+use tokio::sync::broadcast::error::RecvError;
14+use topcoat::context::Cx;
15+use topcoat::router::content::sse::{Event, KeepAlive, Sse};
16+use topcoat::router::response::{IntoResponse, Response};
17+use topcoat::router::{StatusCode, route};
18+
19+use crate::server;
20+
21+/// How long one connection is held before the server ends it and the browser
22+/// opens another. The session is resolved once, at connect, and never again
23+/// for the life of the stream — the reconnect is what re-authenticates, so a
24+/// session revoked mid-stream goes quiet within one window rather than never.
25+const WINDOW: Duration = Duration::from_secs(50 * 60);
26+
27+/// Tells a live stream that the process is going down.
28+///
29+/// Without this, stopping the server takes as long as its graceful shutdown
30+/// allows: the server stops accepting connections and then waits for
31+/// in-flight requests to finish, and an open live stream is an in-flight
32+/// request that intends to sit there for the whole window. Every open admin
33+/// tab is one. So the streams are told, and they end; the browser reconnects
34+/// when the server comes back, which is what it does after any dropped
35+/// connection.
36+#[derive(Clone)]
37+pub struct Shutdown(pub tokio::sync::watch::Receiver<bool>);
38+
39+#[route(GET "/admin/live")]
40+async fn live(cx: &Cx) -> topcoat::Result<Response> {
41+ // Resolved once, here, and never again for the life of this connection.
42+ let Ok(_admin) = server::current_user(cx)
43+ .await
44+ .filter(|user| user.admin)
45+ .ok_or(())
46+ else {
47+ return (StatusCode::UNAUTHORIZED, "").into_response(cx);
48+ };
49+ let rx = server::app(cx).live.subscribe();
50+ let stopping = topcoat::context::try_app_context::<Shutdown>(cx).map(|s| s.0.clone());
51+ let deadline = Instant::now() + WINDOW;
52+
53+ let events = futures_util::stream::unfold(
54+ (rx, deadline, stopping),
55+ |(mut rx, deadline, mut stopping)| async move {
56+ loop {
57+ // Already going down: end, so this connection is not one the
58+ // shutdown has to sit and wait out.
59+ if stopping.as_ref().is_some_and(|watch| *watch.borrow()) {
60+ return None;
61+ }
62+ let left = deadline.saturating_duration_since(Instant::now());
63+ if left.is_zero() {
64+ return None;
65+ }
66+ // Three things end the wait: an announcement, the window
67+ // running out, and the server being told to stop. The third
68+ // is watched rather than polled, so SIGTERM is felt at once.
69+ let heard = tokio::time::timeout(left, async {
70+ match stopping.as_mut() {
71+ Some(watch) => tokio::select! {
72+ _ = watch.changed() => None,
73+ got = rx.recv() => Some(got),
74+ },
75+ None => Some(rx.recv().await),
76+ }
77+ })
78+ .await;
79+ match heard {
80+ // The window closed, or the server is stopping. Ending
81+ // the stream is the point: the browser reconnects by
82+ // itself and authenticates again.
83+ Err(_) | Ok(None) => return None,
84+ // The broadcaster is gone, which means the process is
85+ // going with it.
86+ Ok(Some(Err(RecvError::Closed))) => return None,
87+ // This reader fell behind and announcements were dropped.
88+ // Which ones is unknowable, so the tick says "re-read
89+ // everything" — the client refetches the whole page, so
90+ // a lagged tick and a plain tick are the same frame.
91+ Ok(Some(Err(RecvError::Lagged(_)))) | Ok(Some(Ok(()))) => {}
92+ }
93+ return Some((
94+ Ok::<_, std::convert::Infallible>(Event::new().data("{}")),
95+ (rx, deadline, stopping),
96+ ));
97+ }
98+ },
99+ );
100+
101+ Sse::new(events.boxed())
102+ .keep_alive(KeepAlive::new())
103+ .into_response(cx)
104+}
crates/im-web/src/mailer.rsmodified+1 -1
@@ -53,7 +53,7 @@ async fn send(store: &Store, to: &str, subject: &str, body: String) -> Result<()
5353 let smtp = settings::smtp(store).await?;
5454 let message = lettre::Message::builder()
5555 .from(
56- smtp.from
56+ smtp.from_header()
5757 .parse()
5858 .map_err(|e| MailError::Backend(format!("smtp from: {e}")))?,
5959 )
crates/im-web/src/main.rsmodified+13 -6
@@ -14,6 +14,7 @@ mod admin;
1414 mod auth;
1515 mod config;
1616 mod layout;
17+mod live;
1718 mod mailer;
1819 mod oidc;
1920 mod pages;
@@ -204,19 +205,21 @@ async fn create_client(config: Config, name: &str, uris: &[String]) {
204205 println!(" client_secret {}", secret.expose());
205206 println!(" (the secret is shown once; its digest is all the database keeps)");
206207 }
207-
208208 async fn serve(config: Config) {
209209 for line in config.report() {
210210 println!("im {line}");
211211 }
212212 let store = open_store(&config).await;
213+ let (live, _) = tokio::sync::broadcast::channel(64);
214+ // Told when the process is stopping, so the live streams end instead of
215+ // being waited out — see `live::Shutdown`.
216+ let (stop, stopping) = tokio::sync::watch::channel(false);
213217 let app = server::App {
214218 store,
215219 config: config.clone(),
220+ live,
216221 };
217222
218- // The bundle beside the executable is the only stylesheet this process
219- // can serve — `topcoat asset bundle -p im-web` produces it.
220223 let bundle = topcoat::asset::AssetBundle::load().unwrap_or_else(|err| {
221224 eprintln!("im: the asset bundle beside the executable failed to load: {err}");
222225 eprintln!("im: run `topcoat asset bundle -p im-web` first");
@@ -228,6 +231,7 @@ async fn serve(config: Config) {
228231 .cookies()
229232 .assets(bundle)
230233 .app_context(app)
234+ .app_context(live::Shutdown(stopping))
231235 .build();
232236
233237 // `topcoat::start` binds HOST/PORT from the environment; the listen
@@ -236,14 +240,15 @@ async fn serve(config: Config) {
236240 let listener = tokio::net::TcpListener::bind(config.listen)
237241 .await
238242 .expect("failed to bind the listen address");
239- topcoat::serve_until(listener, router, shutdown_signal())
243+ topcoat::serve_until(listener, router, shutdown_signal(stop))
240244 .await
241245 .expect("server error");
242246 }
243247
244248 /// Resolves when the process is asked to stop: Ctrl+C, or `SIGTERM` from a
245-/// service manager.
246-async fn shutdown_signal() {
249+/// service manager. The live streams hear it first, so the graceful shutdown
250+/// does not sit waiting on one long-lived connection per open tab.
251+async fn shutdown_signal(stop: tokio::sync::watch::Sender<bool>) {
247252 let ctrl_c = async {
248253 tokio::signal::ctrl_c()
249254 .await
@@ -262,4 +267,6 @@ async fn shutdown_signal() {
262267 () = ctrl_c => {},
263268 () = terminate => {},
264269 }
270+ // Streams end on their own; the browser reconnects when we are back.
271+ let _ = stop.send(true);
265272 }
crates/im-web/src/oidc.rsmodified+1 -2
@@ -302,8 +302,7 @@ async fn exchange(cx: &Cx, Form(input): Form<TokenForm>) -> Result<Response> {
302302 &consumed.session_hash,
303303 )
304304 .await?;
305- im_core::events::log(
306- &app(cx).store,
305+ server::log_event(cx,
307306 "code_exchanged",
308307 Some(&user.email),
309308 Some(&format!("via {}", client.name)),
crates/im-web/src/server.rsmodified+17 -0
@@ -26,6 +26,23 @@ pub const PENDING_MINUTES: i64 = 10;
2626 pub struct App {
2727 pub store: Arc<Store>,
2828 pub config: Config,
29+ /// The live channel's ticker: any mutation announces itself here, and
30+ /// every open admin tab re-reads what it is showing. Carries no data —
31+ /// a tick says "re-fetch", nothing more.
32+ pub live: tokio::sync::broadcast::Sender<()>,
33+}
34+
35+/// Announce that the panel's data moved. Sends are lossy on purpose: nobody
36+/// listening is not an error, and a lagging tab gets a resync tick.
37+pub fn note(cx: &Cx) {
38+ let _ = app(cx).live.send(());
39+}
40+
41+/// Log the event, then tick the live channel — the two travel together so
42+/// the Logs page (and any watching panel) catches up without a reload.
43+pub async fn log_event(cx: &Cx, kind: &str, actor: Option<&str>, detail: Option<&str>) {
44+ im_core::events::log(&app(cx).store, kind, actor, detail).await;
45+ note(cx);
2946 }
3047
3148 pub fn app(cx: &Cx) -> &App {
style/main.scssmodified+34 -0
@@ -586,6 +586,40 @@ body:has(.admin-shell) {
586586 &:hover { background: var(--danger-tint-alt); }
587587 }
588588
589+// The two-step row action, iz's confirm-details: the summary wears the
590+// button skin; the popover names the cost and holds the real button.
591+.admin-confirm {
592+ position: relative;
593+
594+ summary {
595+ list-style: none;
596+
597+ &::-webkit-details-marker { display: none; }
598+ }
599+
600+ &[open] summary { background: var(--panel-sunken); }
601+}
602+
603+.admin-confirm-pop {
604+ position: absolute;
605+ right: 0;
606+ top: calc(100% + 6px);
607+ z-index: 30;
608+ width: 240px;
609+ padding: 12px;
610+ background: var(--surface);
611+ border: 1px solid var(--border-strong);
612+ border-radius: var(--radius);
613+ display: flex;
614+ flex-direction: column;
615+ gap: 8px;
616+ font-size: 12px;
617+
618+ .admin-action { width: 100%; height: 30px; }
619+}
620+
621+.admin-confirm-title { font-weight: 600; color: var(--ink); }
622+
589623 input[type="checkbox"] { accent-color: var(--accent); }
590624
591625 @media (max-width: 720px) {