| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | | use askama::Template; |
| 11 | | use axum::body::Bytes; |
| 12 | | use axum::extract::connect_info::ConnectInfo; |
| 13 | | use axum::extract::{Form, Path, Query, State}; |
| 14 | | use axum::http::{header, HeaderMap, HeaderValue, StatusCode}; |
| 15 | | use axum::response::sse::{Event as SseEvent, KeepAlive, Sse}; |
| 16 | | use axum::response::{Html, IntoResponse, Redirect, Response}; |
| 17 | | use axum::routing::{get, post}; |
| 18 | | use axum::Router; |
| 19 | | use futures::StreamExt; |
| 20 | | use serde::Deserialize; |
| 21 | | use spectra_core::conversation::{self as conv, Author, Post, Signer}; |
| 22 | | use spectra_core::event::{Auth, Method}; |
| 23 | | use spectra_core::ids::{format_time, now_ms}; |
| 24 | | use spectra_core::principals::{Principal, Principals}; |
| 25 | | use spectra_mcp::http::{AppState, PeerInfo}; |
| 26 | | use spectra_mcp::session::{self, Session}; |
| 27 | | use std::time::Duration; |
| 28 | |
|
| 29 | | const MARK: &str = include_str!("../assets/spectra.svg"); |
| 30 | | const STYLE: &str = include_str!("../assets/style.css"); |
| 31 | | const SCRIPT: &str = include_str!("../assets/radar.js"); |
| 32 | | const COOKIE: &str = "spectra_session"; |
| 33 | |
|
| 34 | | #[derive(Clone)] |
| 35 | | pub struct RadarState { |
| 36 | | pub app: AppState, |
| 37 | | } |
| 38 | |
|
| 39 | | impl RadarState { |
| 40 | 25× | fn sessions(&self) -> &session::Sessions { |
| 41 | 25× | &self.app.sessions |
| 42 | 25× | } |
| 43 | | } |
| 44 | |
|
| 45 | |
|
| 46 | 21× | pub fn router(app: AppState) -> Router { |
| 47 | 21× | let state = RadarState { app }; |
| 48 | 21× | Router::new() |
| 49 | 21× | .route("/", get(live)) |
| 50 | 21× | .route("/channels", get(channels)) |
| 51 | 21× | .route("/c/{name}", get(channel).post(post_channel)) |
| 52 | 21× | .route("/c/{name}/t/{id}", get(thread).post(post_thread)) |
| 53 | 21× | .route("/briefs", get(briefs).post(save_brief)) |
| 54 | 21× | .route("/constellation", get(constellation)) |
| 55 | 21× | .route("/radar/constellation.json", get(constellation_json)) |
| 56 | 21× | .route("/radar/constellation.js", get(|| async { asset("text/javascript; charset=utf-8", SKY_SCRIPT) })) |
| 57 | 21× | .route("/log", get(log)) |
| 58 | 21× | .route("/log/verify", post(verify)) |
| 59 | 21× | .route("/radar/link", post(link)) |
| 60 | 21× | .route("/signin", get(signin)) |
| 61 | 21× | .route("/signout", post(signout)) |
| 62 | 21× | .route("/radar/events", get(events)) |
| 63 | 21× | .route("/radar/style.css", get(|| async { asset("text/css; charset=utf-8", STYLE) })) |
| 64 | 21× | .route("/radar/radar.js", get(|| async { asset("text/javascript; charset=utf-8", SCRIPT) })) |
| 65 | 21× | .route("/radar/spectra.svg", get(|| async { asset("image/svg+xml", MARK) })) |
| 66 | 21× | .layer(axum::middleware::map_response(security_headers)) |
| 67 | 21× | .with_state(state) |
| 68 | 21× | } |
| 69 | |
|
| 70 | 0× | fn asset(kind: &'static str, body: &'static str) -> Response { |
| 71 | 0× | ([(header::CONTENT_TYPE, kind), (header::CACHE_CONTROL, "max-age=300")], body).into_response() |
| 72 | 0× | } |
| 73 | |
|
| 74 | |
|
| 75 | 30× | async fn security_headers(mut r: Response) -> Response { |
| 76 | 30× | let h = r.headers_mut(); |
| 77 | 30× | h.insert("content-security-policy", HeaderValue::from_static("default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; frame-ancestors 'none'; form-action 'self'; base-uri 'none'")); |
| 78 | 30× | h.insert("x-content-type-options", HeaderValue::from_static("nosniff")); |
| 79 | | |
| 80 | 30× | h.insert("referrer-policy", HeaderValue::from_static("same-origin")); |
| 81 | 30× | h.insert("x-frame-options", HeaderValue::from_static("DENY")); |
| 82 | 30× | r |
| 83 | 30× | } |
| 84 | |
|
| 85 | |
|
| 86 | | pub struct Shell { |
| 87 | | pub page: &'static str, |
| 88 | | pub owner: String, |
| 89 | | pub head: u64, |
| 90 | | pub version: &'static str, |
| 91 | | pub mark: &'static str, |
| 92 | | } |
| 93 | |
|
| 94 | |
|
| 95 | | struct Owner { |
| 96 | | session: Session, |
| 97 | | principal: Principal, |
| 98 | | shell: Shell, |
| 99 | | } |
| 100 | |
|
| 101 | | impl Owner { |
| 102 | 3× | fn author(&self) -> Author<'static> { |
| 103 | 3× | Author { |
| 104 | 3× | principal: self.principal.clone(), |
| 105 | 3× | signer: Signer::Request(Auth { |
| 106 | 3× | key: Some(self.session.key), |
| 107 | 3× | method: Method::Session, |
| 108 | 3× | assurance: 2, |
| 109 | 3× | proof: Some(self.session.proof.clone()), |
| 110 | 3× | }), |
| 111 | 3× | } |
| 112 | 3× | } |
| 113 | | } |
| 114 | |
|
| 115 | 25× | fn cookie(headers: &HeaderMap) -> Option<String> { |
| 116 | 25× | let c = headers.get(header::COOKIE)?.to_str().ok()?; |
| 117 | 20× | c.split(';').map(str::trim).find_map(|kv| kv.strip_prefix(&format!("{COOKIE}=")).map(String::from)) |
| 118 | 25× | } |
| 119 | |
|
| 120 | 25× | async fn owner(st: &RadarState, headers: &HeaderMap, page: &'static str) -> Result<Owner, Response> { |
| 121 | 25× | let now = now_ms(); |
| 122 | 25× | let session = cookie(headers) |
| 123 | 25× | .and_then(|id| st.sessions().get(&id, now)) |
| 124 | 25× | .ok_or_else(|| signin_page("Radar shows Spectra to its owner only.", StatusCode::UNAUTHORIZED))?; |
| 125 | 20× | let d = &st.app.daemon; |
| 126 | 20× | let principal = d |
| 127 | 20× | .principals |
| 128 | 20× | .read() |
| 129 | 20× | .await |
| 130 | 20× | .principal(&key_id(session.key), now) |
| 131 | 20× | .map_err(|why| signin_page(&format!("This session no longer belongs to the owner: {why}."), StatusCode::UNAUTHORIZED))?; |
| 132 | 20× | if !matches!(principal, Principal::Owner { .. }) { |
| 133 | 0× | return Err(signin_page("Radar shows Spectra to its owner only.", StatusCode::FORBIDDEN)); |
| 134 | 20× | } |
| 135 | 20× | let shell = Shell { page, owner: principal.display(), head: d.ledger.head().await.0, version: env!("CARGO_PKG_VERSION"), mark: MARK }; |
| 136 | 20× | Ok(Owner { session, principal, shell }) |
| 137 | 25× | } |
| 138 | |
|
| 139 | 20× | fn key_id(k: [u8; 32]) -> spectra_core::identity::KeyId { |
| 140 | 20× | spectra_core::identity::KeyId(k) |
| 141 | 20× | } |
| 142 | |
|
| 143 | | #[derive(Template)] |
| 144 | | #[template(path = "signin.html")] |
| 145 | | struct SigninPage<'a> { |
| 146 | | mark: &'static str, |
| 147 | | message: &'a str, |
| 148 | | } |
| 149 | |
|
| 150 | 6× | fn signin_page(message: &str, status: StatusCode) -> Response { |
| 151 | 6× | (status, render(&SigninPage { mark: MARK, message })).into_response() |
| 152 | 6× | } |
| 153 | |
|
| 154 | 18× | fn render<T: Template>(t: &T) -> Response { |
| 155 | 18× | match t.render() { |
| 156 | 18× | Ok(html) => Html(html).into_response(), |
| 157 | 0× | Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("could not render the page: {e}")).into_response(), |
| 158 | | } |
| 159 | 18× | } |
| 160 | |
|
| 161 | |
|
| 162 | |
|
| 163 | 7× | fn check_form(st: &RadarState, o: &Owner, headers: &HeaderMap, csrf: &str) -> Option<Response> { |
| 164 | 7× | if !spectra_mcp::http::origin_ok(headers, &st.app.origins) { |
| 165 | 1× | return Some((StatusCode::FORBIDDEN, "this origin may not change Spectra").into_response()); |
| 166 | 6× | } |
| 167 | 6× | if csrf != o.session.csrf { |
| 168 | 2× | return Some((StatusCode::FORBIDDEN, "the form is stale: reload the page").into_response()); |
| 169 | 4× | } |
| 170 | 4× | None |
| 171 | 7× | } |
| 172 | |
|
| 173 | |
|
| 174 | 4× | fn markdown(body: &str) -> String { |
| 175 | 4× | let mut html = String::new(); |
| 176 | 4× | pulldown_cmark::html::push_html( |
| 177 | 4× | &mut html, |
| 178 | 4× | pulldown_cmark::Parser::new_ext(body, pulldown_cmark::Options::ENABLE_STRIKETHROUGH | pulldown_cmark::Options::ENABLE_TABLES), |
| 179 | | ); |
| 180 | 4× | ammonia::clean(&html) |
| 181 | 4× | } |
| 182 | |
|
| 183 | |
|
| 184 | |
|
| 185 | | struct AgentCard { |
| 186 | | name: String, |
| 187 | | owner: String, |
| 188 | | kind: String, |
| 189 | | project: String, |
| 190 | | presence: String, |
| 191 | | status: Option<String>, |
| 192 | | last_tool: Option<String>, |
| 193 | | last_at: String, |
| 194 | | } |
| 195 | |
|
| 196 | | struct EventRow { |
| 197 | | seq: i64, |
| 198 | | at: String, |
| 199 | | kind: String, |
| 200 | | actor: String, |
| 201 | | subject: Option<String>, |
| 202 | | } |
| 203 | |
|
| 204 | | #[derive(Template)] |
| 205 | | #[template(path = "live.html")] |
| 206 | | struct LivePage { |
| 207 | | shell: Shell, |
| 208 | | agents: Vec<AgentCard>, |
| 209 | | unread: i64, |
| 210 | | events: Vec<EventRow>, |
| 211 | | } |
| 212 | |
|
| 213 | 3× | async fn live(State(st): State<RadarState>, headers: HeaderMap) -> Response { |
| 214 | 3× | let o = match owner(&st, &headers, "live").await { |
| 215 | 2× | Ok(o) => o, |
| 216 | 1× | Err(r) => return r, |
| 217 | | }; |
| 218 | 2× | let d = &st.app.daemon; |
| 219 | 2× | let pool = d.ledger.pool(); |
| 220 | 2× | let rows: Vec<(String, String, String, String, Option<String>)> = |
| 221 | 2× | sqlx::query_as("SELECT a.name, a.owner_name, a.kind, a.project, p.status_text FROM agents a LEFT JOIN presence p ON p.agent = a.name WHERE a.disabled_ms IS NULL ORDER BY a.name") |
| 222 | 2× | .fetch_all(pool) |
| 223 | 2× | .await |
| 224 | 2× | .unwrap_or_default(); |
| 225 | 2× | let mut agents = Vec::new(); |
| 226 | | { |
| 227 | 2× | let now = now_ms(); |
| 228 | 2× | for (name, owner, kind, project, status) in rows { |
| 229 | 1× | let last: Option<(String, i64)> = |
| 230 | 1× | sqlx::query_as("SELECT tool, at_ms FROM tool_calls WHERE agent = ? ORDER BY seq DESC LIMIT 1") |
| 231 | 1× | .bind(&name) |
| 232 | 1× | .fetch_optional(pool) |
| 233 | 1× | .await |
| 234 | 1× | .ok() |
| 235 | 1× | .flatten(); |
| 236 | 1× | let presence = d.presence.lock().await.state(&name, now).to_string(); |
| 237 | 1× | agents.push(AgentCard { |
| 238 | 1× | name, |
| 239 | 1× | owner, |
| 240 | 1× | kind, |
| 241 | 1× | project, |
| 242 | 1× | presence, |
| 243 | 1× | status, |
| 244 | 1× | last_tool: last.as_ref().map(|(t, _)| t.clone()), |
| 245 | 1× | last_at: last.map(|(_, at)| format_time(at as u64)).unwrap_or_default(), |
| 246 | | }); |
| 247 | | } |
| 248 | | } |
| 249 | 2× | let unread = conv::unread(&d.ledger, "human").await.unwrap_or(0); |
| 250 | 2× | let events = recent(&st, None, None, 50) |
| 251 | 2× | .await |
| 252 | 2× | .into_iter() |
| 253 | 24× | .map(|e| EventRow { seq: e.seq, at: e.at, kind: e.kind, actor: e.actor, subject: e.subject }) |
| 254 | 2× | .collect(); |
| 255 | 2× | render(&LivePage { shell: o.shell, agents, unread, events }) |
| 256 | 3× | } |
| 257 | |
|
| 258 | |
|
| 259 | |
|
| 260 | | struct ChannelRow { |
| 261 | | name: String, |
| 262 | | display: String, |
| 263 | | kind: String, |
| 264 | | purpose: String, |
| 265 | | count: i64, |
| 266 | | last: String, |
| 267 | | } |
| 268 | |
|
| 269 | |
|
| 270 | | type ChannelCount = (String, String, String, Option<String>, i64, Option<i64>); |
| 271 | |
|
| 272 | | #[derive(Template)] |
| 273 | | #[template(path = "channels.html")] |
| 274 | | struct ChannelsPage { |
| 275 | | shell: Shell, |
| 276 | | channels: Vec<ChannelRow>, |
| 277 | | } |
| 278 | |
|
| 279 | 2× | async fn channels(State(st): State<RadarState>, headers: HeaderMap) -> Response { |
| 280 | 2× | let o = match owner(&st, &headers, "channels").await { |
| 281 | 1× | Ok(o) => o, |
| 282 | 1× | Err(r) => return r, |
| 283 | | }; |
| 284 | 1× | let rows: Vec<ChannelCount> = sqlx::query_as( |
| 285 | 1× | "SELECT c.id, c.name, c.kind, c.purpose, (SELECT COUNT(*) FROM messages m WHERE m.channel = c.id), (SELECT MAX(at_ms) FROM messages m WHERE m.channel = c.id) \ |
| 286 | 1× | FROM channels c ORDER BY c.kind = 'direct', c.kind = 'system', c.name", |
| 287 | 1× | ) |
| 288 | 1× | .fetch_all(st.app.daemon.ledger.pool()) |
| 289 | 1× | .await |
| 290 | 1× | .unwrap_or_default(); |
| 291 | 1× | let channels = rows |
| 292 | 1× | .into_iter() |
| 293 | 1× | .map(|(_, name, kind, purpose, count, last)| ChannelRow { |
| 294 | 4× | display: match name.strip_prefix("dm:") { |
| 295 | 0× | Some(p) => format!("@{p}"), |
| 296 | 4× | None => format!("#{name}"), |
| 297 | | }, |
| 298 | 4× | name, |
| 299 | 4× | kind, |
| 300 | 4× | purpose: purpose.unwrap_or_default(), |
| 301 | 4× | count, |
| 302 | 4× | last: last.map(|t| format_time(t as u64)).unwrap_or_default(), |
| 303 | 4× | }) |
| 304 | 1× | .collect(); |
| 305 | 1× | render(&ChannelsPage { shell: o.shell, channels }) |
| 306 | 2× | } |
| 307 | |
|
| 308 | |
|
| 309 | |
|
| 310 | | const SKY_SCRIPT: &str = include_str!("../assets/constellation.js"); |
| 311 | |
|
| 312 | |
|
| 313 | 2× | async fn sky(st: &RadarState, owner: &str) -> serde_json::Value { |
| 314 | 2× | let d = &st.app.daemon; |
| 315 | 2× | let pool = d.ledger.pool(); |
| 316 | 2× | let projects: Vec<(String, String)> = |
| 317 | 2× | sqlx::query_as("SELECT name, description FROM projects ORDER BY seq").fetch_all(pool).await.unwrap_or_default(); |
| 318 | 2× | let links: Vec<(String, String)> = |
| 319 | 2× | sqlx::query_as("SELECT project, depends_on FROM project_relations").fetch_all(pool).await.unwrap_or_default(); |
| 320 | 2× | let agents: Vec<(String, String, String)> = |
| 321 | 2× | sqlx::query_as("SELECT name, kind, project FROM agents WHERE disabled_ms IS NULL ORDER BY name") |
| 322 | 2× | .fetch_all(pool) |
| 323 | 2× | .await |
| 324 | 2× | .unwrap_or_default(); |
| 325 | 2× | let presence = d.presence.lock().await; |
| 326 | 2× | let now = now_ms(); |
| 327 | 2× | let list: Vec<serde_json::Value> = projects |
| 328 | 2× | .iter() |
| 329 | 2× | .map(|(name, description)| { |
| 330 | 2× | serde_json::json!({ |
| 331 | 2× | "name": name, |
| 332 | 2× | "description": description, |
| 333 | 2× | "depends_on": links.iter().filter(|(p, _)| p == name).map(|(_, q)| q).collect::<Vec<_>>(), |
| 334 | 2× | "agents": agents.iter().filter(|(_, _, p)| p == name) |
| 335 | 2× | .map(|(a, kind, _)| serde_json::json!({ "name": a, "kind": kind, "presence": presence.state(a, now) })) |
| 336 | 2× | .collect::<Vec<_>>(), |
| 337 | | }) |
| 338 | 2× | }) |
| 339 | 2× | .collect(); |
| 340 | 2× | serde_json::json!({ "owner": owner, "projects": list }) |
| 341 | 2× | } |
| 342 | |
|
| 343 | 3× | fn esc(s: &str) -> String { |
| 344 | 3× | s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) |
| 345 | 3× | } |
| 346 | |
|
| 347 | | const HUES: [u32; 8] = [0, 30, 55, 120, 190, 230, 275, 320]; |
| 348 | |
|
| 349 | 1× | fn presence_colour(p: &str) -> &'static str { |
| 350 | 1× | match p { |
| 351 | 1× | "online" => "#3fb950", |
| 352 | 0× | "busy" => "#a371f7", |
| 353 | 0× | "idle" | "paused" => "#d29922", |
| 354 | 0× | "blocked" => "#f0883e", |
| 355 | 0× | _ => "#6e7681", |
| 356 | | } |
| 357 | 1× | } |
| 358 | |
|
| 359 | |
|
| 360 | 1× | fn still(sky: &serde_json::Value) -> String { |
| 361 | 1× | let (cx, cy, ring, orbit) = (450.0f64, 320.0f64, 205.0f64, 54.0f64); |
| 362 | 1× | let projects = sky["projects"].as_array().cloned().unwrap_or_default(); |
| 363 | 1× | let n = projects.len().max(1) as f64; |
| 364 | 1× | let mut at = std::collections::HashMap::new(); |
| 365 | 1× | let mut nodes = String::new(); |
| 366 | 1× | let mut lines = String::new(); |
| 367 | 1× | for (i, p) in projects.iter().enumerate() { |
| 368 | 1× | let a = -std::f64::consts::FRAC_PI_2 + std::f64::consts::TAU * i as f64 / n; |
| 369 | 1× | let (x, y) = (cx + ring * a.cos(), cy + ring * a.sin()); |
| 370 | 1× | let name = p["name"].as_str().unwrap_or(""); |
| 371 | 1× | at.insert(name.to_string(), (x, y)); |
| 372 | 1× | let hue = HUES[i % HUES.len()]; |
| 373 | 1× | lines.push_str(&format!(r#"<line class="spoke" x1="{cx}" y1="{cy}" x2="{x:.1}" y2="{y:.1}"/>"#)); |
| 374 | 1× | let s = 24.0; |
| 375 | 1× | nodes.push_str(&format!( |
| 376 | 1× | r#"<circle class="orbit" cx="{x:.1}" cy="{y:.1}" r="{orbit}"/><polygon class="prism" fill="hsl({hue},80%,60%)" points="{:.1},{:.1} {:.1},{:.1} {:.1},{:.1}"/><text class="plabel" x="{x:.1}" y="{:.1}">{}</text>"#, |
| 377 | 1× | x, |
| 378 | 1× | y - s, |
| 379 | 1× | x + s * 0.87, |
| 380 | 1× | y + s * 0.5, |
| 381 | 1× | x - s * 0.87, |
| 382 | 1× | y + s * 0.5, |
| 383 | 1× | y + orbit + 22.0, |
| 384 | 1× | esc(name) |
| 385 | 1× | )); |
| 386 | 1× | let agents = p["agents"].as_array().cloned().unwrap_or_default(); |
| 387 | 1× | for (j, ag) in agents.iter().enumerate() { |
| 388 | 1× | let b = std::f64::consts::TAU * j as f64 / agents.len().max(1) as f64; |
| 389 | 1× | let (ax, ay) = (x + orbit * b.cos(), y + orbit * b.sin()); |
| 390 | 1× | nodes.push_str(&format!( |
| 391 | 1× | r#"<circle class="agent" cx="{ax:.1}" cy="{ay:.1}" r="7" fill="{}"/><text class="alabel" x="{ax:.1}" y="{:.1}">{}</text>"#, |
| 392 | 1× | presence_colour(ag["presence"].as_str().unwrap_or("")), |
| 393 | 1× | ay + 18.0, |
| 394 | 1× | esc(ag["name"].as_str().unwrap_or("")) |
| 395 | 1× | )); |
| 396 | 1× | } |
| 397 | | } |
| 398 | 1× | for p in &projects { |
| 399 | 1× | let from = at.get(p["name"].as_str().unwrap_or("")); |
| 400 | 1× | for q in p["depends_on"].as_array().cloned().unwrap_or_default() { |
| 401 | 0× | if let (Some((x1, y1)), Some((x2, y2))) = (from, at.get(q.as_str().unwrap_or(""))) { |
| 402 | 0× | lines.push_str(&format!(r#"<path class="link" d="M{x1:.1},{y1:.1} Q{cx},{cy} {x2:.1},{y2:.1}"/>"#)); |
| 403 | 0× | } |
| 404 | | } |
| 405 | | } |
| 406 | 1× | format!( |
| 407 | | r#"{lines}<circle class="core" cx="{cx}" cy="{cy}" r="22"/><text class="olabel" x="{cx}" y="{:.1}">{}</text>{nodes}"#, |
| 408 | 1× | cy + 44.0, |
| 409 | 1× | esc(sky["owner"].as_str().unwrap_or("")) |
| 410 | | ) |
| 411 | 1× | } |
| 412 | |
|
| 413 | | #[derive(Template)] |
| 414 | | #[template(path = "constellation.html")] |
| 415 | | struct ConstellationPage { |
| 416 | | shell: Shell, |
| 417 | | still: String, |
| 418 | | data: String, |
| 419 | | empty: bool, |
| 420 | | } |
| 421 | |
|
| 422 | 1× | async fn constellation(State(st): State<RadarState>, headers: HeaderMap) -> Response { |
| 423 | 1× | let o = match owner(&st, &headers, "constellation").await { |
| 424 | 1× | Ok(o) => o, |
| 425 | 0× | Err(r) => return r, |
| 426 | | }; |
| 427 | 1× | let sky = sky(&st, &o.principal.display()).await; |
| 428 | 1× | let empty = sky["projects"].as_array().is_none_or(|a| a.is_empty()); |
| 429 | | |
| 430 | 1× | let data = sky.to_string().replace('<', "\\u003c"); |
| 431 | 1× | render(&ConstellationPage { shell: o.shell, still: still(&sky), data, empty }) |
| 432 | 1× | } |
| 433 | |
|
| 434 | 2× | async fn constellation_json(State(st): State<RadarState>, headers: HeaderMap) -> Response { |
| 435 | 2× | match owner(&st, &headers, "constellation").await { |
| 436 | 1× | Ok(o) => axum::Json(sky(&st, &o.principal.display()).await).into_response(), |
| 437 | 1× | Err(r) => r, |
| 438 | | } |
| 439 | 2× | } |
| 440 | |
|
| 441 | |
|
| 442 | |
|
| 443 | | struct ProjectBriefRow { |
| 444 | | name: String, |
| 445 | | description: String, |
| 446 | | text: String, |
| 447 | | } |
| 448 | |
|
| 449 | | #[derive(Template)] |
| 450 | | #[template(path = "briefs.html")] |
| 451 | | struct BriefsPage { |
| 452 | | shell: Shell, |
| 453 | | csrf: String, |
| 454 | | overall: String, |
| 455 | | projects: Vec<ProjectBriefRow>, |
| 456 | | } |
| 457 | |
|
| 458 | 2× | async fn briefs(State(st): State<RadarState>, headers: HeaderMap) -> Response { |
| 459 | 2× | let o = match owner(&st, &headers, "briefs").await { |
| 460 | 2× | Ok(o) => o, |
| 461 | 0× | Err(r) => return r, |
| 462 | | }; |
| 463 | 2× | let pool = st.app.daemon.ledger.pool(); |
| 464 | 2× | let overall = spectra_core::rules::layer(pool, None).await.ok().flatten().unwrap_or_default(); |
| 465 | 2× | let rows: Vec<(String, String, Option<String>)> = sqlx::query_as( |
| 466 | 2× | "SELECT p.name, p.description, b.text FROM projects p LEFT JOIN briefs b ON b.layer = 'project' AND b.project = p.name ORDER BY p.name", |
| 467 | 2× | ) |
| 468 | 2× | .fetch_all(pool) |
| 469 | 2× | .await |
| 470 | 2× | .unwrap_or_default(); |
| 471 | 2× | let projects = |
| 472 | 2× | rows.into_iter().map(|(name, description, text)| ProjectBriefRow { name, description, text: text.unwrap_or_default() }).collect(); |
| 473 | 2× | let csrf = o.session.csrf.clone(); |
| 474 | 2× | render(&BriefsPage { shell: o.shell, csrf, overall, projects }) |
| 475 | 2× | } |
| 476 | |
|
| 477 | | #[derive(Deserialize)] |
| 478 | | struct BriefForm { |
| 479 | | _csrf: String, |
| 480 | | project: Option<String>, |
| 481 | | text: String, |
| 482 | | } |
| 483 | |
|
| 484 | 2× | async fn save_brief(State(st): State<RadarState>, headers: HeaderMap, Form(f): Form<BriefForm>) -> Response { |
| 485 | 2× | let o = match owner(&st, &headers, "briefs").await { |
| 486 | 2× | Ok(o) => o, |
| 487 | 0× | Err(r) => return r, |
| 488 | | }; |
| 489 | 2× | if let Some(r) = check_form(&st, &o, &headers, &f._csrf) { |
| 490 | 1× | return r; |
| 491 | 1× | } |
| 492 | | |
| 493 | 1× | let text = f.text.replace("\r\n", "\n"); |
| 494 | 1× | if let Err(e) = spectra_core::rules::check(&text) { |
| 495 | 0× | return (StatusCode::BAD_REQUEST, format!("{e:#}")).into_response(); |
| 496 | 1× | } |
| 497 | 1× | let project = f.project.filter(|p| !p.is_empty()); |
| 498 | 1× | let pool = st.app.daemon.ledger.pool(); |
| 499 | 1× | if let Some(p) = &project { |
| 500 | 1× | let known: Option<String> = |
| 501 | 1× | sqlx::query_scalar("SELECT name FROM projects WHERE name = ?").bind(p).fetch_optional(pool).await.unwrap_or(None); |
| 502 | 1× | if known.is_none() { |
| 503 | 0× | return (StatusCode::NOT_FOUND, "no such project").into_response(); |
| 504 | 1× | } |
| 505 | 0× | } |
| 506 | 1× | let Signer::Request(auth) = o.author().signer else { return StatusCode::INTERNAL_SERVER_ERROR.into_response() }; |
| 507 | 1× | let mut e = |
| 508 | 1× | spectra_core::event::NewEvent::system("brief.set", serde_json::json!({ "project": project, "text": text })).by("human", auth); |
| 509 | 1× | e.project = project.clone(); |
| 510 | 1× | match st.app.daemon.ledger.append_one(e).await { |
| 511 | | Ok(_) => { |
| 512 | 1× | Redirect::to(&format!("/briefs#{}", project.map(|p| format!("p-{p}")).unwrap_or_else(|| "overall".into()))).into_response() |
| 513 | | } |
| 514 | 0× | Err(e) => (StatusCode::BAD_REQUEST, format!("{e:#}")).into_response(), |
| 515 | | } |
| 516 | 2× | } |
| 517 | |
|
| 518 | |
|
| 519 | |
|
| 520 | | struct MessageRow { |
| 521 | | id: String, |
| 522 | | author: String, |
| 523 | | at: String, |
| 524 | | kind: String, |
| 525 | | replies: i64, |
| 526 | | redacted: bool, |
| 527 | | body_html: String, |
| 528 | | } |
| 529 | |
|
| 530 | | #[derive(Template)] |
| 531 | | #[template(path = "channel.html")] |
| 532 | | struct ChannelPage { |
| 533 | | shell: Shell, |
| 534 | | name: String, |
| 535 | | display: String, |
| 536 | | purpose: Option<String>, |
| 537 | | brief: Option<String>, |
| 538 | | thread: Option<String>, |
| 539 | | messages: Vec<MessageRow>, |
| 540 | | can_post: bool, |
| 541 | | action: String, |
| 542 | | csrf: String, |
| 543 | | } |
| 544 | |
|
| 545 | 4× | async fn show(st: &RadarState, o: Owner, name: &str, thread: Option<&str>) -> Response { |
| 546 | 4× | let d = &st.app.daemon; |
| 547 | 4× | let (ch, msgs) = match conv::read(&d.ledger, &o.principal, if thread.is_some() { None } else { Some(name) }, thread, None, 200).await { |
| 548 | 4× | Ok(r) => r, |
| 549 | 0× | Err(e) => return (StatusCode::NOT_FOUND, format!("{e:#}")).into_response(), |
| 550 | | }; |
| 551 | 4× | let mut messages = Vec::new(); |
| 552 | 4× | for m in msgs { |
| 553 | 3× | messages.push(MessageRow { |
| 554 | 3× | author: spectra_core::conversation::display_name(&d.ledger, &m.author).await, |
| 555 | 3× | at: format_time(m.at_ms as u64), |
| 556 | 3× | redacted: m.redacted.is_some(), |
| 557 | 3× | body_html: if m.redacted.is_some() { ammonia::clean_text(&m.body) } else { markdown(&m.body) }, |
| 558 | 3× | id: m.id, |
| 559 | 3× | kind: m.kind, |
| 560 | 3× | replies: m.replies, |
| 561 | | }); |
| 562 | | } |
| 563 | 4× | let can_post = conv::can_post(&o.principal, &ch).is_ok(); |
| 564 | 4× | let action = match thread { |
| 565 | 0× | Some(t) => format!("/c/{}/t/{t}", ch.name), |
| 566 | 4× | None => format!("/c/{}", ch.name), |
| 567 | | }; |
| 568 | 4× | let csrf = o.session.csrf.clone(); |
| 569 | 4× | let brief = if ch.kind == "project" { spectra_core::rules::layer(d.ledger.pool(), Some(&ch.name)).await.ok().flatten() } else { None }; |
| 570 | 4× | let brief = brief.map(|b| markdown(&b)); |
| 571 | 4× | render(&ChannelPage { |
| 572 | 4× | shell: o.shell, |
| 573 | 4× | name: ch.name.clone(), |
| 574 | 4× | display: ch.display(), |
| 575 | 4× | purpose: ch.purpose.clone(), |
| 576 | 4× | brief, |
| 577 | 4× | thread: thread.map(String::from), |
| 578 | 4× | messages, |
| 579 | 4× | can_post, |
| 580 | 4× | action, |
| 581 | 4× | csrf, |
| 582 | 4× | }) |
| 583 | 4× | } |
| 584 | |
|
| 585 | 5× | async fn channel(State(st): State<RadarState>, headers: HeaderMap, Path(name): Path<String>) -> Response { |
| 586 | 5× | match owner(&st, &headers, "channels").await { |
| 587 | 4× | Ok(o) => show(&st, o, &name, None).await, |
| 588 | 1× | Err(r) => r, |
| 589 | | } |
| 590 | 5× | } |
| 591 | |
|
| 592 | 0× | async fn thread(State(st): State<RadarState>, headers: HeaderMap, Path((name, id)): Path<(String, String)>) -> Response { |
| 593 | 0× | match owner(&st, &headers, "channels").await { |
| 594 | 0× | Ok(o) => show(&st, o, &name, Some(&id)).await, |
| 595 | 0× | Err(r) => r, |
| 596 | | } |
| 597 | 0× | } |
| 598 | |
|
| 599 | | #[derive(Deserialize)] |
| 600 | | struct PostForm { |
| 601 | | _csrf: String, |
| 602 | | body: String, |
| 603 | | reply_to: Option<String>, |
| 604 | | } |
| 605 | |
|
| 606 | 4× | async fn post_to(st: &RadarState, headers: &HeaderMap, name: &str, form: PostForm, back: String) -> Response { |
| 607 | 4× | let o = match owner(st, headers, "channels").await { |
| 608 | 4× | Ok(o) => o, |
| 609 | 0× | Err(r) => return r, |
| 610 | | }; |
| 611 | 4× | if let Some(r) = check_form(st, &o, headers, &form._csrf) { |
| 612 | 2× | return r; |
| 613 | 2× | } |
| 614 | 2× | let post = Post { |
| 615 | 2× | channel: if form.reply_to.is_some() { None } else { Some(name.to_string()) }, |
| 616 | 2× | body: form.body, |
| 617 | 2× | reply_to: form.reply_to, |
| 618 | 2× | ..Default::default() |
| 619 | | }; |
| 620 | 2× | match conv::post(&st.app.daemon.ledger, &o.author(), post, now_ms()).await { |
| 621 | 2× | Ok(_) => Redirect::to(&back).into_response(), |
| 622 | 0× | Err(e) => (StatusCode::BAD_REQUEST, format!("{e:#}")).into_response(), |
| 623 | | } |
| 624 | 4× | } |
| 625 | |
|
| 626 | 4× | async fn post_channel(State(st): State<RadarState>, headers: HeaderMap, Path(name): Path<String>, Form(form): Form<PostForm>) -> Response { |
| 627 | 4× | let back = format!("/c/{name}"); |
| 628 | 4× | post_to(&st, &headers, &name, form, back).await |
| 629 | 4× | } |
| 630 | |
|
| 631 | 0× | async fn post_thread( |
| 632 | 0× | State(st): State<RadarState>, |
| 633 | 0× | headers: HeaderMap, |
| 634 | 0× | Path((name, id)): Path<(String, String)>, |
| 635 | 0× | Form(mut form): Form<PostForm>, |
| 636 | 0× | ) -> Response { |
| 637 | 0× | form.reply_to = Some(id.clone()); |
| 638 | 0× | let back = format!("/c/{name}/t/{id}"); |
| 639 | 0× | post_to(&st, &headers, &name, form, back).await |
| 640 | 0× | } |
| 641 | |
|
| 642 | |
|
| 643 | |
|
| 644 | | struct LogRow { |
| 645 | | seq: i64, |
| 646 | | id: String, |
| 647 | | at: String, |
| 648 | | kind: String, |
| 649 | | actor: String, |
| 650 | | subject: Option<String>, |
| 651 | | method: String, |
| 652 | | assurance: i64, |
| 653 | | hash: String, |
| 654 | | prev: String, |
| 655 | | key: String, |
| 656 | | proof: String, |
| 657 | | payload: String, |
| 658 | | } |
| 659 | |
|
| 660 | 4× | async fn recent(st: &RadarState, kind: Option<&str>, before: Option<i64>, limit: i64) -> Vec<LogRow> { |
| 661 | | #[allow(clippy::type_complexity)] |
| 662 | 4× | let rows: Vec<( |
| 663 | 4× | i64, |
| 664 | 4× | String, |
| 665 | 4× | i64, |
| 666 | 4× | String, |
| 667 | 4× | String, |
| 668 | 4× | Option<String>, |
| 669 | 4× | i64, |
| 670 | 4× | i64, |
| 671 | 4× | Vec<u8>, |
| 672 | 4× | Vec<u8>, |
| 673 | 4× | Option<Vec<u8>>, |
| 674 | 4× | Option<Vec<u8>>, |
| 675 | 4× | Option<Vec<u8>>, |
| 676 | 4× | )> = sqlx::query_as( |
| 677 | 4× | "SELECT seq, id, at_ms, kind, actor, subject, auth_method, auth_assurance, hash, prev, auth_key, auth_proof, payload FROM events \ |
| 678 | 4× | WHERE (? IS NULL OR kind = ?) AND (? IS NULL OR seq < ?) ORDER BY seq DESC LIMIT ?", |
| 679 | 4× | ) |
| 680 | 4× | .bind(kind) |
| 681 | 4× | .bind(kind) |
| 682 | 4× | .bind(before) |
| 683 | 4× | .bind(before) |
| 684 | 4× | .bind(limit) |
| 685 | 4× | .fetch_all(st.app.daemon.ledger.pool()) |
| 686 | 4× | .await |
| 687 | 4× | .unwrap_or_default(); |
| 688 | 4× | let mut out = Vec::new(); |
| 689 | 59× | for (seq, id, at, kind, actor, subject, method, assurance, hash, prev, key, proof, payload) in rows { |
| 690 | 59× | let payload = payload |
| 691 | 59× | .and_then(|p| serde_json::from_slice::<serde_json::Value>(&p).ok()) |
| 692 | 59× | .map(|v| serde_json::to_string_pretty(&v).unwrap_or_default()) |
| 693 | 59× | .unwrap_or_else(|| "(pruned to its stub)".into()); |
| 694 | 59× | out.push(LogRow { |
| 695 | 59× | seq, |
| 696 | 59× | id, |
| 697 | 59× | at: format_time(at as u64), |
| 698 | 59× | kind, |
| 699 | 59× | actor: spectra_core::conversation::display_name(&st.app.daemon.ledger, &actor).await, |
| 700 | 59× | subject, |
| 701 | 59× | method: Method::from_u8(method as u8).map(|m| m.name()).unwrap_or("?").to_string(), |
| 702 | 59× | assurance, |
| 703 | 59× | hash: hex::encode(hash), |
| 704 | 59× | prev: hex::encode(prev), |
| 705 | 59× | key: key.map(hex::encode).unwrap_or_else(|| "none (Spectra itself; covered by the next checkpoint)".into()), |
| 706 | 59× | proof: proof.map(|p| format!("{} bytes", p.len())).unwrap_or_else(|| "none".into()), |
| 707 | 59× | payload, |
| 708 | | }); |
| 709 | | } |
| 710 | 4× | out |
| 711 | 4× | } |
| 712 | |
|
| 713 | | #[derive(Template)] |
| 714 | | #[template(path = "log.html")] |
| 715 | | struct LogPage { |
| 716 | | shell: Shell, |
| 717 | | head_hash: String, |
| 718 | | verified: String, |
| 719 | | csrf: String, |
| 720 | | kinds: Vec<String>, |
| 721 | | kind: String, |
| 722 | | events: Vec<LogRow>, |
| 723 | | older: Option<i64>, |
| 724 | | } |
| 725 | |
|
| 726 | | #[derive(Deserialize)] |
| 727 | | struct LogQuery { |
| 728 | | kind: Option<String>, |
| 729 | | before: Option<i64>, |
| 730 | | around: Option<i64>, |
| 731 | | } |
| 732 | |
|
| 733 | 3× | async fn log(State(st): State<RadarState>, headers: HeaderMap, Query(q): Query<LogQuery>) -> Response { |
| 734 | 3× | let o = match owner(&st, &headers, "log").await { |
| 735 | 2× | Ok(o) => o, |
| 736 | 1× | Err(r) => return r, |
| 737 | | }; |
| 738 | 2× | let d = &st.app.daemon; |
| 739 | 2× | let (_, head) = d.ledger.head().await; |
| 740 | 2× | let last: Option<(Vec<u8>, i64)> = |
| 741 | 2× | sqlx::query_as("SELECT payload, at_ms FROM events WHERE kind = 'ledger.verified' ORDER BY seq DESC LIMIT 1") |
| 742 | 2× | .fetch_optional(d.ledger.pool()) |
| 743 | 2× | .await |
| 744 | 2× | .ok() |
| 745 | 2× | .flatten(); |
| 746 | 2× | let verified = match last { |
| 747 | 1× | Some((p, at)) => { |
| 748 | 1× | let v: serde_json::Value = serde_json::from_slice(&p).unwrap_or_default(); |
| 749 | 1× | let n = v["findings"].as_u64().unwrap_or(0); |
| 750 | 1× | format!( |
| 751 | | "{} at {} over {} events", |
| 752 | 1× | if n == 0 { "clean".to_string() } else { format!("{n} finding(s)") }, |
| 753 | 1× | format_time(at as u64), |
| 754 | 1× | v["events"].as_u64().unwrap_or(0) |
| 755 | | ) |
| 756 | | } |
| 757 | 1× | None => "not yet".into(), |
| 758 | | }; |
| 759 | 2× | let kinds: Vec<String> = |
| 760 | 2× | sqlx::query_scalar("SELECT kind FROM event_counts ORDER BY n DESC LIMIT 12").fetch_all(d.ledger.pool()).await.unwrap_or_default(); |
| 761 | 2× | let kind = q.kind.unwrap_or_default(); |
| 762 | 2× | let before = q.before.or(q.around.map(|a| a + 25)); |
| 763 | 2× | let events = recent(&st, (!kind.is_empty()).then_some(kind.as_str()), before, 100).await; |
| 764 | 2× | let older = (events.len() == 100).then(|| events.last().map(|e| e.seq)).flatten(); |
| 765 | 2× | let csrf = o.session.csrf.clone(); |
| 766 | 2× | render(&LogPage { shell: o.shell, head_hash: hex::encode(head), verified, csrf, kinds, kind, events, older }) |
| 767 | 3× | } |
| 768 | |
|
| 769 | | #[derive(Deserialize)] |
| 770 | | struct CsrfForm { |
| 771 | | _csrf: String, |
| 772 | | } |
| 773 | |
|
| 774 | |
|
| 775 | 1× | async fn verify(State(st): State<RadarState>, headers: HeaderMap, Form(f): Form<CsrfForm>) -> Response { |
| 776 | 1× | let o = match owner(&st, &headers, "log").await { |
| 777 | 1× | Ok(o) => o, |
| 778 | 0× | Err(r) => return r, |
| 779 | | }; |
| 780 | 1× | if let Some(r) = check_form(&st, &o, &headers, &f._csrf) { |
| 781 | 0× | return r; |
| 782 | 1× | } |
| 783 | 1× | let ledger = &st.app.daemon.ledger; |
| 784 | 1× | match ledger.verify(&mut Principals::default()).await { |
| 785 | 1× | Ok(v) => { |
| 786 | 1× | let e = spectra_core::event::NewEvent::system( |
| 787 | 1× | "ledger.verified", |
| 788 | 1× | serde_json::json!({ "events": v.events, "checkpoints": v.checkpoints, "findings": v.findings.len(), "head": hex::encode(v.head), "first": v.findings.first().map(|f| format!("#{}: {}", f.seq, f.detail)) }), |
| 789 | | ); |
| 790 | 1× | let _ = ledger.append_one(e).await; |
| 791 | 1× | Redirect::to("/log").into_response() |
| 792 | | } |
| 793 | 0× | Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:#}")).into_response(), |
| 794 | | } |
| 795 | 1× | } |
| 796 | |
|
| 797 | |
|
| 798 | |
|
| 799 | |
|
| 800 | 2× | async fn link(State(st): State<RadarState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, body: Bytes) -> Response { |
| 801 | 2× | let caller = match spectra_mcp::http::authenticate(&st.app, peer, &headers, "POST /radar/link", &body).await { |
| 802 | 2× | Ok(c) => c, |
| 803 | 0× | Err(r) => return r, |
| 804 | | }; |
| 805 | 2× | if !matches!(caller.principal, Principal::Owner { .. }) { |
| 806 | 0× | return (StatusCode::FORBIDDEN, axum::Json(serde_json::json!({ "title": "only the owner signs in to Radar" }))).into_response(); |
| 807 | 2× | } |
| 808 | 2× | let (Some(key), Some(proof)) = (caller.auth.key, caller.auth.proof) else { |
| 809 | 0× | return StatusCode::UNAUTHORIZED.into_response(); |
| 810 | | }; |
| 811 | 2× | let code = st.sessions().link(key, proof, now_ms()); |
| 812 | 2× | let base = st.app.origins.first().cloned().unwrap_or_default(); |
| 813 | 2× | axum::Json(serde_json::json!({ "url": format!("{base}/signin?code={code}"), "valid_ms": session::LINK_MS })).into_response() |
| 814 | 2× | } |
| 815 | |
|
| 816 | | #[derive(Deserialize)] |
| 817 | | struct SigninQuery { |
| 818 | | code: Option<String>, |
| 819 | | |
| 820 | | next: Option<String>, |
| 821 | | } |
| 822 | |
|
| 823 | |
|
| 824 | 2× | fn landing(next: Option<&str>) -> &'static str { |
| 825 | 2× | match next.unwrap_or("") { |
| 826 | 2× | "constellation" | "/constellation" => "/constellation", |
| 827 | 2× | "briefs" | "/briefs" => "/briefs", |
| 828 | 2× | "channels" | "/channels" => "/channels", |
| 829 | 2× | "log" | "/log" => "/log", |
| 830 | 2× | _ => "/", |
| 831 | | } |
| 832 | 2× | } |
| 833 | |
|
| 834 | 3× | async fn signin(State(st): State<RadarState>, Query(q): Query<SigninQuery>) -> Response { |
| 835 | 3× | let Some(id) = q.code.and_then(|c| st.sessions().open(&c, now_ms())) else { |
| 836 | 1× | return signin_page("That sign-in link has been used or has expired.", StatusCode::UNAUTHORIZED); |
| 837 | | }; |
| 838 | 2× | let cookie = format!("{COOKIE}={id}; HttpOnly; SameSite=Strict; Path=/; Max-Age={}", session::SESSION_MS / 1000); |
| 839 | 2× | let mut r = Redirect::to(landing(q.next.as_deref())).into_response(); |
| 840 | 2× | r.headers_mut().insert(header::SET_COOKIE, HeaderValue::from_str(&cookie).unwrap()); |
| 841 | 2× | r |
| 842 | 3× | } |
| 843 | |
|
| 844 | 0× | async fn signout(State(st): State<RadarState>, headers: HeaderMap, Form(f): Form<CsrfForm>) -> Response { |
| 845 | 0× | if let Ok(o) = owner(&st, &headers, "live").await { |
| 846 | 0× | if check_form(&st, &o, &headers, &f._csrf).is_none() { |
| 847 | 0× | if let Some(id) = cookie(&headers) { |
| 848 | 0× | st.sessions().close(&id); |
| 849 | 0× | } |
| 850 | 0× | } |
| 851 | 0× | } |
| 852 | 0× | signin_page("Signed out.", StatusCode::OK) |
| 853 | 0× | } |
| 854 | |
|
| 855 | |
|
| 856 | |
|
| 857 | |
|
| 858 | |
|
| 859 | 0× | async fn events(State(st): State<RadarState>, headers: HeaderMap) -> Response { |
| 860 | 0× | if let Err(r) = owner(&st, &headers, "live").await { |
| 861 | 0× | return r; |
| 862 | 0× | } |
| 863 | 0× | let rx = st.app.daemon.ledger.subscribe(); |
| 864 | 0× | let stream = tokio_stream::wrappers::BroadcastStream::new(rx).filter_map(|e| async move { |
| 865 | 0× | let e = e.ok()?; |
| 866 | 0× | let data = serde_json::json!({ "seq": e.seq, "kind": e.kind, "actor": e.actor, "subject": e.subject, "project": e.project }); |
| 867 | 0× | Some(Ok::<_, std::convert::Infallible>(SseEvent::default().data(data.to_string()))) |
| 868 | 0× | }); |
| 869 | 0× | Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))).into_response() |
| 870 | 0× | } |