Skip to main content

hyprstream_core/services/oauth/
session.rs

1//! Server-side session management for the OAuth browser login flow.
2//!
3//! Sessions are stored server-side and identified by a cryptographic cookie.
4//! Cookie attributes: HttpOnly, Secure, SameSite=Lax.
5
6use std::collections::HashMap;
7use std::time::{Duration, Instant};
8
9use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
10use rand::RngCore;
11use tokio::sync::RwLock;
12
13/// A server-side session for an authenticated user.
14#[derive(Debug, Clone)]
15pub struct Session {
16    /// Authenticated subject. ATProto browser sessions store the verified DID.
17    pub username: String,
18    /// How the user authenticated ("local" or provider slug).
19    pub auth_method: String,
20    /// Verified ATProto DID for browser sessions created by the exchange seam.
21    pub atproto_did: Option<String>,
22    /// Authority-owned tenant binding resolved from the verified identity.
23    pub verified_tenant: Option<String>,
24    /// When the user authenticated.
25    pub authenticated_at: Instant,
26    /// When the session expires.
27    pub expires_at: Instant,
28}
29
30/// Session store with sweeping support.
31pub struct SessionStore {
32    sessions: RwLock<HashMap<String, Session>>,
33    ttl: Duration,
34}
35
36pub const SESSION_COOKIE_NAME: &str = "hyprstream_session";
37
38impl SessionStore {
39    pub fn new(ttl_seconds: u64) -> Self {
40        Self {
41            sessions: RwLock::new(HashMap::new()),
42            ttl: Duration::from_secs(ttl_seconds),
43        }
44    }
45
46    /// Create a new session and return the session ID (for the cookie).
47    pub async fn create(&self, username: String, auth_method: String) -> String {
48        let mut id_bytes = [0u8; 32];
49        rand::rngs::OsRng.fill_bytes(&mut id_bytes);
50        let session_id = URL_SAFE_NO_PAD.encode(id_bytes);
51
52        let session = Session {
53            username,
54            auth_method,
55            atproto_did: None,
56            verified_tenant: None,
57            authenticated_at: Instant::now(),
58            expires_at: Instant::now() + self.ttl,
59        };
60
61        self.sessions
62            .write()
63            .await
64            .insert(session_id.clone(), session);
65        session_id
66    }
67
68    /// Create a browser session from a server-verified ATProto identity.
69    pub async fn create_atproto(&self, did: String, verified_tenant: Option<String>) -> String {
70        let mut id_bytes = [0u8; 32];
71        rand::rngs::OsRng.fill_bytes(&mut id_bytes);
72        let session_id = URL_SAFE_NO_PAD.encode(id_bytes);
73        let session = Session {
74            username: did.clone(),
75            auth_method: "atproto".to_owned(),
76            atproto_did: Some(did),
77            verified_tenant,
78            authenticated_at: Instant::now(),
79            expires_at: Instant::now() + self.ttl,
80        };
81        self.sessions
82            .write()
83            .await
84            .insert(session_id.clone(), session);
85        session_id
86    }
87
88    /// Look up a session by ID. Returns None if not found or expired.
89    pub async fn get(&self, session_id: &str) -> Option<Session> {
90        let sessions = self.sessions.read().await;
91        sessions.get(session_id).and_then(|s| {
92            if s.expires_at > Instant::now() {
93                Some(s.clone())
94            } else {
95                None
96            }
97        })
98    }
99
100    /// Remove a session (logout).
101    pub async fn remove(&self, session_id: &str) {
102        self.sessions.write().await.remove(session_id);
103    }
104
105    /// Sweep expired sessions.
106    pub async fn sweep(&self) {
107        let now = Instant::now();
108        self.sessions
109            .write()
110            .await
111            .retain(|_, s| s.expires_at > now);
112    }
113}
114
115impl Default for SessionStore {
116    fn default() -> Self {
117        Self::new(8 * 3600) // 8 hours
118    }
119}
120
121/// Extract session ID from request cookies.
122pub fn extract_session_id(headers: &axum::http::HeaderMap) -> Option<String> {
123    let prefix = format!("{SESSION_COOKIE_NAME}=");
124    headers
125        .get(axum::http::header::COOKIE)
126        .and_then(|v| v.to_str().ok())
127        .and_then(|cookies| {
128            cookies
129                .split(';')
130                .map(str::trim)
131                .find_map(|cookie| cookie.strip_prefix(&prefix))
132                .filter(|session_id| !session_id.is_empty())
133                .map(String::from)
134        })
135}
136
137/// Build a Set-Cookie header value for the session.
138pub fn session_cookie(session_id: &str, secure: bool) -> String {
139    let secure_flag = if secure { "; Secure" } else { "" };
140    format!(
141        "{SESSION_COOKIE_NAME}={session_id}; HttpOnly; SameSite=Lax; Path=/{secure_flag}; Max-Age=28800"
142    )
143}
144
145/// Build a Set-Cookie header that clears the session.
146pub fn clear_session_cookie() -> String {
147    format!("{SESSION_COOKIE_NAME}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0")
148}