haematite-cli 0.21.8

The haematite command: serve a store, its door and Studio, answer MCP, query with jq, and host the store's assistant seat
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! What the door answers for one request (ACCESS-002 R2).
//!
//! - `/signin` sends the browser to Lys with a short-lived Lax cookie
//!   binding the state to it.
//! - `/callback` finishes the sign-in and sets a Strict session cookie
//!   holding only an opaque id.
//! - `POST /signout` forgets the session and clears its cookie.
//! - `/api/session` answers Settings' Lys line, and `/api/haem` the stores
//!   this door serves, as `{"stores": [{"name": …}]}`: the shape Studio reads.
//! - `POST /api/haem/<store>` carries one verb with the session's pass.
//! - `GET /api/haem/<store>/follow?branch=<name>` follows a branch's head
//!   as Server-Sent Events, pushed by the store as the head moves.
//! - Any other address is one of Studio's files or the app itself: gzipped
//!   when the browser takes gzip, and kept by it for good when its name
//!   carries Vite's content hash (door/packed.rs).
//!
//! Every /api answer needs a session. A verb and a sign-out must come from
//! Studio's own origin; a follow sent with an Origin must name Studio's.

//! Assistant routes are dispatched by `assistant`; static assets by `files`.
//! Store child state and store receipts are handled by `children` and `responses`.

use std::collections::BTreeMap;
use std::io::{self, Write};
use std::path::PathBuf;
use std::sync::{Arc, atomic::AtomicBool};
use std::time::Duration;

use serde::Deserialize;
use serde_json::value::RawValue;
use serde_json::{Value, json};

use super::forward::{Carried, Followed, Following, carry, follow};
use super::http::{Request, Response};
use super::packed::Packed;
#[path = "route_files.rs"]
mod files;
use files::file;
#[path = "route_children.rs"]
mod children;
pub(super) use children::child_given_up;
#[path = "route_responses.rs"]
mod responses;
use super::signin::{Door, Issuer};
use crate::client::{Ended, Reply};
use crate::serve::storage::Failure;
pub(super) use responses::refusal;
use responses::{Receipted, refused_by_store, with_receipt};

const SESSION: &str = "haem_session";
const STATE: &str = "haem_state";
const RETURN: &str = "haem_return";
/// How long a sign-in's cookies are kept, in seconds.
const SIGN_IN_FOR: u64 = 600;

/// What this door serves.
pub struct Site {
    /// Studio's origin, the only one a verb is taken from.
    pub origin: String,
    /// The folder holding Studio's built files.
    pub files: PathBuf,
    /// Each store this door serves, by name, with its socket.
    pub stores: BTreeMap<String, PathBuf>,
    /// A store child's terminal failure is shared with the exit waiter.
    pub store_children: BTreeMap<String, (String, Arc<AtomicBool>)>,
    /// The bound on each store connection's steps.
    pub timeout: Duration,
    /// The gzipped content-hashed assets served so far.
    pub packed: Packed,
}

/// How long, in milliseconds, a browser waits before it follows again after
/// a follow's stream ends: sent once at the start of every stream.
const RETRY_MS: u32 = 1_000;

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Verb<'a> {
    method: &'a str,
    #[serde(borrow)]
    params: Option<&'a RawValue>,
}

