Skip to main content

agentmux_srv/server/
local_session.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The browser sessions of a headless srv that serves its own UI on loopback: one-time codes, the
5//! pending sessions a code makes, and the live sessions a person confirms.
6//!
7//! The flow, from the person's side: `agentmux-srv open` mints a code with the key, the browser
8//! enters it, the page shows a short check phrase, `open` shows the same phrase and asks the
9//! person to confirm. Only a confirmed session is live. Codes and pending sessions are memory only
10//! and a restart ends them. The live sessions are kept across a restart when a data root is given
11//! ([`SessionStore::keep_in`], the file is in `local_session_file.rs`): only their digests, and only
12//! while they are inside their limits.
13//!
14//! A live session is a pair: a cookie (sent by the browser to every port of the address, so it
15//! proves little alone) and a per-tab token the page keeps in `sessionStorage` (isolated by
16//! origin, port included). One record holds the hash of both, and a request needs both to name it
17//! ([`SessionStore::admit`]). Secrets are kept as SHA-256 digests; a code, handle, cookie or token
18//! never reaches a log.
19
20use std::collections::{HashMap, VecDeque};
21use std::path::PathBuf;
22use std::sync::Mutex;
23use std::time::{Duration, Instant};
24
25use agentmux_common::secret_eq::secret_eq;
26use ring::rand::{SecureRandom, SystemRandom};
27use sha2::{Digest, Sha256};
28
29use super::local_session_file::{self as file, KeyBinding, Record};
30
31/// A code can be entered for this long after it is minted.
32pub(crate) const CODE_LIFE: Duration = Duration::from_secs(60);
33/// A pending session waits this long, from the moment its code was entered, for the person's answer.
34pub(crate) const PENDING_LIFE: Duration = Duration::from_secs(60);
35/// A session ends after this long without a request.
36pub(crate) const SESSION_IDLE_LIFE: Duration = Duration::from_secs(12 * 60 * 60);
37/// A session ends this long after it was confirmed, however much it is used: a browser that is
38/// always open signs in again (with `agentmux-srv open`) once a week.
39pub(crate) const SESSION_MAX_LIFE: Duration = Duration::from_secs(7 * 24 * 60 * 60);
40/// Most codes and most pending sessions held at once; the oldest goes first.
41const MAX_HELD: usize = 64;
42/// Most refusals remembered at once (they are counted over a minute).
43pub(crate) const MAX_FAILURES: usize = 1000;
44/// This many refusals in a minute are logged one by one; after them, one line says the rest are only counted.
45pub(crate) const LOGGED_FAILURES: usize = 5;
46/// Most confirms remembered at once; the oldest goes first.
47const MAX_CONFIRMS: usize = 32;
48
49type Digest32 = [u8; 32];
50
51fn digest(secret: &str) -> Digest32 {
52    Sha256::digest(secret.as_bytes()).into()
53}
54
55/// 256 random bits as 64 hex characters (a valid WebSocket subprotocol token and cookie value).
56pub(crate) fn random_secret() -> String {
57    let mut bytes = [0u8; 32];
58    SystemRandom::new().fill(&mut bytes).expect("the system random source");
59    hex::encode(bytes)
60}
61
62/// Two short pronounceable words from 1024 each (about 20 bits), e.g. `kela-mivo`: easy to compare by eye.
63pub(crate) fn check_phrase() -> String {
64    let mut bytes = [0u8; 4];
65    SystemRandom::new().fill(&mut bytes).expect("the system random source");
66    let a = u16::from_le_bytes([bytes[0], bytes[1]]) & 0x3ff;
67    let b = u16::from_le_bytes([bytes[2], bytes[3]]) & 0x3ff;
68    format!("{}-{}", phrase_word(a), phrase_word(b))
69}
70
71/// Word `n` (0..1024): consonant, vowel, consonant, vowel from 8 consonants and 4 vowels.
72fn phrase_word(n: u16) -> String {
73    const CONSONANTS: [char; 8] = ['k', 'l', 'm', 'n', 'r', 's', 't', 'v'];
74    const VOWELS: [char; 4] = ['a', 'e', 'i', 'o'];
75    let n = usize::from(n & 0x3ff);
76    [CONSONANTS[n >> 7], VOWELS[(n >> 5) & 3], CONSONANTS[(n >> 2) & 7], VOWELS[n & 3]].iter().collect()
77}
78
79/// What a request to a route may present.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub(crate) enum RouteClass {
82    /// The cookie and the token must both name one session. Every route unless listed below.
83    Both,
84    /// The cookie alone (for a GET that an element loads by URL and that changes nothing).
85    CookieOnly,
86}
87
88/// What a session's page was handed, once.
89pub(crate) struct Grant {
90    pub cookie: String,
91    pub token: String,
92}
93
94enum Outcome {
95    Waiting,
96    /// Confirmed. `Some` until the waiting page collects it.
97    Granted(Option<Grant>),
98    Discarded,
99}
100
101struct Pending {
102    code: Digest32,
103    phrase: String,
104    born: Instant,
105    outcome: Outcome,
106    /// The session confirming made, to end it if the page never collected its grant.
107    cookie: Option<Digest32>,
108}
109
110/// How a confirm was made: where the process that sent it stands.
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub(crate) enum ConfirmHow {
113    /// The sending process is in no agent's process tree.
114    Outside,
115    /// The sending process could not be found (the lookup failed, or the peer is not on IPv4 loopback); the confirm was not taken.
116    Unknown,
117    /// The request carried forwarding headers, so it came through a proxy or a tunnel; the confirm was not taken.
118    Forwarded,
119    /// The sending process is in this agent's tree (`agent:<id>`); the confirm was not taken.
120    Refused(String),
121}
122
123impl ConfirmHow {
124    /// Whether the confirm is the person's answer: only a process found outside every agent's tree is.
125    pub(crate) fn is_taken(&self) -> bool {
126        matches!(self, ConfirmHow::Outside)
127    }
128
129    pub(crate) fn label(&self) -> String {
130        match self {
131            ConfirmHow::Outside => "peer outside agent trees".to_string(),
132            ConfirmHow::Unknown => "peer unknown".to_string(),
133            ConfirmHow::Forwarded => "peer forwarded".to_string(),
134            ConfirmHow::Refused(who) => format!("refused: {who}"),
135        }
136    }
137}
138
139/// One confirm of a session, as `status` shows it. It holds no value of a code, cookie or token: the session is named by its
140/// check phrase, which the person saw.
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub(crate) struct Confirm {
143    pub at_unix_ms: u64,
144    pub session: String,
145    pub how: ConfirmHow,
146}
147
148struct Session {
149    token: Digest32,
150    last_seen: Instant,
151    /// When the person confirmed it: [`SESSION_MAX_LIFE`] counts from here.
152    born: Instant,
153    /// How long it had already gone unused, and how long ago it was confirmed, when this process started: a session kept
154    /// across a restart (an `Instant` cannot name a time before the machine booted). Added to the time since `last_seen`
155    /// and `born`; a use clears the first.
156    idle_carry: Duration,
157    born_carry: Duration,
158}
159
160impl Session {
161    fn new(token: Digest32, now: Instant) -> Session {
162        Session { token, last_seen: now, born: now, idle_carry: Duration::ZERO, born_carry: Duration::ZERO }
163    }
164
165    fn idle(&self, now: Instant) -> Duration {
166        self.idle_carry + now.saturating_duration_since(self.last_seen)
167    }
168
169    fn age(&self, now: Instant) -> Duration {
170        self.born_carry + now.saturating_duration_since(self.born)
171    }
172
173    fn touch(&mut self, now: Instant) {
174        self.last_seen = now;
175        self.idle_carry = Duration::ZERO;
176    }
177
178    fn expired(&self, now: Instant) -> bool {
179        self.idle(now) > SESSION_IDLE_LIFE || self.age(now) > SESSION_MAX_LIFE
180    }
181}
182
183/// Where the live sessions are kept across a restart, once that is on.
184struct Persist {
185    path: PathBuf,
186    binding: KeyBinding,
187    /// When the file was last written, so a use of a session rewrites it at most every [`file::SAVE_EVERY`].
188    last_saved: Option<Instant>,
189}
190
191#[derive(Default)]
192struct Inner {
193    persist: Option<Persist>,
194    /// Codes minted and not yet entered.
195    codes: HashMap<Digest32, Instant>,
196    /// Keyed by the page's handle.
197    pending: HashMap<Digest32, Pending>,
198    /// Keyed by the cookie's digest.
199    sessions: HashMap<Digest32, Session>,
200    failures: VecDeque<Instant>,
201    /// Oldest first.
202    confirms: VecDeque<Confirm>,
203}
204
205pub(crate) struct SessionStore {
206    inner: Mutex<Inner>,
207    /// Counts the logouts, so a socket upgraded with a session hears that it ended.
208    revoked: tokio::sync::watch::Sender<u64>,
209}
210
211impl Default for SessionStore {
212    fn default() -> Self {
213        SessionStore { inner: Mutex::new(Inner::default()), revoked: tokio::sync::watch::channel(0).0 }
214    }
215}
216
217/// Which session a request came from (the digest of its cookie), carried on the request so a
218/// WebSocket upgraded with it can be closed when the session ends.
219#[derive(Debug, Clone, Copy, PartialEq, Eq)]
220pub(crate) struct SessionId(Digest32);
221
222impl SessionId {
223    pub(crate) fn of_cookie(cookie: &str) -> SessionId {
224        SessionId(digest(cookie))
225    }
226}
227
228/// How often a socket re-checks that its session is still live (a logout is heard at once).
229const LIVE_RECHECK: Duration = Duration::from_secs(10);
230
231/// What a code entry made.
232pub(crate) struct Entered {
233    pub handle: String,
234    pub phrase: String,
235}
236
237/// Where a code stands, for the `open` that minted it.
238#[derive(Debug, PartialEq, Eq)]
239pub(crate) enum CodeState {
240    /// Minted and nobody has entered it yet.
241    Unused,
242    /// Entered; the browser that did shows this phrase.
243    Entered { phrase: String },
244    /// Expired, answered or never minted here.
245    Gone,
246}
247
248/// The waiting page's answer.
249pub(crate) enum Collected {
250    Waiting,
251    Granted(Grant),
252    Refused,
253}
254
255impl SessionStore {
256    fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
257        self.inner.lock().unwrap_or_else(|e| e.into_inner())
258    }
259
260    /// Keep the live sessions in `path` from now on, after taking back the ones a restart finds there that are inside their
261    /// limits. A file that cannot be trusted is cleared and logged once, with no value from it; the store then starts empty.
262    pub(crate) fn keep_in(&self, path: PathBuf, binding: KeyBinding, now: Instant, wall_secs: u64) {
263        let mut inner = self.lock();
264        match file::load(&path, &binding, wall_secs) {
265            Ok(None) => {}
266            Ok(Some(records)) => {
267                let mut kept = 0usize;
268                for r in records {
269                    let session = Session {
270                        token: r.token,
271                        last_seen: now,
272                        born: now,
273                        idle_carry: Duration::from_secs(wall_secs.saturating_sub(r.last_seen_secs)),
274                        born_carry: Duration::from_secs(wall_secs.saturating_sub(r.born_secs)),
275                    };
276                    if session.expired(now) {
277                        continue;
278                    }
279                    inner.sessions.insert(r.cookie, session);
280                    kept += 1;
281                }
282                tracing::info!(kept, "browser sign-ins kept across the restart");
283            }
284            Err(why) => tracing::warn!(reason = why.why(), "the saved browser sign-ins were not used and all of them were cleared"),
285        }
286        inner.persist = Some(Persist { path, binding, last_saved: None });
287        save(&mut inner, now);
288    }
289
290    /// A new one-time code: 256 random bits, single use, [`CODE_LIFE`].
291    pub(crate) fn mint_code(&self, now: Instant) -> String {
292        let code = random_secret();
293        let mut inner = self.lock();
294        prune(&mut inner, now);
295        if inner.codes.len() >= MAX_HELD {
296            if let Some(oldest) = inner.codes.iter().min_by_key(|(_, born)| **born).map(|(k, _)| *k) {
297                inner.codes.remove(&oldest);
298            }
299        }
300        inner.codes.insert(digest(&code), now);
301        code
302    }
303
304    /// Enter a code: it is spent whether or not it was valid, and a valid one makes a pending
305    /// session, which holds no access. `None` for a wrong, used or expired code.
306    pub(crate) fn enter(&self, code: &str, now: Instant) -> Option<Entered> {
307        let mut inner = self.lock();
308        prune(&mut inner, now);
309        let code = digest(code);
310        inner.codes.remove(&code)?;
311        if inner.pending.len() >= MAX_HELD {
312            if let Some(oldest) = inner.pending.iter().min_by_key(|(_, p)| p.born).map(|(k, _)| *k) {
313                end_pending(&mut inner, oldest);
314            }
315        }
316        let handle = random_secret();
317        let phrase = check_phrase();
318        let pending = Pending { code, phrase: phrase.clone(), born: now, outcome: Outcome::Waiting, cookie: None };
319        inner.pending.insert(digest(&handle), pending);
320        Some(Entered { handle, phrase })
321    }
322
323    /// Where the code `open` minted stands. It looks nothing up by anything else.
324    pub(crate) fn code_state(&self, code: &str, now: Instant) -> CodeState {
325        let mut inner = self.lock();
326        prune(&mut inner, now);
327        let code = digest(code);
328        if inner.codes.contains_key(&code) {
329            return CodeState::Unused;
330        }
331        inner
332            .pending
333            .values()
334            .find(|p| p.code == code && matches!(p.outcome, Outcome::Waiting))
335            .map_or(CodeState::Gone, |p| CodeState::Entered { phrase: p.phrase.clone() })
336    }
337
338    /// Record how the confirm of the session made from `code` arrived. False when no pending session of that code waits.
339    pub(crate) fn note_confirm(&self, code: &str, how: ConfirmHow, now: Instant) -> bool {
340        let mut inner = self.lock();
341        prune(&mut inner, now);
342        let code = digest(code);
343        let Some(session) = inner.pending.values().find(|p| p.code == code && matches!(p.outcome, Outcome::Waiting)).map(|p| p.phrase.clone())
344        else {
345            return false;
346        };
347        if inner.confirms.len() >= MAX_CONFIRMS {
348            inner.confirms.pop_front();
349        }
350        inner.confirms.push_back(Confirm { at_unix_ms: agentmux_common::time::now_secs_u64().saturating_mul(1000), session, how });
351        true
352    }
353
354    /// The confirms remembered, oldest first.
355    pub(crate) fn confirms(&self) -> Vec<Confirm> {
356        self.lock().confirms.iter().cloned().collect()
357    }
358
359    /// The person's answer for the session made from `code`. True when a pending session of that
360    /// code was waiting. Confirming makes the live session (its hashes), and keeps the cookie and
361    /// token for the waiting page to collect once.
362    pub(crate) fn decide(&self, code: &str, accept: bool, now: Instant) -> bool {
363        let mut inner = self.lock();
364        prune(&mut inner, now);
365        let code = digest(code);
366        let Some(handle) = inner.pending.iter().find(|(_, p)| p.code == code && matches!(p.outcome, Outcome::Waiting)).map(|(h, _)| *h)
367        else {
368            return false;
369        };
370        if !accept {
371            if let Some(p) = inner.pending.get_mut(&handle) {
372                p.outcome = Outcome::Discarded;
373            }
374            return true;
375        }
376        let grant = Grant { cookie: random_secret(), token: random_secret() };
377        let cookie = digest(&grant.cookie);
378        inner.sessions.insert(cookie, Session::new(digest(&grant.token), now));
379        save(&mut inner, now);
380        if let Some(p) = inner.pending.get_mut(&handle) {
381            p.cookie = Some(cookie);
382            p.outcome = Outcome::Granted(Some(grant));
383        }
384        true
385    }
386
387    /// The waiting page asks, with its handle. A grant is handed over exactly once; a discarded,
388    /// expired, spent or unknown handle is refused.
389    pub(crate) fn collect(&self, handle: &str, now: Instant) -> Collected {
390        let mut inner = self.lock();
391        prune(&mut inner, now);
392        let handle = digest(handle);
393        let Some(pending) = inner.pending.get_mut(&handle) else {
394            return Collected::Refused;
395        };
396        match &mut pending.outcome {
397            Outcome::Waiting => Collected::Waiting,
398            Outcome::Granted(grant) => match grant.take() {
399                Some(grant) => {
400                    // Spent: the handle dies with the answer.
401                    inner.pending.remove(&handle);
402                    Collected::Granted(grant)
403                }
404                None => Collected::Refused,
405            },
406            Outcome::Discarded => {
407                inner.pending.remove(&handle);
408                Collected::Refused
409            }
410        }
411    }
412
413    /// Does this request name a live session? `Both` needs the token too. A use slides the idle limit.
414    pub(crate) fn admit(&self, cookie: Option<&str>, token: Option<&str>, class: RouteClass, now: Instant) -> bool {
415        let Some(cookie) = cookie else { return false };
416        let mut inner = self.lock();
417        prune(&mut inner, now);
418        let Some(session) = inner.sessions.get_mut(&digest(cookie)) else {
419            return false;
420        };
421        let token_ok = match class {
422            RouteClass::CookieOnly => true,
423            RouteClass::Both => token.is_some_and(|t| secret_eq(&digest(t), &session.token)),
424        };
425        if token_ok {
426            session.touch(now);
427            save_if_due(&mut inner, now);
428        }
429        token_ok
430    }
431
432    /// End every session and every pending sign-in. How many sessions there were.
433    pub(crate) fn revoke_all(&self) -> usize {
434        let mut inner = self.lock();
435        inner.codes.clear();
436        inner.pending.clear();
437        let n = inner.sessions.len();
438        inner.sessions.clear();
439        save(&mut inner, Instant::now());
440        drop(inner);
441        self.revoked.send_modify(|logouts| *logouts += 1);
442        n
443    }
444
445    /// End one session (this browser's): the others stay. False when it was not live. A socket that
446    /// was upgraded with it hears that it ended.
447    pub(crate) fn revoke(&self, id: SessionId, now: Instant) -> bool {
448        let mut inner = self.lock();
449        prune(&mut inner, now);
450        let was_live = inner.sessions.remove(&id.0).is_some();
451        if was_live {
452            save(&mut inner, now);
453        }
454        drop(inner);
455        if was_live {
456            self.revoked.send_modify(|logouts| *logouts += 1);
457        }
458        was_live
459    }
460
461    /// Is this session still live? A socket that asks is in use, so it slides the idle limit.
462    pub(crate) fn is_live(&self, id: SessionId, now: Instant) -> bool {
463        let mut inner = self.lock();
464        prune(&mut inner, now);
465        let live = inner.sessions.get_mut(&id.0).map(|s| s.touch(now)).is_some();
466        if live {
467            save_if_due(&mut inner, now);
468        }
469        live
470    }
471
472    /// Completes when the session has ended: at a logout, and at the first re-check after it
473    /// expired. A WebSocket is authenticated once, when it is upgraded, so it waits on this.
474    pub(crate) async fn ended(&self, id: SessionId) {
475        let mut logouts = self.revoked.subscribe();
476        while self.is_live(id, Instant::now()) {
477            tokio::select! {
478                _ = logouts.changed() => {}
479                _ = tokio::time::sleep(LIVE_RECHECK) => {}
480            }
481        }
482    }
483
484    pub(crate) fn session_count(&self, now: Instant) -> usize {
485        let mut inner = self.lock();
486        prune(&mut inner, now);
487        inner.sessions.len()
488    }
489
490    /// Count a refused sign-in; how many in the last minute (at most [`MAX_FAILURES`]), this one
491    /// included. The list is capped, so a flood of refusals holds no more memory than a trickle.
492    pub(crate) fn note_failure(&self, now: Instant) -> usize {
493        let mut inner = self.lock();
494        let minute = Duration::from_secs(60);
495        while inner.failures.front().is_some_and(|t| now.duration_since(*t) > minute) {
496            inner.failures.pop_front();
497        }
498        if inner.failures.len() >= MAX_FAILURES {
499            inner.failures.pop_front();
500        }
501        inner.failures.push_back(now);
502        inner.failures.len()
503    }
504}
505
506/// A use of a session is written at most every [`file::SAVE_EVERY`].
507fn save_if_due(inner: &mut Inner, now: Instant) {
508    if inner.persist.as_ref().is_some_and(|p| p.last_saved.is_none_or(|t| now.duration_since(t) >= file::SAVE_EVERY)) {
509        save(inner, now);
510    }
511}
512
513/// Write the live sessions to the file, or delete it when there are none. A write that fails is logged (its kind only) and the
514/// sessions stay in memory: nothing is lost but a sign-in surviving the next restart.
515fn save(inner: &mut Inner, now: Instant) {
516    let Inner { sessions, persist, .. } = inner;
517    let Some(p) = persist.as_mut() else { return };
518    p.last_saved = Some(now);
519    let wall = agentmux_common::time::now_secs_u64();
520    if sessions.is_empty() {
521        if let Err(e) = file::clear(&p.path, &p.binding, wall) {
522            tracing::warn!(kind = ?e.kind(), "the file of browser sign-ins could not be deleted or emptied; sessions that have ended may come back after a restart");
523        }
524        return;
525    }
526    let records: Vec<Record> = sessions
527        .iter()
528        .map(|(cookie, s)| Record {
529            cookie: *cookie,
530            token: s.token,
531            born_secs: wall.saturating_sub(s.age(now).as_secs()),
532            last_seen_secs: wall.saturating_sub(s.idle(now).as_secs()),
533        })
534        .collect();
535    if let Err(e) = file::save(&p.path, &p.binding, wall, &records) {
536        // The old file may hold a session that has just ended: take it away, so nothing that ended comes back.
537        match file::clear(&p.path, &p.binding, wall) {
538            Ok(()) => tracing::warn!(kind = ?e.kind(), "the browser sign-ins could not be saved; they end at the next restart"),
539            Err(_) => tracing::warn!(kind = ?e.kind(), "the browser sign-ins could not be saved or the old file removed; sessions that have ended may come back after a restart"),
540        }
541    }
542}
543
544/// Drop what has expired. A grant nobody collected ends its session too.
545fn prune(inner: &mut Inner, now: Instant) {
546    inner.codes.retain(|_, born| now.duration_since(*born) <= CODE_LIFE);
547    let stale: Vec<Digest32> =
548        inner.pending.iter().filter(|(_, p)| now.duration_since(p.born) > PENDING_LIFE).map(|(h, _)| *h).collect();
549    for handle in stale {
550        end_pending(inner, handle);
551    }
552    inner.sessions.retain(|_, s| !s.expired(now));
553}
554
555fn end_pending(inner: &mut Inner, handle: Digest32) {
556    if let Some(p) = inner.pending.remove(&handle) {
557        if let (Outcome::Granted(Some(_)), Some(cookie)) = (&p.outcome, p.cookie) {
558            inner.sessions.remove(&cookie);
559        }
560    }
561}
562
563#[cfg(test)]
564#[path = "tests/local_session_tests.rs"]
565mod tests;