Skip to main content

toolblox_lib/
login.rs

1//! Isolated Roblox login webview and secret handoff.
2
3use std::fmt;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, Mutex};
6
7use serde::Serialize;
8use tauri::webview::{NewWindowResponse, PageLoadEvent};
9use tauri::{Manager, WebviewUrl, WebviewWindow, WebviewWindowBuilder};
10use zeroize::Zeroizing;
11
12/// Window label of the Roblox sign-in webview.
13pub const LOGIN_WINDOW_LABEL: &str = "roblox-login";
14/// Page the sign-in webview opens.
15pub const LOGIN_URL: &str = "https://www.roblox.com/login";
16/// Name of the Roblox session cookie.
17const SECURITY_COOKIE_NAME: &str = ".ROBLOSECURITY";
18
19/// A session cookie read from the sign-in webview. Its memory is zeroed on drop.
20pub struct RobloxCookie(Zeroizing<String>);
21
22impl RobloxCookie {
23    /// Returns the raw cookie value. Callers must not log or return it to JavaScript.
24    pub fn expose_secret(&self) -> &str {
25        self.0.as_str()
26    }
27}
28
29/// The Roblox user a session belongs to.
30#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
31#[serde(rename_all = "camelCase")]
32pub struct AccountIdentity {
33    pub id: u64,
34    pub name: String,
35    pub display_name: String,
36    pub avatar_url: Option<String>,
37}
38
39/// Progress of a sign-in window.
40#[derive(Clone, Debug, Eq, PartialEq)]
41pub enum LoginPhase {
42    /// Waiting for the user to sign in.
43    Waiting,
44    /// Reading the session cookie.
45    Checking,
46    Complete,
47    Cancelled,
48    Failed,
49}
50
51/// Why a sign-in failed. Displays as a user-facing message.
52#[derive(Clone, Debug, Eq, PartialEq)]
53pub enum LoginError {
54    AlreadyOpen,
55    Window,
56    CookieRead,
57    Network,
58    InvalidSession,
59    CredentialStore,
60    Cleanup,
61    /// The sign-in was for a different account than the one being signed in again.
62    WrongAccount,
63}
64
65impl fmt::Display for LoginError {
66    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
67        formatter.write_str(match self {
68            Self::AlreadyOpen => "The Roblox sign-in window is already open. Can you continue in that window?",
69            Self::Window => "The Roblox sign-in window couldn't open. Would trying again help?",
70            Self::CookieRead => "The Roblox session couldn't be read. Would signing in again help?",
71            Self::Network => "Toolblox couldn't reach Roblox. Is the connection working?",
72            Self::InvalidSession => "Roblox didn't accept the session. Would signing in again help?",
73            Self::CredentialStore => {
74                "The Roblox session couldn't be stored securely. Is the credential store available?"
75            }
76            Self::Cleanup => {
77                "The temporary Roblox browsing data couldn't be cleared. Would restarting Toolblox help?"
78            }
79            Self::WrongAccount => {
80                "The signed-in Roblox account doesn't match. Can you sign in with the selected account?"
81            }
82        })
83    }
84}
85
86impl std::error::Error for LoginError {}
87
88/// The outcome of a sign-in, delivered once.
89#[derive(Clone, Debug, Eq, PartialEq)]
90pub enum LoginNotice {
91    Complete(AccountIdentity),
92    Failed(LoginError),
93    Cancelled,
94}
95
96/// Checks a session with Roblox and returns its user.
97type ValidateSession =
98    dyn Fn(&RobloxCookie) -> Result<AccountIdentity, LoginError> + Send + Sync + 'static;
99/// Stores a validated session.
100type StoreSession =
101    dyn Fn(&AccountIdentity, &RobloxCookie) -> Result<(), LoginError> + Send + Sync + 'static;
102/// Receives the sign-in outcome.
103type Notify = dyn Fn(LoginNotice) + Send + Sync + 'static;
104
105/// State shared by one sign-in window's callbacks.
106struct LoginRuntime {
107    /// Whether a cookie check is running.
108    in_flight: AtomicBool,
109    /// Set once the window closes or the sign-in fails, stopping further checks.
110    cancelled: AtomicBool,
111    phase: Mutex<LoginPhase>,
112    validate: Arc<ValidateSession>,
113    store: Arc<StoreSession>,
114    notify: Arc<Notify>,
115}
116
117impl LoginRuntime {
118    /// Replaces the current phase.
119    fn set_phase(&self, phase: LoginPhase) {
120        *self.phase.lock().unwrap_or_else(|error| error.into_inner()) = phase;
121    }
122}
123
124/// Opens an isolated, incognito Roblox sign-in window.
125///
126/// After each page load the window's cookies are polled for the session cookie. When found, the
127/// session is validated, the window's browsing data is cleared, the session is stored, and `notify`
128/// receives the outcome. Navigation is limited to HTTPS Roblox hosts, and new windows are blocked.
129pub fn open_roblox_login<V, S, N>(
130    app: &tauri::AppHandle,
131    validate: V,
132    store: S,
133    notify: N,
134) -> Result<(), LoginError>
135where
136    V: Fn(&RobloxCookie) -> Result<AccountIdentity, LoginError> + Send + Sync + 'static,
137    S: Fn(&AccountIdentity, &RobloxCookie) -> Result<(), LoginError> + Send + Sync + 'static,
138    N: Fn(LoginNotice) + Send + Sync + 'static,
139{
140    if app.get_webview_window(LOGIN_WINDOW_LABEL).is_some() {
141        return Err(LoginError::AlreadyOpen);
142    }
143
144    let runtime = Arc::new(LoginRuntime {
145        in_flight: AtomicBool::new(false),
146        cancelled: AtomicBool::new(false),
147        phase: Mutex::new(LoginPhase::Waiting),
148        validate: Arc::new(validate),
149        store: Arc::new(store),
150        notify: Arc::new(notify),
151    });
152    let page_runtime = runtime.clone();
153    let login_url = LOGIN_URL.parse().map_err(|_| LoginError::Window)?;
154
155    let window =
156        WebviewWindowBuilder::new(app, LOGIN_WINDOW_LABEL, WebviewUrl::External(login_url))
157            .title("Sign in to Roblox")
158            .inner_size(480.0, 640.0)
159            .incognito(true)
160            .devtools(false)
161            .on_navigation(is_allowed_roblox_navigation)
162            .on_new_window(|_, _| NewWindowResponse::Deny)
163            .on_page_load(move |window, payload| {
164                if payload.event() == PageLoadEvent::Finished {
165                    schedule_cookie_check(window, page_runtime.clone());
166                }
167            })
168            .build()
169            .map_err(|_| LoginError::Window)?;
170
171    let closed_runtime = runtime.clone();
172    window.on_window_event(move |event| {
173        if matches!(event, tauri::WindowEvent::Destroyed) {
174            closed_runtime.cancelled.store(true, Ordering::SeqCst);
175            if closed_runtime.phase.lock().is_ok_and(|phase| {
176                !matches!(
177                    *phase,
178                    LoginPhase::Complete | LoginPhase::Cancelled | LoginPhase::Failed
179                )
180            }) {
181                closed_runtime.set_phase(LoginPhase::Cancelled);
182                (closed_runtime.notify)(LoginNotice::Cancelled);
183            }
184        }
185    });
186
187    Ok(())
188}
189
190/// Window label of the signed-in Roblox profile webview.
191pub const PROFILE_WINDOW_LABEL: &str = "roblox-profile";
192
193/// Opens an isolated, incognito roblox.com window signed in with `session`, on the profile of
194/// `user_id`, for actions Roblox only allows after a verification check it shows itself. An open
195/// profile window is replaced. The session cookie is HTTP-only, so the page can't read it, and
196/// the incognito data is discarded when the window closes. Navigation is limited to HTTPS Roblox
197/// hosts, and new windows are blocked.
198pub fn open_roblox_profile(
199    app: &tauri::AppHandle,
200    session: &crate::credentials::Secret,
201    user_id: u64,
202) -> Result<(), LoginError> {
203    if let Some(window) = app.get_webview_window(PROFILE_WINDOW_LABEL) {
204        let _ = window.destroy();
205    }
206    let blank = "about:blank".parse().map_err(|_| LoginError::Window)?;
207    let window = WebviewWindowBuilder::new(app, PROFILE_WINDOW_LABEL, WebviewUrl::External(blank))
208        .title("Roblox")
209        .inner_size(1000.0, 720.0)
210        .incognito(true)
211        .devtools(false)
212        .on_navigation(|url| url.as_str() == "about:blank" || is_allowed_roblox_navigation(url))
213        .on_new_window(|_, _| NewWindowResponse::Deny)
214        .build()
215        .map_err(|_| LoginError::Window)?;
216    let cookie = tauri::webview::cookie::Cookie::build((SECURITY_COOKIE_NAME, session.expose()))
217        .domain(".roblox.com")
218        .path("/")
219        .secure(true)
220        .http_only(true)
221        .build();
222    let profile = format!("https://www.roblox.com/users/{user_id}/profile")
223        .parse()
224        .map_err(|_| LoginError::Window)?;
225    if window.set_cookie(cookie).is_err() || window.navigate(profile).is_err() {
226        let _ = window.destroy();
227        return Err(LoginError::Window);
228    }
229    Ok(())
230}
231
232/// Allows navigation only to `roblox.com` and its subdomains over HTTPS.
233pub fn is_allowed_roblox_navigation(url: &tauri::Url) -> bool {
234    url.scheme() == "https"
235        && url.host_str().is_some_and(|host| {
236            let host = host.to_ascii_lowercase();
237            host == "roblox.com" || host.ends_with(".roblox.com")
238        })
239}
240
241/// Matches the secure, HTTP-only `.ROBLOSECURITY` cookie on a Roblox domain.
242pub fn is_roblox_security_cookie(
243    name: &str,
244    domain: Option<&str>,
245    secure: Option<bool>,
246    http_only: Option<bool>,
247) -> bool {
248    if name != SECURITY_COOKIE_NAME || secure != Some(true) || http_only != Some(true) {
249        return false;
250    }
251    domain.is_some_and(|domain| {
252        let domain = domain.trim_start_matches('.').to_ascii_lowercase();
253        domain == "roblox.com" || domain.ends_with(".roblox.com")
254    })
255}
256
257/// Checks for the session cookie on a background thread, retrying every second until it's
258/// found, the window closes, or the sign-in fails.
259fn schedule_cookie_check(window: WebviewWindow, runtime: Arc<LoginRuntime>) {
260    if runtime.cancelled.load(Ordering::SeqCst) || runtime.in_flight.swap(true, Ordering::SeqCst) {
261        return;
262    }
263    runtime.set_phase(LoginPhase::Checking);
264
265    std::thread::spawn(move || {
266        let result = read_security_cookie(&window);
267        match result {
268            Ok(None) => {
269                runtime.set_phase(LoginPhase::Waiting);
270                runtime.in_flight.store(false, Ordering::SeqCst);
271                if !runtime.cancelled.load(Ordering::SeqCst) {
272                    std::thread::sleep(std::time::Duration::from_secs(1));
273                    schedule_cookie_check(window, runtime);
274                }
275            }
276            Ok(Some(cookie)) => finish_login(&window, &runtime, cookie),
277            Err(error) => fail_login(&window, &runtime, error),
278        }
279    });
280}
281
282/// Reads the session cookie from the window, if it's set.
283fn read_security_cookie(window: &WebviewWindow) -> Result<Option<RobloxCookie>, LoginError> {
284    let cookies = window.cookies().map_err(|_| LoginError::CookieRead)?;
285    Ok(cookies.into_iter().find_map(|cookie| {
286        is_roblox_security_cookie(
287            cookie.name(),
288            cookie.domain(),
289            cookie.secure(),
290            cookie.http_only(),
291        )
292        .then(|| RobloxCookie(Zeroizing::new(cookie.value().to_owned())))
293    }))
294}
295
296/// Validates and stores the session, clearing browsing data before storing it and closing the
297/// window afterwards.
298fn finish_login(window: &WebviewWindow, runtime: &LoginRuntime, cookie: RobloxCookie) {
299    if runtime.cancelled.load(Ordering::SeqCst) {
300        runtime.in_flight.store(false, Ordering::SeqCst);
301        return;
302    }
303
304    let identity = match (runtime.validate)(&cookie) {
305        Ok(identity) => identity,
306        Err(error) => {
307            fail_login(window, runtime, error);
308            return;
309        }
310    };
311
312    if window.clear_all_browsing_data().is_err() {
313        fail_login(window, runtime, LoginError::Cleanup);
314        return;
315    }
316    if runtime.cancelled.load(Ordering::SeqCst) {
317        let _ = window.destroy();
318        runtime.in_flight.store(false, Ordering::SeqCst);
319        return;
320    }
321    if (runtime.store)(&identity, &cookie).is_err() {
322        fail_login(window, runtime, LoginError::CredentialStore);
323        return;
324    }
325
326    runtime.set_phase(LoginPhase::Complete);
327    runtime.in_flight.store(false, Ordering::SeqCst);
328    let _ = window.destroy();
329    (runtime.notify)(LoginNotice::Complete(identity));
330}
331
332/// Marks the sign-in failed, clears browsing data, closes the window, and reports the error.
333fn fail_login(window: &WebviewWindow, runtime: &LoginRuntime, error: LoginError) {
334    runtime.set_phase(LoginPhase::Failed);
335    runtime.cancelled.store(true, Ordering::SeqCst);
336    runtime.in_flight.store(false, Ordering::SeqCst);
337    let _ = window.clear_all_browsing_data();
338    let _ = window.destroy();
339    (runtime.notify)(LoginNotice::Failed(error));
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345
346    #[test]
347    fn navigation_allows_only_https_roblox_hosts() {
348        assert!(is_allowed_roblox_navigation(
349            &"https://www.roblox.com/login".parse().unwrap()
350        ));
351        assert!(is_allowed_roblox_navigation(
352            &"https://auth.roblox.com/".parse().unwrap()
353        ));
354        assert!(!is_allowed_roblox_navigation(
355            &"http://www.roblox.com/login".parse().unwrap()
356        ));
357        assert!(!is_allowed_roblox_navigation(
358            &"https://roblox.com.example.test/".parse().unwrap()
359        ));
360        assert!(!is_allowed_roblox_navigation(
361            &"https://evilroblox.com/".parse().unwrap()
362        ));
363    }
364
365    #[test]
366    fn cookie_filter_requires_exact_name_security_flags_and_roblox_domain() {
367        assert!(is_roblox_security_cookie(
368            ".ROBLOSECURITY",
369            Some(".roblox.com"),
370            Some(true),
371            Some(true)
372        ));
373        assert!(!is_roblox_security_cookie(
374            ".ROBLOSECURITY",
375            Some("evilroblox.com"),
376            Some(true),
377            Some(true)
378        ));
379        assert!(!is_roblox_security_cookie(
380            ".ROBLOSECURITY",
381            Some(".roblox.com"),
382            Some(false),
383            Some(true)
384        ));
385        assert!(!is_roblox_security_cookie(
386            "session",
387            Some(".roblox.com"),
388            Some(true),
389            Some(true)
390        ));
391    }
392
393    crate::credentials::assert_not_impl!(
394        RobloxCookie: Clone,
395        std::fmt::Debug,
396        std::fmt::Display,
397        serde::Serialize
398    );
399
400    #[test]
401    fn cookie_secret_has_no_debug_or_serialized_representation() {
402        let cookie = RobloxCookie(Zeroizing::new("secret".to_owned()));
403        assert_eq!(cookie.expose_secret(), "secret");
404    }
405}