Skip to main content

toolblox_lib/
lib.rs

1//! Toolblox native host.
2//!
3//! Toolblox is a Tauri 2 desktop app for managing and launching Roblox accounts. This crate owns
4//! everything that touches secrets, the network, the file system, or other processes. The React
5//! interface receives display data and opaque IDs only.
6//!
7//! # Modules
8//!
9//! - [`app_commands`]: the Tauri commands the interface calls, and the shared [`Runtime`].
10//! - [`startup`] and [`update`]: the fail-closed update gate that runs before the app opens.
11//! - [`storage`] and [`models`]: validated, atomic JSON persistence for settings and accounts.
12//! - [`credentials`]: Roblox sessions in Windows Credential Manager or the macOS Keychain.
13//! - [`login`]: the isolated Roblox sign-in window.
14//! - [`roblox`]: Roblox web APIs for profiles, presence, games, and join tickets.
15//! - [`auto_rejoin`]: presence monitoring for drop notifications and auto-rejoin.
16//! - [`multi_instance`]: running several Roblox clients on Windows and macOS.
17//! - [`roblox_process`]: running Roblox client processes.
18//! - [`lifecycle`]: window, tray, and single-instance behavior.
19//! - [`logs`]: the rotating, redacted log file.
20//! - [`widgets`], [`widget_protocol`], [`widget_ipc`], and [`widget_process`]: signed widget
21//!   packages, their assets, permission-checked messages, and sidecar processes.
22//!
23//! # Data
24//!
25//! Data lives in the Toolblox data folder: `%LOCALAPPDATA%\Toolblox` on Windows and
26//! `~/Library/Application Support/Toolblox` on macOS.
27
28#![allow(rustdoc::private_intra_doc_links)]
29
30mod app_commands;
31mod auto_rejoin;
32mod credentials;
33mod lifecycle;
34mod login;
35mod logs;
36mod models;
37mod multi_instance;
38mod roblox;
39mod roblox_process;
40mod startup;
41mod storage;
42mod theme;
43mod update;
44mod widget_ipc;
45mod widget_process;
46mod widget_protocol;
47mod widgets;
48
49use std::path::PathBuf;
50use std::sync::{Arc, Mutex};
51
52use app_commands::Runtime;
53use lifecycle::LifecycleState;
54use tauri::Manager;
55
56/// Returns the Toolblox data folder.
57///
58/// This is `%LOCALAPPDATA%\Toolblox` on Windows and `~/Library/Application Support/Toolblox` on
59/// macOS. Debug builds use `TOOLBLOX_DATA_DIR` instead when it's set.
60fn toolblox_data_root() -> Result<PathBuf, std::io::Error> {
61    #[cfg(debug_assertions)]
62    if let Some(path) = std::env::var_os("TOOLBLOX_DATA_DIR") {
63        return Ok(PathBuf::from(path));
64    }
65    #[cfg(windows)]
66    let base = std::env::var_os("LOCALAPPDATA")
67        .map(PathBuf::from)
68        .or_else(|| {
69            std::env::var_os("USERPROFILE").map(|home| PathBuf::from(home).join("AppData/Local"))
70        });
71    #[cfg(target_os = "macos")]
72    let base = std::env::var_os("HOME")
73        .map(|home| PathBuf::from(home).join("Library/Application Support"));
74    #[cfg(not(any(windows, target_os = "macos")))]
75    let base = std::env::var_os("XDG_DATA_HOME")
76        .map(PathBuf::from)
77        .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".local/share")));
78    base.map(|path| path.join("Toolblox")).ok_or_else(|| {
79        std::io::Error::new(
80            std::io::ErrorKind::NotFound,
81            "Toolblox couldn't locate its data folder. Is the user profile available?",
82        )
83    })
84}
85
86/// Moves data that 0.2.0 beta saved in a `v2` subfolder into the data folder.
87///
88/// Moved entries replace same-named ones already in the data folder. An interrupted move
89/// continues on the next launch, and nothing happens once the subfolder is gone.
90fn move_beta_data(data_root: &std::path::Path) -> std::io::Result<()> {
91    let beta_root = data_root.join("v2");
92    let entries = match std::fs::read_dir(&beta_root) {
93        Ok(entries) => entries,
94        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
95        Err(error) => return Err(error),
96    };
97    for entry in entries {
98        let entry = entry?;
99        let target = data_root.join(entry.file_name());
100        match std::fs::symlink_metadata(&target) {
101            Ok(metadata) if metadata.is_dir() => std::fs::remove_dir_all(&target)?,
102            Ok(_) => std::fs::remove_file(&target)?,
103            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
104            Err(error) => return Err(error),
105        }
106        std::fs::rename(entry.path(), target)?;
107    }
108    std::fs::remove_dir(beta_root)
109}
110
111/// Name of the marker file that requests safe mode for the next launch.
112const SAFE_MODE_MARKER: &str = "safe-mode-next-launch";
113
114/// Records whether the next launch skips widgets. Failures only lose the one-time request.
115pub fn set_safe_mode_marker(data_root: &std::path::Path, enabled: bool) {
116    let marker = data_root.join(SAFE_MODE_MARKER);
117    let _ = if enabled {
118        std::fs::create_dir_all(data_root).and_then(|_| std::fs::write(marker, b""))
119    } else {
120        std::fs::remove_file(marker)
121    };
122}
123
124/// Safe mode applies for this launch when requested with `--safe-mode` or by the marker, which is
125/// consumed so the following launch loads widgets again.
126fn take_safe_mode(data_root: &std::path::Path) -> bool {
127    let marker = std::fs::remove_file(data_root.join(SAFE_MODE_MARKER)).is_ok();
128    marker || std::env::args().any(|argument| argument == "--safe-mode")
129}
130
131/// Builds and runs the Tauri application.
132#[cfg_attr(mobile, tauri::mobile_entry_point)]
133pub fn run() {
134    let lifecycle_state = Arc::new(LifecycleState::default());
135    let single_instance_state = Arc::clone(&lifecycle_state);
136    tauri::Builder::default()
137        .plugin(tauri_plugin_single_instance::init(move |app, _, _| {
138            lifecycle::activate_or_defer(app, &single_instance_state);
139        }))
140        .plugin(tauri_plugin_opener::init())
141        .plugin(tauri_plugin_notification::init())
142        .plugin(tauri_plugin_updater::Builder::new().build())
143        .register_uri_scheme_protocol("widget", widget_protocol::response)
144        .setup(move |app| {
145            app.handle().plugin(tauri_plugin_autostart::init(
146                tauri_plugin_autostart::MacosLauncher::LaunchAgent,
147                None,
148            ))?;
149
150            let data_root = toolblox_data_root()?;
151            let moved = move_beta_data(&data_root);
152            let widgets_root = data_root.join("widgets");
153            let safe_mode = take_safe_mode(&data_root);
154            let _ = logs::init(&data_root.join("logs"));
155            log::info!(
156                "Toolblox {} ({}) starting on {} {}{}",
157                env!("CARGO_PKG_VERSION"),
158                if cfg!(debug_assertions) {
159                    "debug"
160                } else {
161                    "release"
162                },
163                std::env::consts::OS,
164                std::env::consts::ARCH,
165                if safe_mode { " in safe mode" } else { "" }
166            );
167            if let Err(error) = moved {
168                log::error!("Moving data from the 0.2.0 beta folder failed: {error}");
169            }
170            let storage = Arc::new(storage::Storage::new(data_root.clone()));
171            let updated = semver::Version::parse(env!("CARGO_PKG_VERSION"))
172                .map_err(|error| error.to_string())
173                .and_then(|version| {
174                    storage
175                        .record_version(&version)
176                        .map_err(|error| error.to_string())
177                })
178                .unwrap_or_else(|error| {
179                    log::error!("Recording the Toolblox version failed: {error}");
180                    false
181                });
182            let credentials = Arc::new(credentials::OsCredentialStore);
183            let client = reqwest::Client::builder()
184                .https_only(true)
185                .redirect(reqwest::redirect::Policy::none())
186                .timeout(std::time::Duration::from_secs(20))
187                .user_agent(concat!("Toolblox/", env!("CARGO_PKG_VERSION")))
188                .build()?;
189            let processes = Arc::new(Mutex::new(widget_process::WidgetProcessManager::default()));
190            let runtime = Runtime {
191                storage,
192                credentials,
193                client,
194                widgets_root,
195                catalogue: Mutex::new(None),
196                catalogue_error: Mutex::new(None),
197                catalogue_checked: Mutex::new(None),
198                processes: Arc::clone(&processes),
199                widget_sessions: Mutex::new(widget_ipc::WidgetSessions::default()),
200                multi_instance_helper: Some(
201                    app.path()
202                        .resource_dir()?
203                        .join("resources/multi-instance/multi_instance_helper.exe"),
204                ),
205                cleared_roblox_pids: Mutex::new(Default::default()),
206                expired_sessions: Mutex::new(Default::default()),
207                join_generation: Default::default(),
208                cancelled_joins: Mutex::new(Default::default()),
209                safe_mode,
210                updated: updated.into(),
211            };
212            app.manage(runtime);
213            app.manage(Arc::clone(&lifecycle_state));
214            app.manage(startup::StartupState::new());
215
216            #[cfg(debug_assertions)]
217            {
218                use tauri::Emitter;
219                let sync_app = app.handle().clone();
220                std::thread::spawn(move || {
221                    let mut seen = std::collections::HashMap::new();
222                    loop {
223                        if app_commands::sync_local_widgets(&sync_app.state::<Runtime>(), &mut seen)
224                        {
225                            let _ = sync_app.emit(app_commands::WIDGETS_CHANGED, ());
226                        }
227                        std::thread::sleep(std::time::Duration::from_secs(1));
228                    }
229                });
230            }
231
232            let before_quit = Arc::new(move || {
233                if let Ok(mut processes) = processes.lock() {
234                    processes.stop_all();
235                }
236            });
237            lifecycle::install_tray(app.handle(), Arc::clone(&lifecycle_state), before_quit)?;
238
239            if let Some(window) = app.get_webview_window(lifecycle::MAIN_WINDOW_LABEL) {
240                let close_state = Arc::clone(&lifecycle_state);
241                let close_window = window.clone();
242                window.on_window_event(move |event| {
243                    if let tauri::WindowEvent::CloseRequested { api, .. } = event {
244                        let app = close_window.app_handle();
245                        let startup_ready = matches!(
246                            app.state::<startup::StartupState>().view(),
247                            startup::StartupView::Ready
248                        );
249                        let run_in_background = startup_ready
250                            && app
251                                .state::<Runtime>()
252                                .storage
253                                .load_settings()
254                                .map(|settings| settings.run_in_background)
255                                .unwrap_or(false);
256                        if matches!(
257                            lifecycle::handle_close_request(
258                                &close_window,
259                                api,
260                                &close_state,
261                                run_in_background,
262                            ),
263                            Ok(lifecycle::CloseDecision::Exit)
264                        ) {
265                            app.exit(0);
266                        }
267                    }
268                });
269            }
270
271            if let Some(window) = app.get_webview_window(lifecycle::MAIN_WINDOW_LABEL) {
272                window.show()?;
273                lifecycle::apply_pending_activation(app.handle(), &lifecycle_state)?;
274            }
275            tauri::async_runtime::spawn(startup::run(app.handle().clone()));
276            let services_app = app.handle().clone();
277            tauri::async_runtime::spawn(async move {
278                startup::wait_until_ready(&services_app).await;
279                #[cfg(not(debug_assertions))]
280                {
281                    use tauri_plugin_autostart::ManagerExt;
282
283                    let runtime = services_app.state::<Runtime>();
284                    if let Ok(settings) = runtime.storage.load_settings() {
285                        let autostart = services_app.autolaunch();
286                        if autostart.is_enabled().ok() != Some(settings.open_on_launch) {
287                            let _ = if settings.open_on_launch {
288                                autostart.enable()
289                            } else {
290                                autostart.disable()
291                            };
292                        }
293                    }
294                }
295                let always_on_top = services_app
296                    .state::<Runtime>()
297                    .storage
298                    .load_settings()
299                    .is_ok_and(|settings| settings.always_on_top);
300                if always_on_top
301                    && let Some(window) =
302                        services_app.get_webview_window(lifecycle::MAIN_WINDOW_LABEL)
303                {
304                    let _ = window.set_always_on_top(true);
305                }
306                app_commands::backfill_profiles(&services_app.state::<Runtime>()).await;
307                app_commands::check_sessions(&services_app.state::<Runtime>()).await;
308                auto_rejoin::run(services_app).await;
309            });
310            Ok(())
311        })
312        .invoke_handler(tauri::generate_handler![
313            app_commands::get_app_state,
314            app_commands::take_updated,
315            app_commands::begin_roblox_login,
316            app_commands::update_account_notes,
317            app_commands::set_account_place,
318            app_commands::set_account_pinned,
319            app_commands::place_exists,
320            app_commands::search_places,
321            app_commands::get_online_friends,
322            app_commands::search_players,
323            app_commands::get_relationship,
324            app_commands::change_relationship,
325            app_commands::open_roblox_profile,
326            app_commands::forget_recent_place,
327            app_commands::get_widget_store,
328            app_commands::set_widget_store,
329            app_commands::restart_app,
330            app_commands::snap_window,
331            app_commands::set_mini_window,
332            app_commands::start_window_drag,
333            app_commands::show_notification,
334            app_commands::remove_account,
335            app_commands::join_accounts,
336            app_commands::cancel_join,
337            app_commands::reorder_accounts,
338            app_commands::save_settings,
339            app_commands::install_widget,
340            app_commands::set_widget_enabled,
341            app_commands::update_widget,
342            app_commands::uninstall_widget,
343            app_commands::retry_catalogue,
344            app_commands::open_widget,
345            app_commands::close_widget_session,
346            app_commands::open_widget_popout,
347            app_commands::close_widget_popout,
348            app_commands::widget_request,
349            app_commands::read_log,
350            app_commands::open_log_folder,
351            app_commands::open_data_folder,
352            app_commands::close_all_clients,
353            app_commands::write_log,
354            app_commands::get_theme,
355            app_commands::save_theme,
356            app_commands::embed_theme_files,
357            app_commands::export_theme,
358            startup::startup_status,
359            startup::retry_startup_update,
360            startup::quit_startup,
361        ])
362        .build(tauri::generate_context!())
363        .expect("Toolblox couldn't start")
364        .run(|app, event| {
365            #[cfg(target_os = "macos")]
366            if matches!(event, tauri::RunEvent::Reopen { .. }) {
367                lifecycle::activate_or_defer(
368                    app,
369                    app.state::<Arc<LifecycleState>>().inner().as_ref(),
370                );
371            }
372            if matches!(event, tauri::RunEvent::Exit) {
373                if let Ok(mut processes) = app.state::<Runtime>().processes.lock() {
374                    processes.stop_all();
375                }
376                log::info!("Toolblox exited");
377                log::logger().flush();
378            }
379        });
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385
386    /// Module widgets share the main webview and widget popouts, so their permissions and network
387    /// policy are pinned. Widening them needs security review: no permission may create or script
388    /// webviews, read cookies, or reach the network outside IPC.
389    #[test]
390    fn webview_permissions_match_the_reviewed_list() {
391        let capability: serde_json::Value =
392            serde_json::from_str(include_str!("../capabilities/default.json")).unwrap();
393        assert_eq!(
394            capability["permissions"],
395            serde_json::json!(["core:default", "opener:default"])
396        );
397        assert_eq!(
398            capability["windows"],
399            serde_json::json!(["main", "popout-*"])
400        );
401        let capabilities = std::fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/capabilities"))
402            .unwrap()
403            .count();
404        assert_eq!(capabilities, 1);
405
406        let config: serde_json::Value =
407            serde_json::from_str(include_str!("../tauri.conf.json")).unwrap();
408        let security = &config["app"]["security"];
409        assert_eq!(security["capabilities"], serde_json::json!(["default"]));
410        let connect = security["csp"]
411            .as_str()
412            .unwrap()
413            .split(';')
414            .map(str::trim)
415            .find(|directive| directive.starts_with("connect-src"));
416        assert_eq!(connect, Some("connect-src ipc: http://ipc.localhost"));
417    }
418
419    #[test]
420    fn beta_data_moves_up_and_replaces_older_entries() {
421        let root = tempfile::tempdir().unwrap();
422        let data = root.path();
423        std::fs::create_dir_all(data.join("v2/logs")).unwrap();
424        std::fs::create_dir_all(data.join("logs")).unwrap();
425        std::fs::write(data.join("v2/accounts.json"), "new").unwrap();
426        std::fs::write(data.join("v2/logs/toolblox.log"), "new").unwrap();
427        std::fs::write(data.join("accounts.json"), "old").unwrap();
428        std::fs::write(data.join("logs/old.log"), "old").unwrap();
429        std::fs::write(data.join("notes.txt"), "kept").unwrap();
430
431        move_beta_data(data).unwrap();
432
433        assert!(!data.join("v2").exists());
434        assert_eq!(
435            std::fs::read_to_string(data.join("accounts.json")).unwrap(),
436            "new"
437        );
438        assert!(data.join("logs/toolblox.log").exists());
439        assert!(!data.join("logs/old.log").exists());
440        assert!(data.join("notes.txt").exists());
441        move_beta_data(data).unwrap();
442        assert_eq!(
443            std::fs::read_to_string(data.join("accounts.json")).unwrap(),
444            "new"
445        );
446    }
447
448    #[test]
449    fn safe_mode_marker_applies_to_one_launch() {
450        let root = tempfile::tempdir().unwrap();
451        set_safe_mode_marker(root.path(), true);
452        assert!(take_safe_mode(root.path()));
453        assert!(!take_safe_mode(root.path()));
454        set_safe_mode_marker(root.path(), true);
455        set_safe_mode_marker(root.path(), false);
456        assert!(!take_safe_mode(root.path()));
457    }
458}