web: Keep pages current with Server-Sent Events #24

Merged
dev merged 1 commits from web-sse into main 2026-11-29 14:46:12 +00:00
13 changed files with 1801 additions and 106 deletions

No files matched your search

+1 -1
View File
@@ -142,7 +142,7 @@ What each request runs, and whose code, decides whether it needs an approval fir
| `src/bin/slop-broker.rs` | Daemon (`serve`); `slop-approve` when run under that name |
| `src/bin/slop.rs` | Agent client; `slop guide` prints `slop-tools.md` |
| `tests/broker.rs` | Handler tests over an in-memory duplex stream with a fake `ssh` |
| `src/web/` | The approvals web app: routes (`mod.rs`), OIDC sign-in and passkey confirmation (`auth.rs`), Web Push (`push.rs`), the audit log by request (`history.rs`), the pages (`page.rs`) and static assets |
| `src/web/` | The approvals web app: routes (`mod.rs`), each page's Server-Sent Events (`events.rs`), OIDC sign-in and passkey confirmation (`auth.rs`), Web Push (`push.rs`), the audit log by request (`history.rs`), the pages (`page.rs`) and static assets, among them the page script (`assets/app.js`) and idiomorph, vendored (`assets/idiomorph.js`) |
| `templates/`, `askama.toml` | The web app's HTML, as [askama](https://askama.rs) templates compiled into the broker; `askama.toml` passes everything they show through `ops::printable` before escaping it |
| `nix/` | The package, NixOS modules (`modules/nixos`), home-manager module (`modules/home-manager`), the VM test (`vm-test.nix`, `checks.<system>.vm`), clippy and rustfmt checks (`lints.nix`) and the demo's VMs and repository template (`demo/`, `packages.<system>.demo` and `demo-box`) |
| `devenv.nix` | The development environment, its scripts and the demo's host side (`devenv up`); `nix develop` gives a plainer shell from `flake.nix` without them |
+11 -1
View File
@@ -233,7 +233,17 @@ on a desktop shows what `slop-approve` can only print.
- Each request's page shows its full timeline, including the detail approvers saw, so a
notification for a request that's since been answered still leads somewhere useful.
- **Front end.** Server-rendered HTML that works without JavaScript.
- A small script refreshes the list and manages notifications, and a service worker shows them.
- A small script keeps the page current and manages notifications, and a service worker shows
them.
- **Live updates.** Each open page follows one stream of Server-Sent Events (`/events`).
- Each event carries a region of the page as HTML: a whole element with its `id`, such as the
pending list or a request, rendered by the same templates as the page. Agent-supplied text
is only ever escaped by them, never in the browser.
- The script morphs each region into the page with
[idiomorph](https://github.com/bigskysoftware/idiomorph) (vendored), so open details, the
focus and what's being typed stay.
- A region comes when the stream starts, so a page that lost its connection catches up when
the browser reconnects, and then when it changes. Signing out ends the stream.
- Everything shown passes through the same filter as `slop-approve` for control and
bidirectional characters.
- A strict content security policy allows only the app's own scripts.
-5
View File
@@ -279,11 +279,6 @@ impl Queue {
leases.sort();
leases
}
/// The current version of the pending set, which [`Queue::subscribe`] reports changes of.
pub fn version(&self) -> u64 {
self.state.lock().unwrap().sequence
}
}
fn info(id: &str, entry: &Entry, now: Instant) -> PendingInfo {
+43 -26
View File
@@ -18,36 +18,48 @@ function formatLeft(seconds) {
return `${seconds}s`;
}
setInterval(() => {
function showCountdowns() {
for (const element of document.querySelectorAll(".expires[data-until]")) {
const seconds = Math.max(0, Math.round((Number(element.dataset.until) - Date.now()) / 1000));
element.textContent = seconds > 0 ? `expires in ${formatLeft(seconds)}` : "expired";
}
}, 1000);
}
// Polls for changes to the pending set while the page is visible.
async function refresh() {
const pending = document.getElementById("pending");
setInterval(showCountdowns, 1000);
// Follows the broker's events for this page. Each `morph` event is a region of the page, a whole
// element with its `id`, which is morphed into the one here (with idiomorph) rather than replacing
// it, so open details, the focus and what's being typed stay.
function listen() {
const request = document.getElementById("request");
const container = pending || request;
if (!container || document.hidden) return;
if ((!document.getElementById("pending") && !request) || !("EventSource" in window)) return;
const response = await fetch("/api/version", { credentials: "same-origin" });
if (response.status === 401) return location.reload();
if (!response.ok) return;
const { version } = await response.json();
if (String(version) === container.dataset.version) return;
const path = request ? `/events?request=${encodeURIComponent(request.dataset.id)}` : "/events";
const source = new EventSource(path);
source.addEventListener("morph", (event) => {
const template = document.createElement("template");
template.innerHTML = event.data;
for (const region of template.content.children) {
const current = document.getElementById(region.id);
if (!current) continue;
Idiomorph.morph(current, region, { ignoreActiveValue: true, callbacks: { beforeAttributeUpdated: keepOpen } });
ready(document.getElementById(region.id));
}
});
// Signed out: reloading leads to signing in again.
source.addEventListener("signed-out", () => {
source.close();
location.reload();
});
// The browser reconnects by itself, unless the broker refused; then start again later.
source.addEventListener("error", () => {
if (source.readyState === EventSource.CLOSED) setTimeout(() => location.reload(), 30000);
});
}
if (request) return location.reload();
// Swap in the new list, keeping open details open.
const open = new Set([...pending.querySelectorAll("article details[open]")].map((d) => d.closest("article").id));
const fragment = await fetch("/pending", { credentials: "same-origin" });
if (!fragment.ok) return;
pending.innerHTML = await fragment.text();
pending.dataset.version = String(version);
for (const id of open) document.getElementById(id)?.querySelector("details")?.setAttribute("open", "");
startCountdowns(pending);
// Whether a details element stays open or closed is the approver's.
function keepOpen(attribute, element) {
return !(attribute === "open" && element.tagName === "DETAILS");
}
function base64urlToBytes(text) {
@@ -128,8 +140,13 @@ function localTimes(root) {
}
}
localTimes(document);
startCountdowns(document);
setInterval(() => refresh().catch(() => {}), 3000);
document.addEventListener("visibilitychange", () => refresh().catch(() => {}));
// What rendered times need, for the page or a region of it
function ready(root) {
localTimes(root);
startCountdowns(root);
showCountdowns();
}
ready(document);
listen();
setUpPush().catch(() => {});
File diff suppressed because it is too large. Load diff
+187
View File
@@ -0,0 +1,187 @@
//! Keeps open pages current with one stream of Server-Sent Events each.
//!
//! - Each `morph` event carries a region of the page: a whole element with its `id`, which the
//! page script morphs into the one it has, so open details and the focus stay. The main page's
//! region is the pending list (`#pending`), and a request's page's is the request (`#request`).
//! - A region comes when the stream starts, so a page catches up after reconnecting, and then
//! whenever it changes.
//! - `signed-out` ends the stream, when the approver signs out or the session expires.
use std::convert::Infallible;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, Instant};
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::response::{IntoResponse, Response};
use tokio::sync::watch;
use tower_sessions::Session;
use super::{User, page};
use crate::server::Broker;
/// How often a page gets updates at most.
const INTERVAL: Duration = Duration::from_secs(1);
/// The signed-in approver's CSRF token, or `None` once they've signed out.
type SignedIn = Box<dyn FnMut() -> Pin<Box<dyn Future<Output = Option<String>> + Send>> + Send>;
pub fn stream(broker: Arc<Broker>, session: Session, request: Option<String>) -> Response {
let signed_in: SignedIn = Box::new(move || {
let session = session.clone();
Box::pin(async move { session.get::<User>(super::USER).await.ok().flatten().map(|user| user.csrf) })
});
let updates = Updates::new(broker, signed_in, request);
let events = futures_util::stream::unfold(updates, |mut updates| async move {
let (name, data) = updates.next().await?;
Some((Ok::<_, Infallible>(Event::default().event(name).data(data)), updates))
});
let mut response = Sse::new(events).keep_alive(KeepAlive::default()).into_response();
// Proxies such as nginx would otherwise hold events back.
response.headers_mut().insert("x-accel-buffering", axum::http::HeaderValue::from_static("no"));
response
}
struct Updates {
broker: Arc<Broker>,
signed_in: SignedIn,
/// The request whose page it is, or none for the main page.
request: Option<String>,
queue: watch::Receiver<u64>,
/// The region last sent.
sent: Option<String>,
last: Option<Instant>,
ended: bool,
}
impl Updates {
fn new(broker: Arc<Broker>, signed_in: SignedIn, request: Option<String>) -> Updates {
let queue = broker.queue.subscribe();
Updates { broker, signed_in, request, queue, sent: None, last: None, ended: false }
}
/// The next event, as a name and data, once something changes; `None` ends the stream.
async fn next(&mut self) -> Option<(&'static str, String)> {
if self.ended {
return None;
}
loop {
// The region at first, then when it changes, at most once an interval
if let Some(last) = self.last {
self.queue.changed().await.ok()?;
tokio::time::sleep(INTERVAL.saturating_sub(last.elapsed())).await;
}
self.last = Some(Instant::now());
self.queue.borrow_and_update();
// Signing out, or the session expiring, ends it.
let Some(csrf) = (self.signed_in)().await else {
self.ended = true;
return Some(("signed-out", "signed out".into()));
};
let region = self.region(&csrf);
if self.sent.as_ref() != Some(&region) {
self.sent = Some(region.clone());
return Some(("morph", region));
}
}
}
fn region(&self, csrf: &str) -> String {
match &self.request {
None => page::pending(csrf, &self.broker.queue.list(), &self.broker.queue.all_leases()),
Some(id) => {
let entry = self.broker.queue.list().into_iter().find(|e| &e.id == id);
let past = super::past(&self.broker, id);
let view = page::RequestView { id, entry: entry.as_ref(), past: past.as_ref() };
page::request_region(csrf, &view)
}
}
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicBool, Ordering};
use super::*;
use crate::detail::Detail;
use crate::queue::NewRequest;
fn broker() -> Arc<Broker> {
let config = serde_json::from_value(serde_json::json!({
"requesters": {},
"policies": {},
"approve_socket": "/unused",
"approver_group": "root",
}))
.unwrap();
Arc::new(Broker::new(config).unwrap())
}
fn submit(broker: &Broker, id: &str) -> tokio::sync::oneshot::Receiver<crate::queue::Outcome> {
let request = NewRequest {
requester: "agent".into(),
op: "ssh".into(),
lease_key: "k".into(),
summary: "ssh river".into(),
detail: Detail::new(),
label: None,
sensitive: false,
passkey: false,
leases: vec![300],
};
broker.queue.submit(id, request, 4).unwrap()
}
#[tokio::test]
async fn the_main_page_gets_its_list_as_it_changes() {
let broker = broker();
let signed_out = Arc::new(AtomicBool::new(false));
let check = signed_out.clone();
let signed_in: SignedIn = Box::new(move || {
let out = check.load(Ordering::SeqCst);
Box::pin(async move { (!out).then(|| "token".to_owned()) })
});
let mut updates = Updates::new(broker.clone(), signed_in, None);
// The list to start with, as a whole element
let (name, data) = updates.next().await.unwrap();
assert_eq!(name, "morph");
assert!(data.starts_with(r#"<div id="pending">"#) && data.contains("Nothing is waiting"), "{data}");
// A new request, then its leaving
let _reply = submit(&broker, "abc");
let (_, data) = updates.next().await.unwrap();
assert!(data.contains("ssh river"), "{data}");
broker.queue.cancel("abc");
let (_, data) = updates.next().await.unwrap();
assert!(data.contains("Nothing is waiting"), "{data}");
signed_out.store(true, Ordering::SeqCst);
let _reply = submit(&broker, "def");
assert_eq!(updates.next().await.unwrap().0, "signed-out");
assert!(updates.next().await.is_none());
}
#[tokio::test]
async fn a_request_page_gets_its_request() {
let broker = broker();
let signed_in: SignedIn = Box::new(|| Box::pin(async { Some("token".to_owned()) }));
let mut updates = Updates::new(broker.clone(), signed_in, Some("abc".into()));
let (_, data) = updates.next().await.unwrap();
assert!(data.starts_with(r#"<div id="request" data-id="abc">"#), "{data}");
assert!(data.contains("The audit log has nothing"), "{data}");
// Other requests change nothing here, so nothing comes until this one does
let _other = submit(&broker, "xyz");
let _reply = submit(&broker, "abc");
let (_, data) = updates.next().await.unwrap();
assert!(data.contains("<h1>ssh river</h1>"), "{data}");
}
}
+30 -23
View File
@@ -2,6 +2,7 @@
//! for approvers signed in through an OpenID Connect provider, plus Web Push notifications. It
//! sits behind a reverse proxy, which is the only thing that should reach its listener.
mod auth;
mod events;
mod history;
mod page;
mod push;
@@ -81,10 +82,9 @@ pub async fn run(broker: Arc<Broker>, config: WebConfig, secret: String) -> Resu
let app = Router::new()
.route("/", get(index))
.route("/pending", get(pending_fragment))
.route("/requests/{id}", get(request_page).post(answer))
.route("/log", get(log_page))
.route("/api/version", get(version))
.route("/events", get(page_events))
.route("/api/csrf", get(csrf))
.route("/push/key", get(push_key))
.route("/push/subscribe", post(subscribe))
@@ -94,6 +94,7 @@ pub async fn run(broker: Arc<Broker>, config: WebConfig, secret: String) -> Resu
.route("/auth/logout", post(logout))
.route("/signed-out", get(signed_out))
.route("/app.js", get(|| async { page::asset("text/javascript", include_str!("assets/app.js")) }))
.route("/idiomorph.js", get(|| async { page::asset("text/javascript", include_str!("assets/idiomorph.js")) }))
.route("/sw.js", get(|| async { page::asset("text/javascript", include_str!("assets/sw.js")) }))
.route("/style.css", get(|| async { page::asset("text/css", include_str!("assets/style.css")) }))
.route("/icon.svg", get(|| async { page::asset("image/svg+xml", include_str!("assets/icon.svg")) }))
@@ -204,14 +205,7 @@ async fn index(State(web): State<Arc<Web>>, session: Session) -> Result<Response
let entries = web.broker.queue.list();
let leases = web.broker.queue.all_leases();
Ok(page::index(&user.name, &user.csrf, &entries, &leases, web.broker.queue.version()).into_response())
}
async fn pending_fragment(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
let user = api_user(&session).await?;
let entries = web.broker.queue.list();
let leases = web.broker.queue.all_leases();
Ok(page::pending(&user.csrf, &entries, &leases).into_response())
Ok(page::index(&user.name, &user.csrf, &entries, &leases).into_response())
}
async fn request_page(
@@ -223,14 +217,32 @@ async fn request_page(
Ok(user) => user,
Err(redirect) => return Ok(redirect),
};
// The log may be missing or unreadable; the request itself still shows.
let past = web.broker.audit.tail(LOG_RECORDS).ok().and_then(|records| {
let (histories, _) = history::gather(records);
histories.into_iter().find(|h| h.id == id)
});
let current = pending(&web, &id);
Ok(page::request(&user.name, &user.csrf, &id, current.as_ref(), past.as_ref(), web.broker.queue.version())
.into_response())
let (entry, past) = (pending(&web, &id), past(&web.broker, &id));
let view = page::RequestView { id: &id, entry: entry.as_ref(), past: past.as_ref() };
Ok(page::request(&user.name, &user.csrf, &view).into_response())
}
/// What the audit log has of a request. The log may be missing or unreadable; the request itself
/// still shows.
fn past(broker: &Broker, id: &str) -> Option<History> {
let records = broker.audit.tail(LOG_RECORDS).ok()?;
let (histories, _) = history::gather(records);
histories.into_iter().find(|h| h.id == id)
}
#[derive(Deserialize)]
struct EventsQuery {
request: Option<String>,
}
/// The page's stream of updates (see [`events`]): the main page's, or a request's.
async fn page_events(
State(web): State<Arc<Web>>,
session: Session,
Query(query): Query<EventsQuery>,
) -> Result<Response, Failure> {
api_user(&session).await?;
Ok(events::stream(web.broker.clone(), session, query.request))
}
#[derive(Deserialize)]
@@ -310,11 +322,6 @@ async fn log_page(
Ok(page::log(&user.name, &user.csrf, &view).into_response())
}
async fn version(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
api_user(&session).await?;
Ok(axum::Json(serde_json::json!({ "version": web.broker.queue.version() })).into_response())
}
async fn csrf(session: Session) -> Result<Response, Failure> {
let user = api_user(&session).await?;
Ok(axum::Json(serde_json::json!({ "csrf": user.csrf })).into_response())
+43 -32
View File
@@ -82,7 +82,7 @@ pub fn message(title: &str, text: &str) -> Html<String> {
render(Message { title, text })
}
/// The pending requests and leases, which the page script swaps in when they change.
/// The pending requests and leases: the main page's region that the page script keeps current.
#[derive(Template)]
#[template(path = "pending.html")]
struct Pending<'a> {
@@ -91,8 +91,8 @@ struct Pending<'a> {
leases: &'a [(String, String, u64)],
}
pub fn pending(csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> Html<String> {
render(Pending { csrf, entries, leases })
pub fn pending(csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> String {
render(Pending { csrf, entries, leases }).0
}
#[derive(Template)]
@@ -102,17 +102,27 @@ struct Index<'a> {
csrf: &'a str,
entries: &'a [PendingInfo],
leases: &'a [(String, String, u64)],
version: u64,
}
pub fn index(
name: &str,
csrf: &str,
entries: &[PendingInfo],
leases: &[(String, String, u64)],
version: u64,
) -> Html<String> {
render(Index { name, csrf, entries, leases, version })
pub fn index(name: &str, csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> Html<String> {
render(Index { name, csrf, entries, leases })
}
/// What a request's page shows: the request while it waits, and what the audit log has of it.
pub struct RequestView<'a> {
pub id: &'a str,
pub entry: Option<&'a PendingInfo>,
pub past: Option<&'a History>,
}
impl RequestView<'_> {
fn heading(&self) -> String {
match (self.entry, self.past) {
(Some(entry), _) => entry.summary.clone(),
(None, Some(past)) if !past.summary.is_empty() => past.summary.clone(),
_ => format!("Request {}", short(self.id)),
}
}
}
#[derive(Template)]
@@ -120,26 +130,23 @@ pub fn index(
struct Request<'a> {
name: &'a str,
csrf: &'a str,
heading: String,
entry: Option<&'a PendingInfo>,
past: Option<&'a History>,
version: u64,
view: &'a RequestView<'a>,
}
pub fn request(
name: &str,
csrf: &str,
id: &str,
entry: Option<&PendingInfo>,
past: Option<&History>,
version: u64,
) -> Html<String> {
let heading = match (entry, past) {
(Some(entry), _) => entry.summary.clone(),
(None, Some(past)) if !past.summary.is_empty() => past.summary.clone(),
_ => format!("Request {}", short(id)),
};
render(Request { name, csrf, heading, entry, past, version })
pub fn request(name: &str, csrf: &str, view: &RequestView) -> Html<String> {
render(Request { name, csrf, view })
}
/// A request's page without the rest: the region that the page script keeps current.
#[derive(Template)]
#[template(path = "request_region.html")]
struct RequestRegion<'a> {
csrf: &'a str,
view: &'a RequestView<'a>,
}
pub fn request_region(csrf: &str, view: &RequestView) -> String {
render(RequestRegion { csrf, view }).0
}
/// What the log page is filtered by.
@@ -256,7 +263,8 @@ mod tests {
offers: vec![Decision::Once, Decision::Lease(300), Decision::Deny],
expires_in: 125,
};
let html = pending("token", &[entry], &[]).0;
let html = pending("token", &[entry], &[]);
assert!(html.starts_with("<div id=\"pending\">") && html.trim_end().ends_with("</div>"), "{html}");
assert!(html.contains(r#"value="5m""#));
assert!(html.contains("For 5m"));
assert!(html.contains("ssh river &#60;x&#62;"));
@@ -296,7 +304,10 @@ mod tests {
];
let (histories, _) = super::history::gather(records);
let html = request("broker", "token", "abc", None, Some(&histories[0]), 0).0;
let view = RequestView { id: "abc", entry: None, past: Some(&histories[0]) };
let html = request("broker", "token", &view).0;
assert!(html.contains(r#"<div id="request" data-id="abc">"#), "{html}");
assert!(html.contains(request_region("token", &view).trim()), "{html}");
assert!(html.contains("<dt>Command</dt><dd class=\"neutral\"><code>uptime</code></dd>"), "{html}");
assert!(html.contains("<span class=\"diff-add\">+a</span>"), "{html}");
assert!(html.contains("Details (Text)") && html.contains("<pre>Old: text</pre>"), "{html}");
+1
View File
@@ -7,6 +7,7 @@
<link rel="stylesheet" href="/style.css">
<link rel="manifest" href="/manifest.webmanifest">
<link rel="icon" href="/icon.svg">
<script src="/idiomorph.js" defer></script>
<script src="/app.js" defer></script>
</head>
<body>
-2
View File
@@ -5,7 +5,5 @@
<section id="push" hidden>
<p><span id="push-state"></span> <button type="button" id="push-toggle" class="quiet"></button></p>
</section>
<div id="pending" data-version="{{ version }}">
{% include "pending.html" %}
</div>
{% endblock %}
+2
View File
@@ -1,4 +1,5 @@
{%- import "macros.html" as m -%}
<div id="pending">
{% if entries.is_empty() %}
<p class="empty">Nothing is waiting for an answer.</p>
{% endif %}
@@ -13,3 +14,4 @@
{% endfor %}
</tbody></table>
{% endif %}
</div>
+1 -16
View File
@@ -1,20 +1,5 @@
{% extends "base.html" %}
{% import "macros.html" as m %}
{% block title %}Approval request{% endblock %}
{% block main %}
<h1>{{ heading }}</h1>
<div id="request" data-version="{{ version }}">
{% if let Some(entry) = entry %}
{% call m::card(entry, csrf, true) %}{% endcall %}
{% endif %}
{% if let Some(past) = past %}
{% if entry.is_none() %}
<p class="meta">{{ past.requester }} · {{ past.op }} · {% call m::outcome(past.outcome) %}{% endcall %}</p>
{% endif %}
<h2>History</h2>
{% call m::timeline(past.records.as_slice()) %}{% endcall %}
{% else if entry.is_none() %}
<p class="empty">The audit log has nothing about this request.</p>
{% endif %}
</div>
{% include "request_region.html" %}
{% endblock %}
+16
View File
@@ -0,0 +1,16 @@
{%- import "macros.html" as m -%}
<div id="request" data-id="{{ view.id }}">
<h1>{{ view.heading() }}</h1>
{% if let Some(entry) = view.entry %}
{% call m::card(entry, csrf, true) %}{% endcall %}
{% endif %}
{% if let Some(past) = view.past %}
{% if view.entry.is_none() %}
<p class="meta">{{ past.requester }} · {{ past.op }} · {% call m::outcome(past.outcome) %}{% endcall %}</p>
{% endif %}
<h2>History</h2>
{% call m::timeline(past.records.as_slice()) %}{% endcall %}
{% else if view.entry.is_none() %}
<p class="empty">The audit log has nothing about this request.</p>
{% endif %}
</div>