/// The door's answer to `request` at `now`.
#[must_use]
pub fn answer<I: Issuer>(door: &Door<I>, site: &Site, request: &Request, now: u64) -> Response {
    let path = request.path.as_str();
    match (request.method.as_str(), path) {
        ("GET", "/signin") => sign_in(door, request, now),
        ("GET", "/callback") => callback(door, request, now),
        ("POST", "/signout") => sign_out(door, site, request, now),
        ("GET", "/api/session") => with_session(request, |id| door.session_at(id, now))
            .map_or_else(refusal, |line| Response::json(200, &line)),
        ("GET", "/api/haem") => {
            with_session(request, |id| door.pass(id, now)).map_or_else(refusal, |_| {
                let names: Vec<Value> = site
                    .stores
                    .keys()
                    .map(|name| children::store_line(site, name))
                    .collect();
                Response::json(200, &json!({"stores": names}))
            })
        }
        ("POST", _) if path.starts_with("/api/haem/") => verb(door, site, request, now),
        ("GET", _) if path.starts_with("/api/haem/") && path.ends_with("/follow") => {
            follow_head(door, site, request, now)
        }
        (_, _) if path.starts_with("/api/assistant/") => {
            super::assistant::answer(door, site, request, now)
        }
        (_, _) if path.starts_with("/api/") => refusal(Failure::new(
            "route_unknown",
            "the door serves no such address",
        )),
        ("GET", _) => file(site, request),
        ("POST", _) => refusal(Failure::new(
            "route_unknown",
            "the door serves no such address",
        )),
        _ => refusal(Failure::new(
            "method_refused",
            "the door takes GET and POST only",
        )),
    }
}

fn cookie(name: &str, value: &str, same_site: &str, max_age: u64) -> String {
    format!("{name}={value}; HttpOnly; Secure; SameSite={same_site}; Path=/; Max-Age={max_age}")
}

fn sign_in<I: Issuer>(door: &Door<I>, request: &Request, now: u64) -> Response {
    let back = request
        .parameter("return")
        .filter(|back| back.starts_with('#'))
        .unwrap_or_else(|| "#/".to_owned());
    match door.begin(now) {
        Ok(begun) => Response::redirect(&begun.url)
            .with(
                "Set-Cookie",
                &cookie(STATE, &begun.browser, "Lax", SIGN_IN_FOR),
            )
            .with(
                "Set-Cookie",
                &cookie(
                    RETURN,
                    &url::form_urlencoded::byte_serialize(back.as_bytes()).collect::<String>(),
                    "Lax",
                    SIGN_IN_FOR,
                ),
            ),
        Err(failure) => refused_sign_in("/signin", failure),
    }
}

/// Refused sign-ins written to the log since this process started.
static CALLBACK_REFUSALS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// A refused sign-in is answered and logged in one line naming the refusal
/// and its reason, never the code, state, credential or pass, so an operator
/// reads why a sign-in failed without the source (10 Oct 2026 row).
fn refused_callback(failure: Failure) -> Response {
    refused_sign_in("/callback", failure)
}

fn refused_sign_in(path: &str, failure: Failure) -> Response {
    CALLBACK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    eprintln!(
        "haematite door: sign-in refused at {path}: {}: {}",
        failure.code, failure.message
    );
    refusal(failure)
}

#[cfg(test)]
pub(super) fn callback_refusals() -> u64 {
    CALLBACK_REFUSALS.load(std::sync::atomic::Ordering::Relaxed)
}

fn callback<I: Issuer>(door: &Door<I>, request: &Request, now: u64) -> Response {
    let (Some(code), Some(state)) = (request.parameter("code"), request.parameter("state")) else {
        return refused_callback(Failure::new(
            "sign_in_refused",
            "Lys returned no code; sign in again",
        ));
    };
    let browser = request.cookie(STATE).unwrap_or_default();
    match door.callback(&code, &state, browser, now) {
        Ok(id) => {
            let back = request
                .cookie(RETURN)
                .map(|back| {
                    url::form_urlencoded::parse(format!("r={back}").as_bytes())
                        .map(|(_, value)| value.into_owned())
                        .next()
                        .unwrap_or_default()
                })
                .filter(|back| back.starts_with('#'))
                .unwrap_or_else(|| "#/".to_owned());
            Response::redirect(&format!("/{back}"))
                .with(
                    "Set-Cookie",
                    &cookie(SESSION, &id, "Strict", door.session_seconds()),
                )
                .with("Set-Cookie", &cookie(STATE, "", "Lax", 0))
                .with("Set-Cookie", &cookie(RETURN, "", "Lax", 0))
        }
        Err(failure) => refused_callback(failure),
    }
}

