1use 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
12pub const LOGIN_WINDOW_LABEL: &str = "roblox-login";
14pub const LOGIN_URL: &str = "https://www.roblox.com/login";
16const SECURITY_COOKIE_NAME: &str = ".ROBLOSECURITY";
18
19pub struct RobloxCookie(Zeroizing<String>);
21
22impl RobloxCookie {
23 pub fn expose_secret(&self) -> &str {
25 self.0.as_str()
26 }
27}
28
29#[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#[derive(Clone, Debug, Eq, PartialEq)]
41pub enum LoginPhase {
42 Waiting,
44 Checking,
46 Complete,
47 Cancelled,
48 Failed,
49}
50
51#[derive(Clone, Debug, Eq, PartialEq)]
53pub enum LoginError {
54 AlreadyOpen,
55 Window,
56 CookieRead,
57 Network,
58 InvalidSession,
59 CredentialStore,
60 Cleanup,
61 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#[derive(Clone, Debug, Eq, PartialEq)]
90pub enum LoginNotice {
91 Complete(AccountIdentity),
92 Failed(LoginError),
93 Cancelled,
94}
95
96type ValidateSession =
98 dyn Fn(&RobloxCookie) -> Result<AccountIdentity, LoginError> + Send + Sync + 'static;
99type StoreSession =
101 dyn Fn(&AccountIdentity, &RobloxCookie) -> Result<(), LoginError> + Send + Sync + 'static;
102type Notify = dyn Fn(LoginNotice) + Send + Sync + 'static;
104
105struct LoginRuntime {
107 in_flight: AtomicBool,
109 cancelled: AtomicBool,
111 phase: Mutex<LoginPhase>,
112 validate: Arc<ValidateSession>,
113 store: Arc<StoreSession>,
114 notify: Arc<Notify>,
115}
116
117impl LoginRuntime {
118 fn set_phase(&self, phase: LoginPhase) {
120 *self.phase.lock().unwrap_or_else(|error| error.into_inner()) = phase;
121 }
122}
123
124pub 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
190pub const PROFILE_WINDOW_LABEL: &str = "roblox-profile";
192
193pub 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
232pub 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
241pub 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
257fn 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
282fn 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
296fn 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
332fn 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}