1use 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
31pub(crate) const CODE_LIFE: Duration = Duration::from_secs(60);
33pub(crate) const PENDING_LIFE: Duration = Duration::from_secs(60);
35pub(crate) const SESSION_IDLE_LIFE: Duration = Duration::from_secs(12 * 60 * 60);
37pub(crate) const SESSION_MAX_LIFE: Duration = Duration::from_secs(7 * 24 * 60 * 60);
40const MAX_HELD: usize = 64;
42pub(crate) const MAX_FAILURES: usize = 1000;
44pub(crate) const LOGGED_FAILURES: usize = 5;
46const MAX_CONFIRMS: usize = 32;
48
49type Digest32 = [u8; 32];
50
51fn digest(secret: &str) -> Digest32 {
52 Sha256::digest(secret.as_bytes()).into()
53}
54
55pub(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
62pub(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
71fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub(crate) enum RouteClass {
82 Both,
84 CookieOnly,
86}
87
88pub(crate) struct Grant {
90 pub cookie: String,
91 pub token: String,
92}
93
94enum Outcome {
95 Waiting,
96 Granted(Option<Grant>),
98 Discarded,
99}
100
101struct Pending {
102 code: Digest32,
103 phrase: String,
104 born: Instant,
105 outcome: Outcome,
106 cookie: Option<Digest32>,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
112pub(crate) enum ConfirmHow {
113 Outside,
115 Unknown,
117 Forwarded,
119 Refused(String),
121}
122
123impl ConfirmHow {
124 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#[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 born: Instant,
153 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
183struct Persist {
185 path: PathBuf,
186 binding: KeyBinding,
187 last_saved: Option<Instant>,
189}
190
191#[derive(Default)]
192struct Inner {
193 persist: Option<Persist>,
194 codes: HashMap<Digest32, Instant>,
196 pending: HashMap<Digest32, Pending>,
198 sessions: HashMap<Digest32, Session>,
200 failures: VecDeque<Instant>,
201 confirms: VecDeque<Confirm>,
203}
204
205pub(crate) struct SessionStore {
206 inner: Mutex<Inner>,
207 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#[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
228const LIVE_RECHECK: Duration = Duration::from_secs(10);
230
231pub(crate) struct Entered {
233 pub handle: String,
234 pub phrase: String,
235}
236
237#[derive(Debug, PartialEq, Eq)]
239pub(crate) enum CodeState {
240 Unused,
242 Entered { phrase: String },
244 Gone,
246}
247
248pub(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 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 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 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 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 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 pub(crate) fn confirms(&self) -> Vec<Confirm> {
356 self.lock().confirms.iter().cloned().collect()
357 }
358
359 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 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 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 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 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 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 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 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 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
506fn 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
513fn 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 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
544fn 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;