/// Sign this browser out: the door forgets the session its cookie names,
/// with its pass and refresh token (`Door::sign_out`, which says why Lys is
/// not asked to revoke it), and the cookie is cleared. Answered 204 whether
/// or not the door still held the session, so a sign-out after the door
/// restarted, or pressed twice, still clears the cookie.
fn sign_out<I: Issuer>(door: &Door<I>, site: &Site, request: &Request, now: u64) -> Response {
    if request.header("origin") != Some(site.origin.as_str()) {
        return refusal(Failure::new(
            "origin_refused",
            "a sign-out is taken only from Studio's own origin",
        ));
    }
    if let Some(id) = request.cookie(SESSION)
        && let Err(failure) = door.sign_out_at(id, now)
    {
        return refusal(failure);
    }
    Response::no_content().with("Set-Cookie", &cookie(SESSION, "", "Strict", 0))
}

fn with_session<T>(
    request: &Request,
    then: impl FnOnce(&str) -> Result<T, Failure>,
) -> Result<T, Failure> {
    let id = request
        .cookie(SESSION)
        .ok_or_else(|| Failure::new("session_unknown", "sign in to Studio first"))?;
    then(id)
}

fn verb<I: Issuer>(door: &Door<I>, site: &Site, request: &Request, now: u64) -> Response {
    if request.header("origin") != Some(site.origin.as_str()) {
        return refusal(Failure::new(
            "origin_refused",
            "a verb is taken only from Studio's own origin",
        ));
    }
    let token = match with_session(request, |id| door.pass(id, now)) {
        Ok(token) => token,
        Err(failure) => return refusal(failure),
    };
    let name = request.path.trim_start_matches("/api/haem/");
    let Some(socket) = site.stores.get(name) else {
        return refusal(Failure::new(
            "store_unknown",
            "this door serves no store by that name",
        ));
    };
    if let Some(response) = child_given_up(site, name) {
        return response;
    }
    let asked: Verb<'_> = match serde_json::from_slice(&request.body) {
        Ok(asked) => asked,
        Err(error) => return refusal(Failure::new("invalid_params", error.to_string())),
    };
    match carry(socket, site.timeout, &token, asked.method, asked.params) {
        Ok(Carried::Answered(answer)) => {
            Response::new(200, "application/json", answer.get().as_bytes().to_vec())
        }
        Ok(Carried::Refused(refused)) => refused_by_store(&refused),
        Err(Ended::Unknown(why)) => {
            Response::json(502, &json!({"code": "outcome_unknown", "message": why}))
        }
        // The store's whole receipt arrived and still does not say whether the
        // change was applied: the outcome is unknown, and the browser is given
        // the receipt, byte for byte, to reconcile by.
        Err(Ended::Received { why, receipt }) => with_receipt(
            502,
            &Receipted {
                code: "outcome_unknown",
                message: &why,
                path: None,
                receipt: receipt.raw(),
            },
        ),
        Err(Ended::NotAsked(why) | Ended::Usage(why)) => {
            Response::json(502, &json!({"code": "store_not_asked", "message": why}))
        }
    }
}

/// Follow one branch's head as Server-Sent Events. The session, the store
/// and the branch are checked, then the store is asked with the session's
/// pass, as a verb is, up to its first head. Anything refused up to there is
/// answered as JSON with a status, as a verb's refusal is, which a browser's
/// `EventSource` takes as the end and never asks again: nothing retries a
/// store that refused or could not be asked. Once the first head arrives the
/// answer is the event stream: `retry` once, an event `head` per head the
/// store sends, and an event `refused` that ends it, for the follow's own
/// end (`pass_expired`, `branch_unknown`) or a store connection lost
/// (`follow_lost`).
///
/// The stream holds this connection's thread and one of the door's
/// connections while it lasts; every other request has its own thread. A
/// browser that went away wakes a socket watcher which closes its store follow.
fn follow_head<I: Issuer>(door: &Door<I>, site: &Site, request: &Request, now: u64) -> Response {
    if request
        .header("origin")
        .is_some_and(|origin| origin != site.origin)
    {
        return refusal(Failure::new(
            "origin_refused",
            "a follow is taken only from Studio's own origin",
        ));
    }
    let token = match with_session(request, |id| door.pass(id, now)) {
        Ok(token) => token,
        Err(failure) => return refusal(failure),
    };
    let name = request
        .path
        .strip_prefix("/api/haem/")
        .and_then(|rest| rest.strip_suffix("/follow"))
        .unwrap_or_default();
    let Some(socket) = site.stores.get(name) else {
        return refusal(Failure::new(
            "store_unknown",
            "this door serves no store by that name",
        ));
    };
    if let Some(response) = child_given_up(site, name) {
        return response;
    }
    let branch = request.parameter("branch").unwrap_or_default();
    if branch.is_empty() {
        return refusal(Failure::new(
            "invalid_params",
            "name the branch to follow: ?branch=<name>",
        ));
    }
    match follow(socket, site.timeout, &token, &branch) {
        Ok(Followed::Following(following)) => {
            Response::stream_with_peer("text/event-stream", move |output, peer| {
                relay_watched(following, output, peer)
            })
        }
        Ok(Followed::Refused(refused)) => refused_by_store(&refused),
        // A follow changes nothing, so an outcome not known is only a head
        // never read.
        Err(ended) => {
            let refused = json!({"code": "store_not_asked", "message": ended.why()});
            Response::json(502, &refused)
        }
    }
}

