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"
1823 dependencies = [1823 dependencies = [
1824 "base64 0.22.1",1824 "base64 0.22.1",
1825 "data-encoding",1825 "data-encoding",
1826+ "futures-util",
1826 "grass",1827 "grass",
1827 "http",1828 "http",
1828 "im-core",1829 "im-core",
crates/im-core/src/settings.rsmodified+23 -3
@@ -13,7 +13,12 @@ pub struct Smtp {
13 pub host: String,13 pub host: String,
14 pub port: u16,14 pub port: u16,
15 pub username: String,15 pub username: String,
16+ /// The address mail goes out as.
16 pub from: String,17 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,
17 pub password: Option<String>,22 pub password: Option<String>,
18 }23 }
19 24
@@ -21,6 +26,15 @@ impl Smtp {
21 pub fn configured(&self) -> bool {26 pub fn configured(&self) -> bool {
22 !self.host.is_empty() && self.port > 0 && !self.from.is_empty()27 !self.host.is_empty() && self.port > 0 && !self.from.is_empty()
23 }28 }
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+ }
24 }38 }
25 39
26 async fn get(store: &Store, key: &str) -> Result<Option<String>> {40 async fn get(store: &Store, key: &str) -> Result<Option<String>> {
@@ -62,6 +76,7 @@ pub async fn smtp(store: &Store) -> Result<Smtp> {
62 .unwrap_or(587);76 .unwrap_or(587);
63 let username = get(store, "smtp_username").await?.unwrap_or_default();77 let username = get(store, "smtp_username").await?.unwrap_or_default();
64 let from = get(store, "smtp_from").await?.unwrap_or_default();78 let from = get(store, "smtp_from").await?.unwrap_or_default();
79+ let from_name = get(store, "smtp_from_name").await?.unwrap_or_default();
65 let password = get(store, "smtp_password")80 let password = get(store, "smtp_password")
66 .await?81 .await?
67 .and_then(|sealed| secret::open(store.key(), &sealed))82 .and_then(|sealed| secret::open(store.key(), &sealed))
@@ -71,6 +86,7 @@ pub async fn smtp(store: &Store) -> Result<Smtp> {
71 port,86 port,
72 username,87 username,
73 from,88 from,
89+ from_name,
74 password,90 password,
75 })91 })
76 }92 }
@@ -180,7 +196,7 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res
180 "smtp_port",196 "smtp_port",
181 "smtp_username",197 "smtp_username",
182 "smtp_from",198 "smtp_from",
183- "smtp_password",199+ "smtp_from_name",
184 "smtp_check_at",200 "smtp_check_at",
185 "smtp_check_ms",201 "smtp_check_ms",
186 "smtp_check_error",202 "smtp_check_error",
@@ -199,6 +215,7 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res
199 set(store, "smtp_port", &smtp.port.to_string()).await?;215 set(store, "smtp_port", &smtp.port.to_string()).await?;
200 set(store, "smtp_username", &smtp.username).await?;216 set(store, "smtp_username", &smtp.username).await?;
201 set(store, "smtp_from", &smtp.from).await?;217 set(store, "smtp_from", &smtp.from).await?;
218+ set(store, "smtp_from_name", &smtp.from_name).await?;
202 if let Some(password) = password {219 if let Some(password) = password {
203 if !password.is_empty() {220 if !password.is_empty() {
204 set(221 set(
@@ -227,7 +244,8 @@ mod tests {
227 host: "smtp.example.com".into(),244 host: "smtp.example.com".into(),
228 port: 465,245 port: 465,
229 username: "im".into(),246 username: "im".into(),
230- from: "im <auth@example.com>".into(),247+ from: "auth@example.com".into(),
248+ from_name: "im".into(),
231 password: None,249 password: None,
232 };250 };
233 set_smtp(&store, &value, Some("s3cret")).await.unwrap();251 set_smtp(&store, &value, Some("s3cret")).await.unwrap();
@@ -259,6 +277,7 @@ mod tests {
259 port: 465,277 port: 465,
260 username: String::new(),278 username: String::new(),
261 from: "a@b.c".into(),279 from: "a@b.c".into(),
280+ from_name: String::new(),
262 password: None,281 password: None,
263 };282 };
264 set_smtp(&store, &value, Some("s3cret")).await.unwrap();283 set_smtp(&store, &value, Some("s3cret")).await.unwrap();
@@ -282,7 +301,8 @@ mod tests {
282 host: "smtp.example.com".into(),301 host: "smtp.example.com".into(),
283 port: 587,302 port: 587,
284 username: "auth@example.com".into(),303 username: "auth@example.com".into(),
285- from: "im <auth@example.com>".into(),304+ from: "auth@example.com".into(),
305+ from_name: "im".into(),
286 password: None,306 password: None,
287 };307 };
288 set_smtp(&store, &value, Some("s3cret")).await.unwrap();308 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 = [
17 "discover",17 "discover",
18 "serve",18 "serve",
19 "compression",19 "compression",
20+ "sse",
20 ] }21 ] }
22+futures-util = { version = "0.3", default-features = false }
21 im-core = { workspace = true, features = ["server"] }23 im-core = { workspace = true, features = ["server"] }
22 serde.workspace = true24 serde.workspace = true
23 serde_json.workspace = true25 serde_json.workspace = true
crates/im-web/assets/main.cssmodified+38 -0
@@ -546,6 +546,44 @@ body:has(.admin-shell) {
546 background: var(--danger-tint-alt);546 background: var(--danger-tint-alt);
547 }547 }
548 548
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+
549 input[type=checkbox] {587 input[type=checkbox] {
550 accent-color: var(--accent);588 accent-color: var(--accent);
551 }589 }
crates/im-web/src/admin.rsmodified+119 -24
@@ -45,6 +45,63 @@ fn escape(raw: &str) -> String {
45 .replace('"', "&quot;")45 .replace('"', "&quot;")
46 }46 }
47 47
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+
48 fn back(cx: &Cx, section: &str, extra: &str) -> Result<Response> {105 fn back(cx: &Cx, section: &str, extra: &str) -> Result<Response> {
49 (106 (
50 StatusCode::SEE_OTHER,107 StatusCode::SEE_OTHER,
@@ -136,6 +193,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> {
136 (topcoat::view::Unescaped::new_unchecked(banner))193 (topcoat::view::Unescaped::new_unchecked(banner))
137 }194 }
138 (topcoat::view::Unescaped::new_unchecked(section_html))195 (topcoat::view::Unescaped::new_unchecked(section_html))
196+ (topcoat::view::Unescaped::new_unchecked(LIVE_SCRIPT.to_string()))
139 </div>197 </div>
140 </main>198 </main>
141 };199 };
@@ -191,17 +249,43 @@ async fn users_section(
191 r#"<span class="muted">you</span>"#.to_string()249 r#"<span class="muted">you</span>"#.to_string()
192 } else {250 } else {
193 let id = escape(&user.id.to_string());251 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.
194 let toggle = if user.disabled {257 let toggle = if user.disabled {
195- format!(258+ confirm_action(
196- r#"<form method="post" action="/admin/enable"><input type="hidden" name="user" value="{id}"><button class="admin-action" type="submit">Enable</button></form>"#259+ &id,
260+ "/admin/enable",
261+ "Enable",
262+ "",
263+ &format!("Enable {email}?"),
264+ "They can sign in again.",
265+ "Confirm enable",
197 )266 )
198 } else {267 } else {
199- format!(268+ confirm_action(
200- r#"<form method="post" action="/admin/disable"><input type="hidden" name="user" value="{id}"><button class="admin-action" type="submit">Disable</button></form>"#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",
201 )276 )
202 };277 };
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+ );
203 format!(287 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}"#
205 )289 )
206 };290 };
207 rows.push_str(&format!(291 rows.push_str(&format!(
@@ -322,8 +406,10 @@ async fn mail_section(cx: &Cx) -> Result<String, topcoat::Error> {
322 <input class="auth-input auth-input-mono" type="text" name="username" value="{}"></label>406 <input class="auth-input auth-input-mono" type="text" name="username" value="{}"></label>
323 <label class="auth-field"><span class="auth-label">Password</span>407 <label class="auth-field"><span class="auth-label">Password</span>
324 <input class="auth-input auth-input-mono" type="password" name="password" placeholder="{password_note}" autocomplete="off"></label>408 <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>409+ <label class="auth-field"><span class="auth-label">From name</span>
326- <input class="auth-input auth-input-mono" type="text" name="from" value="{}" placeholder="im &lt;auth@example.com&gt;"></label>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>
327 <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">Save</span></button>413 <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">Save</span></button>
328 </form>414 </form>
329 {lede_html}415 {lede_html}
@@ -335,6 +421,7 @@ async fn mail_section(cx: &Cx) -> Result<String, topcoat::Error> {
335 escape(&smtp.host),421 escape(&smtp.host),
336 smtp.port,422 smtp.port,
337 escape(&smtp.username),423 escape(&smtp.username),
424+ escape(&smtp.from_name),
338 escape(&smtp.from)425 escape(&smtp.from)
339 ))426 ))
340 }427 }
@@ -393,8 +480,8 @@ async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Result<Response> {
393 let mailed = mailer::send_invite(store, &app(cx).config.issuer, &email, token.expose())480 let mailed = mailer::send_invite(store, &app(cx).config.issuer, &email, token.expose())
394 .await481 .await
395 .is_ok();482 .is_ok();
396- events::log(483+ server::log_event(
397- store,484+ cx,
398 "invite_created",485 "invite_created",
399 Some(&me.email),486 Some(&me.email),
400 Some(&format!(487 Some(&format!(
@@ -429,7 +516,7 @@ async fn uninvite(cx: &Cx, Form(input): Form<InviteAction>) -> Result<Response>
429 };516 };
430 let store = &app(cx).store;517 let store = &app(cx).store;
431 let email = accounts::revoke_invite(store, &input.invite).await?;518 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;
433 back(cx, "users", "&ok=uninvited")520 back(cx, "users", "&ok=uninvited")
434 }521 }
435 522
@@ -448,7 +535,7 @@ async fn delete(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> {
448 .await?535 .await?
449 .map(|u| u.email);536 .map(|u| u.email);
450 accounts::delete_user(store, &user_id).await?;537 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;
452 back(cx, "users", "&ok=deleted")539 back(cx, "users", "&ok=deleted")
453 }540 }
454 541
@@ -488,7 +575,7 @@ async fn password(cx: &Cx, Form(input): Form<PasswordForm>) -> Result<Response>
488 if let Some(token) = server::presented_session(cx) {575 if let Some(token) = server::presented_session(cx) {
489 im_core::sessions::revoke_user_sessions_except(store, &me.id, &token).await?;576 im_core::sessions::revoke_user_sessions_except(store, &me.id, &token).await?;
490 }577 }
491- events::log(store, "password_changed", Some(&me.email), None).await;578+ server::log_event(cx, "password_changed", Some(&me.email), None).await;
492 back(cx, "account", "&ok=password")579 back(cx, "account", "&ok=password")
493 }580 }
494 #[derive(Deserialize)]581 #[derive(Deserialize)]
@@ -508,8 +595,8 @@ async fn revoke(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> {
508 let email = accounts::user_by_id(store, &user_id)595 let email = accounts::user_by_id(store, &user_id)
509 .await?596 .await?
510 .map(|u| u.email);597 .map(|u| u.email);
511- events::log(598+ server::log_event(
512- store,599+ cx,
513 "sessions_revoked",600 "sessions_revoked",
514 Some(&me.email),601 Some(&me.email),
515 Some(&format!(602 Some(&format!(
@@ -546,8 +633,8 @@ async fn set_disabled(cx: &Cx, input: UserAction, disabled: bool) -> Result<Resp
546 let email = accounts::user_by_id(store, &user_id)633 let email = accounts::user_by_id(store, &user_id)
547 .await?634 .await?
548 .map(|u| u.email);635 .map(|u| u.email);
549- events::log(636+ server::log_event(
550- store,637+ cx,
551 if disabled {638 if disabled {
552 "user_disabled"639 "user_disabled"
553 } else {640 } else {
@@ -574,6 +661,8 @@ struct SmtpForm {
574 port: u16,661 port: u16,
575 username: String,662 username: String,
576 password: Option<String>,663 password: Option<String>,
664+ #[serde(default)]
665+ from_name: String,
577 from: String,666 from: String,
578 }667 }
579 668
@@ -589,13 +678,14 @@ async fn smtp_save(cx: &Cx, Form(input): Form<SmtpForm>) -> Result<Response> {
589 port: input.port,678 port: input.port,
590 username: input.username.trim().to_string(),679 username: input.username.trim().to_string(),
591 from: input.from.trim().to_string(),680 from: input.from.trim().to_string(),
681+ from_name: input.from_name.trim().to_string(),
592 password: None,682 password: None,
593 };683 };
594 settings::set_smtp(store, &value, input.password.as_deref()).await?;684 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;
596 // The saved sender gets re-probed in the background — the standing line686 // The saved sender gets re-probed in the background — the standing line
597 // on the Mail section catches up on the next view, like izlek's panel.687 // 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()));
599 back(cx, "mail", "&ok=smtp")689 back(cx, "mail", "&ok=smtp")
600 }690 }
601 691
@@ -607,12 +697,12 @@ async fn smtp_test(cx: &Cx) -> Result<Response> {
607 };697 };
608 match mailer::send_test(&app(cx).store, &me.email).await {698 match mailer::send_test(&app(cx).store, &me.email).await {
609 Ok(()) => {699 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;
611 back(cx, "mail", "&ok=smtp_test")701 back(cx, "mail", "&ok=smtp_test")
612 }702 }
613 Err(e) => {703 Err(e) => {
614- events::log(704+ server::log_event(
615- &app(cx).store,705+ cx,
616 "smtp_test_failed",706 "smtp_test_failed",
617 Some(&me.email),707 Some(&me.email),
618 Some(&e.to_string()),708 Some(&e.to_string()),
@@ -638,8 +728,8 @@ async fn smtp_check(cx: &Cx) -> Result<Response> {
638 Ok(me) => me,728 Ok(me) => me,
639 Err(redirect) => return Ok(redirect),729 Err(redirect) => return Ok(redirect),
640 };730 };
641- probe(store_of(cx)).await;731+ probe(store_of(cx), app(cx).live.clone()).await;
642- events::log(&app(cx).store, "smtp_checked", Some(&me.email), None).await;732+ server::log_event(cx, "smtp_checked", Some(&me.email), None).await;
643 back(cx, "mail", "")733 back(cx, "mail", "")
644 }734 }
645 735
@@ -651,7 +741,10 @@ fn store_of(cx: &Cx) -> std::sync::Arc<im_core::store::Store> {
651 /// and the after-save probe: a saved sender is re-probed in the background,741 /// and the after-save probe: a saved sender is re-probed in the background,
652 /// so the standing line catches up on the next view without making the save742 /// so the standing line catches up on the next view without making the save
653 /// itself wait on a mail server.743 /// 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+) {
655 let check = match mailer::check(&store).await {748 let check = match mailer::check(&store).await {
656 Ok(took_ms) => settings::SenderCheck {749 Ok(took_ms) => settings::SenderCheck {
657 at: time::OffsetDateTime::now_utc(),750 at: time::OffsetDateTime::now_utc(),
@@ -667,4 +760,6 @@ async fn probe(store: std::sync::Arc<im_core::store::Store>) {
667 if let Err(problem) = settings::record_check(&store, &check).await {760 if let Err(problem) = settings::record_check(&store, &check).await {
668 eprintln!("im: failed to record the sender check: {problem}");761 eprintln!("im: failed to record the sender check: {problem}");
669 }762 }
763+ // The chip changed; watching tabs re-read it on the next tick.
764+ let _ = live.send(());
670 }765 }
crates/im-web/src/auth.rsmodified+6 -6
@@ -76,7 +76,7 @@ async fn login(cx: &Cx, Form(input): Form<LoginForm>) -> Redirect {
76 Err(_) => {76 Err(_) => {
77 // The failure is logged against the address tried, never the77 // The failure is logged against the address tried, never the
78 // password — and never whether the address exists.78 // 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;
80 see(format!("/login?error=bad_login&back={}", urlencode(&back)))80 see(format!("/login?error=bad_login&back={}", urlencode(&back)))
81 }81 }
82 }82 }
@@ -112,14 +112,14 @@ async fn login_totp(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect {
112 None => false,112 None => false,
113 };113 };
114 if !ok {114 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;
116 return see("/login/totp?error=bad_code".to_string());116 return see("/login/totp?error=bad_code".to_string());
117 }117 }
118 let token = im_core::sessions::create_session(store, &user_id).await?;118 let token = im_core::sessions::create_session(store, &user_id).await?;
119 let email = accounts::user_by_id(store, &user_id)119 let email = accounts::user_by_id(store, &user_id)
120 .await?120 .await?
121 .map(|u| u.email);121 .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;
123 server::clear_pending_cookie(cx);123 server::clear_pending_cookie(cx);
124 server::set_session_cookie(cx, token.expose());124 server::set_session_cookie(cx, token.expose());
125 see(pending.back)125 see(pending.back)
@@ -175,7 +175,7 @@ async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Redirect {
175 im_core::totp::set_totp(store, &user.id, &secret).await?;175 im_core::totp::set_totp(store, &user.id, &secret).await?;
176 let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, "/".to_string());176 let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, "/".to_string());
177 server::set_pending_cookie(cx, sealed);177 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;
179 see("/enroll".to_string())179 see("/enroll".to_string())
180 }180 }
181 181
@@ -200,7 +200,7 @@ async fn enroll(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect {
200 let email = accounts::user_by_id(store, &user_id)200 let email = accounts::user_by_id(store, &user_id)
201 .await?201 .await?
202 .map(|u| u.email);202 .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;
204 server::clear_pending_cookie(cx);204 server::clear_pending_cookie(cx);
205 server::set_session_cookie(cx, token.expose());205 server::set_session_cookie(cx, token.expose());
206 // A migrated user who was mid-`/authorize` continues to their app; a206 // A migrated user who was mid-`/authorize` continues to their app; a
@@ -221,7 +221,7 @@ async fn logout(cx: &Cx) -> Redirect {
221 .await?221 .await?
222 .map(|u| u.email);222 .map(|u| u.email);
223 im_core::sessions::revoke_session(&server::app(cx).store, &token).await?;223 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;
225 }225 }
226 server::clear_session_cookie(cx);226 server::clear_session_cookie(cx);
227 see("/".to_string())227 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<()
53 let smtp = settings::smtp(store).await?;53 let smtp = settings::smtp(store).await?;
54 let message = lettre::Message::builder()54 let message = lettre::Message::builder()
55 .from(55 .from(
56- smtp.from56+ smtp.from_header()
57 .parse()57 .parse()
58 .map_err(|e| MailError::Backend(format!("smtp from: {e}")))?,58 .map_err(|e| MailError::Backend(format!("smtp from: {e}")))?,
59 )59 )
crates/im-web/src/main.rsmodified+13 -6
@@ -14,6 +14,7 @@ mod admin;
14 mod auth;14 mod auth;
15 mod config;15 mod config;
16 mod layout;16 mod layout;
17+mod live;
17 mod mailer;18 mod mailer;
18 mod oidc;19 mod oidc;
19 mod pages;20 mod pages;
@@ -204,19 +205,21 @@ async fn create_client(config: Config, name: &str, uris: &[String]) {
204 println!(" client_secret {}", secret.expose());205 println!(" client_secret {}", secret.expose());
205 println!(" (the secret is shown once; its digest is all the database keeps)");206 println!(" (the secret is shown once; its digest is all the database keeps)");
206 }207 }
207-
208 async fn serve(config: Config) {208 async fn serve(config: Config) {
209 for line in config.report() {209 for line in config.report() {
210 println!("im {line}");210 println!("im {line}");
211 }211 }
212 let store = open_store(&config).await;212 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);
213 let app = server::App {217 let app = server::App {
214 store,218 store,
215 config: config.clone(),219 config: config.clone(),
220+ live,
216 };221 };
217 222
218- // The bundle beside the executable is the only stylesheet this process
219- // can serve — `topcoat asset bundle -p im-web` produces it.
220 let bundle = topcoat::asset::AssetBundle::load().unwrap_or_else(|err| {223 let bundle = topcoat::asset::AssetBundle::load().unwrap_or_else(|err| {
221 eprintln!("im: the asset bundle beside the executable failed to load: {err}");224 eprintln!("im: the asset bundle beside the executable failed to load: {err}");
222 eprintln!("im: run `topcoat asset bundle -p im-web` first");225 eprintln!("im: run `topcoat asset bundle -p im-web` first");
@@ -228,6 +231,7 @@ async fn serve(config: Config) {
228 .cookies()231 .cookies()
229 .assets(bundle)232 .assets(bundle)
230 .app_context(app)233 .app_context(app)
234+ .app_context(live::Shutdown(stopping))
231 .build();235 .build();
232 236
233 // `topcoat::start` binds HOST/PORT from the environment; the listen237 // `topcoat::start` binds HOST/PORT from the environment; the listen
@@ -236,14 +240,15 @@ async fn serve(config: Config) {
236 let listener = tokio::net::TcpListener::bind(config.listen)240 let listener = tokio::net::TcpListener::bind(config.listen)
237 .await241 .await
238 .expect("failed to bind the listen address");242 .expect("failed to bind the listen address");
239- topcoat::serve_until(listener, router, shutdown_signal())243+ topcoat::serve_until(listener, router, shutdown_signal(stop))
240 .await244 .await
241 .expect("server error");245 .expect("server error");
242 }246 }
243 247
244 /// Resolves when the process is asked to stop: Ctrl+C, or `SIGTERM` from a248 /// Resolves when the process is asked to stop: Ctrl+C, or `SIGTERM` from a
245-/// service manager.249+/// service manager. The live streams hear it first, so the graceful shutdown
246-async fn shutdown_signal() {250+/// does not sit waiting on one long-lived connection per open tab.
251+async fn shutdown_signal(stop: tokio::sync::watch::Sender<bool>) {
247 let ctrl_c = async {252 let ctrl_c = async {
248 tokio::signal::ctrl_c()253 tokio::signal::ctrl_c()
249 .await254 .await
@@ -262,4 +267,6 @@ async fn shutdown_signal() {
262 () = ctrl_c => {},267 () = ctrl_c => {},
263 () = terminate => {},268 () = terminate => {},
264 }269 }
270+ // Streams end on their own; the browser reconnects when we are back.
271+ let _ = stop.send(true);
265 }272 }
crates/im-web/src/oidc.rsmodified+1 -2
@@ -302,8 +302,7 @@ async fn exchange(cx: &Cx, Form(input): Form<TokenForm>) -> Result<Response> {
302 &consumed.session_hash,302 &consumed.session_hash,
303 )303 )
304 .await?;304 .await?;
305- im_core::events::log(305+ server::log_event(cx,
306- &app(cx).store,
307 "code_exchanged",306 "code_exchanged",
308 Some(&user.email),307 Some(&user.email),
309 Some(&format!("via {}", client.name)),308 Some(&format!("via {}", client.name)),
crates/im-web/src/server.rsmodified+17 -0
@@ -26,6 +26,23 @@ pub const PENDING_MINUTES: i64 = 10;
26 pub struct App {26 pub struct App {
27 pub store: Arc<Store>,27 pub store: Arc<Store>,
28 pub config: Config,28 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);
29 }46 }
30 47
31 pub fn app(cx: &Cx) -> &App {48 pub fn app(cx: &Cx) -> &App {
style/main.scssmodified+34 -0
@@ -586,6 +586,40 @@ body:has(.admin-shell) {
586 &:hover { background: var(--danger-tint-alt); }586 &:hover { background: var(--danger-tint-alt); }
587 }587 }
588 588
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+
589 input[type="checkbox"] { accent-color: var(--accent); }623 input[type="checkbox"] { accent-color: var(--accent); }
590 624
591 @media (max-width: 720px) {625 @media (max-width: 720px) {