/// The stream of a follow the store took: `retry`, its first head, then each
/// frame the store sends until the refusal that ends it.
fn relay_watched(
    following: Following,
    output: &mut dyn Write,
    peer: Option<&std::net::TcpStream>,
) -> io::Result<()> {
    let _monitor = peer
        .map(|peer| {
            let store = following.disconnect_handle()?;
            crate::serve::follow::Monitor::start(peer.try_clone()?, move || {
                if let Err(error) = store.shutdown(std::net::Shutdown::Both) {
                    eprintln!("haematite follow_disconnect_failed: {error}");
                }
            })
        })
        .transpose()?;
    relay(following, output)
}

fn relay(mut following: Following, output: &mut dyn Write) -> io::Result<()> {
    let head = event("head", following.first.get());
    if !sent(output, &format!("retry: {RETRY_MS}\n{head}"))? {
        return Ok(());
    }
    loop {
        match following.next_frame() {
            Ok(Reply::Answered(head)) => {
                if !sent(output, &event("head", head.get()))? {
                    return Ok(());
                }
            }
            Ok(Reply::Refused(refused)) => {
                return refused_event(output, &refused.code, &refused.message);
            }
            Err(ended) => return refused_event(output, "follow_lost", ended.why()),
        }
    }
}

fn refused_event(output: &mut dyn Write, code: &str, message: &str) -> io::Result<()> {
    let data = json!({"code": code, "message": message}).to_string();
    // The last write either way: a browser that has gone needs no ending.
    sent(output, &event("refused", &data))?;
    Ok(())
}

/// One event, each line of `data` on a `data:` line of its own.
pub(super) fn event(name: &str, data: &str) -> String {
    let mut text = format!("event: {name}\n");
    for line in data.lines() {
        text.push_str("data: ");
        text.push_str(line);
        text.push('\n');
    }
    text.push('\n');
    text
}

/// Write `text` and flush it. Answers false when the browser has closed the
/// stream, the normal end of a follow nobody watches any more.
pub(super) fn sent(output: &mut dyn Write, text: &str) -> io::Result<bool> {
    match output.write_all(text.as_bytes()) {
        Ok(()) => {}
        Err(error) if gone(&error) => return Ok(false),
        Err(error) => return Err(error),
    }
    match output.flush() {
        Ok(()) => Ok(true),
        Err(error) if gone(&error) => Ok(false),
        Err(error) => Err(error),
    }
}

/// Whether `error` is the browser having closed the connection.
fn gone(error: &io::Error) -> bool {
    use io::ErrorKind::{BrokenPipe, ConnectionAborted, ConnectionReset};
    matches!(
        error.kind(),
        BrokenPipe | ConnectionReset | ConnectionAborted
    )
}

#[cfg(test)]
#[path = "route_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "route_refusal_tests.rs"]
mod refusal_tests;

#[cfg(test)]
#[path = "route_session_tests.rs"]
mod session_tests;