1use std::fmt::Write as _;
12use std::fs::{self, File, OpenOptions};
13use std::io::{self, Write as _};
14use std::path::{Path, PathBuf};
15use std::sync::{Mutex, OnceLock};
16use std::time::{SystemTime, UNIX_EPOCH};
17
18use log::{Level, LevelFilter, Log, Metadata, Record};
19
20use crate::credentials::SESSION_COOKIE_MARKER as COOKIE_MARKER;
21
22const FILE_NAME: &str = "toolblox.log";
24const MAX_FILE_BYTES: u64 = 1_000_000;
26const BACKUPS: usize = 3;
28pub const MAX_MESSAGE_BYTES: usize = 8 * 1024;
30pub const MAX_TAIL_LINES: usize = 2_000;
32const CRATE_ROOT: &str = "toolblox_lib";
34const CRATE_PREFIX: &str = "toolblox_lib::";
36
37pub const OWN_TARGETS: &[&str] = &["interface", "panic"];
39pub const WIDGET_TARGET_PREFIX: &str = "widget:";
41
42const REDACTED: &str = "[redacted]";
44
45const SECRET_KEYS: &[&str] = &[
48 ".roblosecurity",
49 "rbx-authentication-ticket",
50 "authentication-ticket",
51 "ticket",
52 "x-csrf-token",
53 "authorization",
54 "proxy-authorization",
55 "cookie",
56 "set-cookie",
57 "password",
58 "secret",
59 "token",
60 "access_token",
61 "refresh_token",
62 "api_key",
63 "apikey",
64];
65
66const WHOLE_VALUE_KEYS: &[&str] = &[
69 "authorization",
70 "proxy-authorization",
71 "cookie",
72 "set-cookie",
73];
74
75const LAUNCH_SCHEMES: &[&str] = &["roblox-player:", "roblox-studio:"];
77
78static LOGGER: OnceLock<FileLogger> = OnceLock::new();
79
80struct FileLogger {
82 directory: PathBuf,
83 file: Mutex<Option<File>>,
84}
85
86impl FileLogger {
87 fn path(&self) -> PathBuf {
88 self.directory.join(FILE_NAME)
89 }
90
91 fn append(&self, line: &str) {
92 let mut file = self.file.lock().unwrap_or_else(|error| error.into_inner());
93 let size = file
94 .as_ref()
95 .and_then(|file| file.metadata().ok())
96 .map_or(0, |metadata| metadata.len());
97 if file.is_none() || size + line.len() as u64 > MAX_FILE_BYTES {
98 *file = None;
99 if size > 0 {
100 rotate(&self.directory);
101 }
102 *file = open(&self.path()).ok();
103 }
104 if let Some(file) = file.as_mut() {
105 let _ = file.write_all(line.as_bytes());
106 }
107 }
108}
109
110impl Log for FileLogger {
111 fn enabled(&self, metadata: &Metadata) -> bool {
112 metadata.level() <= level_for(metadata.target())
113 }
114
115 fn log(&self, record: &Record) {
116 if self.enabled(record.metadata()) {
117 let message = record.args().to_string();
118 self.append(&format_line(
119 SystemTime::now(),
120 record.level(),
121 record.target(),
122 &message,
123 ));
124 }
125 }
126
127 fn flush(&self) {
128 if let Ok(mut file) = self.file.lock()
129 && let Some(file) = file.as_mut()
130 {
131 let _ = file.flush();
132 }
133 }
134}
135
136fn level_for(target: &str) -> LevelFilter {
138 let own = target == CRATE_ROOT
139 || target.starts_with(CRATE_PREFIX)
140 || OWN_TARGETS.contains(&target)
141 || target.starts_with(WIDGET_TARGET_PREFIX);
142 match (own, cfg!(debug_assertions)) {
143 (true, true) => LevelFilter::Debug,
144 (true, false) => LevelFilter::Info,
145 (false, _) => LevelFilter::Warn,
146 }
147}
148
149fn open(path: &Path) -> io::Result<File> {
151 OpenOptions::new().create(true).append(true).open(path)
152}
153
154fn rotate(directory: &Path) {
156 let numbered = |index: usize| directory.join(format!("{FILE_NAME}.{index}"));
157 let _ = fs::remove_file(numbered(BACKUPS));
158 for index in (1..BACKUPS).rev() {
159 let _ = fs::rename(numbered(index), numbered(index + 1));
160 }
161 let _ = fs::rename(directory.join(FILE_NAME), numbered(1));
162}
163
164pub fn init(directory: &Path) -> io::Result<()> {
166 fs::create_dir_all(directory)?;
167 let file = open(&directory.join(FILE_NAME))?;
168 let logger = LOGGER.get_or_init(|| FileLogger {
169 directory: directory.to_path_buf(),
170 file: Mutex::new(Some(file)),
171 });
172 if log::set_logger(logger).is_err() {
173 return Ok(());
174 }
175 log::set_max_level(LevelFilter::Debug);
176 let previous = std::panic::take_hook();
177 std::panic::set_hook(Box::new(move |info| {
178 let backtrace = std::backtrace::Backtrace::force_capture();
179 log::error!(target: "panic", "{info}\n{backtrace}");
180 log::logger().flush();
181 previous(info);
182 }));
183 Ok(())
184}
185
186pub fn directory() -> Option<&'static Path> {
188 LOGGER.get().map(|logger| logger.directory.as_path())
189}
190
191pub fn tail(lines: Option<usize>) -> Result<String, String> {
194 let directory = directory()
195 .ok_or_else(|| "Logging couldn't start. Is the data folder writable?".to_string())?;
196 tail_in(
197 directory,
198 lines.map_or(usize::MAX, |lines| lines.clamp(1, MAX_TAIL_LINES)),
199 )
200}
201
202fn tail_in(directory: &Path, lines: usize) -> Result<String, String> {
203 let files = std::iter::once(directory.join(FILE_NAME))
204 .chain((1..=BACKUPS).map(|index| directory.join(format!("{FILE_NAME}.{index}"))));
205 let mut collected: Vec<String> = Vec::new();
206 for path in files {
207 let bytes = match fs::read(&path) {
208 Ok(bytes) => bytes,
209 Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
210 Err(_) => {
211 return Err("The log couldn't be read. Is another program using it?".into());
212 }
213 };
214 let text = String::from_utf8_lossy(&bytes);
215 let mut older: Vec<String> = text
216 .lines()
217 .rev()
218 .take(lines - collected.len())
219 .map(str::to_owned)
220 .collect();
221 collected.append(&mut older);
222 if collected.len() >= lines {
223 break;
224 }
225 }
226 collected.reverse();
227 Ok(collected.join("\n"))
228}
229
230fn format_line(time: SystemTime, level: Level, target: &str, message: &str) -> String {
235 let target = if target == CRATE_ROOT {
236 "toolblox"
237 } else {
238 target.strip_prefix(CRATE_PREFIX).unwrap_or(target)
239 };
240 let mut message = redact(message);
241 if message.len() > MAX_MESSAGE_BYTES {
242 let mut end = MAX_MESSAGE_BYTES;
243 while !message.is_char_boundary(end) {
244 end -= 1;
245 }
246 message.truncate(end);
247 message.push_str(" [truncated]");
248 }
249 let mut line = format!(
250 "{} {:<5} {}: ",
251 timestamp(time),
252 level,
253 sanitize(&redact(target), false)
254 );
255 line.push_str(&sanitize(message.trim_end(), true));
256 line.push('\n');
257 line
258}
259
260fn sanitize(text: &str, multiline: bool) -> String {
262 let mut output = String::with_capacity(text.len());
263 for character in text.chars() {
264 match character {
265 '\n' if multiline => output.push_str("\n "),
266 '\r' if multiline => {}
267 '\t' => output.push(' '),
268 character if character.is_control() => {
269 let _ = write!(output, "\\u{{{:x}}}", character as u32);
270 }
271 character => output.push(character),
272 }
273 }
274 output
275}
276
277fn timestamp(time: SystemTime) -> String {
279 let elapsed = time.duration_since(UNIX_EPOCH).unwrap_or_default();
280 let seconds = elapsed.as_secs();
281 let (year, month, day) = civil_from_days((seconds / 86_400) as i64);
282 let remainder = seconds % 86_400;
283 format!(
284 "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
285 remainder / 3_600,
286 remainder % 3_600 / 60,
287 remainder % 60,
288 elapsed.subsec_millis()
289 )
290}
291
292fn civil_from_days(days: i64) -> (i64, u32, u32) {
294 let shifted = days + 719_468;
295 let era = shifted.div_euclid(146_097);
296 let day_of_era = shifted.rem_euclid(146_097);
297 let year_of_era =
298 (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
299 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
300 let month_index = (5 * day_of_year + 2) / 153;
301 let day = (day_of_year - (153 * month_index + 2) / 5 + 1) as u32;
302 let month = if month_index < 10 {
303 month_index + 3
304 } else {
305 month_index - 9
306 } as u32;
307 (year_of_era + era * 400 + i64::from(month <= 2), month, day)
308}
309
310pub fn redact(text: &str) -> String {
313 let lower = text.to_ascii_lowercase();
314 let bytes = text.as_bytes();
315 let mut output = String::with_capacity(text.len());
316 let mut copied = 0;
317 let mut index = 0;
318 while index < bytes.len() {
319 let Some((value_start, value_end)) = secret_at(&lower, bytes, index) else {
320 index += 1;
321 continue;
322 };
323 output.push_str(&text[copied..value_start]);
324 output.push_str(REDACTED);
325 copied = value_end;
326 index = value_end.max(index + 1);
327 }
328 output.push_str(&text[copied..]);
329 output
330}
331
332fn secret_at(lower: &str, bytes: &[u8], index: usize) -> Option<(usize, usize)> {
334 if !lower.is_char_boundary(index) {
335 return None;
336 }
337 let rest = &lower[index..];
338 if rest.starts_with(COOKIE_MARKER) {
339 return Some((index, value_end(bytes, index, false)));
340 }
341 let boundary = index == 0 || !is_word_byte(bytes[index - 1]);
342 if !boundary {
343 return None;
344 }
345 if let Some(scheme) = LAUNCH_SCHEMES
346 .iter()
347 .find(|scheme| rest.starts_with(**scheme))
348 {
349 let start = index + scheme.len();
350 let end = value_end(bytes, start, false);
351 return (end > start).then_some((start, end));
352 }
353 let key = SECRET_KEYS
354 .iter()
355 .filter(|key| rest.starts_with(**key))
356 .filter(|key| {
357 bytes
358 .get(index + key.len())
359 .is_none_or(|next| !is_word_byte(*next))
360 })
361 .max_by_key(|key| key.len())?;
362 let mut cursor = index + key.len();
363 if bytes.get(cursor) == Some(&b'"') {
364 cursor += 1;
365 }
366 cursor = skip_spaces(bytes, cursor);
367 if !matches!(bytes.get(cursor), Some(b'=' | b':')) {
368 return None;
369 }
370 cursor = skip_spaces(bytes, cursor + 1);
371 let quoted = bytes.get(cursor) == Some(&b'"');
372 if quoted {
373 cursor += 1;
374 }
375 let end = if quoted {
376 bytes[cursor..]
377 .iter()
378 .position(|byte| *byte == b'"' || *byte == b'\n')
379 .map_or(bytes.len(), |offset| cursor + offset)
380 } else {
381 value_end(bytes, cursor, WHOLE_VALUE_KEYS.contains(key))
382 };
383 (end > cursor && &lower[cursor..end] != REDACTED).then_some((cursor, end))
384}
385
386fn value_end(bytes: &[u8], start: usize, whole: bool) -> usize {
389 bytes[start..]
390 .iter()
391 .position(|byte| {
392 if whole {
393 matches!(byte, b'\n' | b'\r' | b'"' | b'\'')
394 } else {
395 byte.is_ascii_whitespace()
396 || matches!(byte, b';' | b',' | b'"' | b'\'' | b'&' | b'<' | b'>' | b'`')
397 }
398 })
399 .map_or(bytes.len(), |offset| start + offset)
400}
401
402fn skip_spaces(bytes: &[u8], mut cursor: usize) -> usize {
403 while bytes.get(cursor) == Some(&b' ') {
404 cursor += 1;
405 }
406 cursor
407}
408
409fn is_word_byte(byte: u8) -> bool {
410 byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.')
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416
417 const COOKIE: &str = "_|WARNING:-DO-NOT-SHARE-THIS.--Sharing-this-will-allow-someone-to-log-in-as-you-and-to-steal-your-ROBUX-and-items.|_ABCDEF0123";
418
419 #[test]
420 fn redacts_cookies_anywhere() {
421 let text = format!("bare {COOKIE} and quoted \"{COOKIE}\"");
422 let redacted = redact(&text);
423 assert!(!redacted.contains("ABCDEF0123"), "{redacted}");
424 assert_eq!(redacted, "bare [redacted] and quoted \"[redacted]\"");
425 assert_eq!(
426 redact(".ROBLOSECURITY=abc123; path=/"),
427 ".ROBLOSECURITY=[redacted]; path=/"
428 );
429 }
430
431 #[test]
432 fn redacts_headers_and_whole_cookie_values() {
433 assert_eq!(
434 redact("Authorization: Bearer abc.def"),
435 "Authorization: [redacted]"
436 );
437 assert_eq!(
438 redact("cookie: a=1; .ROBLOSECURITY=zzz\nnext"),
439 "cookie: [redacted]\nnext"
440 );
441 assert_eq!(
442 redact("rbx-authentication-ticket: T123 sent"),
443 "rbx-authentication-ticket: [redacted] sent"
444 );
445 assert_eq!(redact("x-csrf-token: abc"), "x-csrf-token: [redacted]");
446 }
447
448 #[test]
449 fn redacts_json_and_query_values() {
450 assert_eq!(
451 redact(r#"{"ticket": "T1", "token":"T2", "name":"ok"}"#),
452 r#"{"ticket": "[redacted]", "token":"[redacted]", "name":"ok"}"#
453 );
454 assert_eq!(
455 redact("https://example.com/?access_token=abc&page=2"),
456 "https://example.com/?access_token=[redacted]&page=2"
457 );
458 }
459
460 #[test]
461 fn redacts_launch_uris() {
462 assert_eq!(
463 redact("opening roblox-player:1+launchmode:play+gameinfo:T1+launchtime:5 now"),
464 "opening roblox-player:[redacted] now"
465 );
466 }
467
468 #[test]
469 fn leaves_ordinary_text_alone() {
470 for text in [
471 "Joined place 1818 as builderman",
472 "tokens are fine without a value",
473 "the ticket request failed",
474 "Couldn't reach Roblox: timeout",
475 "notoken=1 is a different key",
476 "café ☕ unicode",
477 ] {
478 assert_eq!(redact(text), text);
479 }
480 }
481
482 #[test]
483 fn lines_cannot_forge_records_or_leak_control_characters() {
484 let line = format_line(
485 UNIX_EPOCH,
486 Level::Warn,
487 "toolblox_lib::widgets",
488 "first\r\n2026-01-01T00:00:00.000Z ERROR fake: forged\u{1b}[31m",
489 );
490 assert_eq!(
491 line,
492 "1970-01-01T00:00:00.000Z WARN widgets: first\n 2026-01-01T00:00:00.000Z ERROR fake: forged\\u{1b}[31m\n"
493 );
494 }
495
496 #[test]
497 fn crate_root_records_are_labelled_toolblox() {
498 let line = format_line(UNIX_EPOCH, Level::Info, "toolblox_lib", "starting");
499 assert_eq!(line, "1970-01-01T00:00:00.000Z INFO toolblox: starting\n");
500 }
501
502 #[test]
503 fn long_messages_are_cut_on_a_character_boundary() {
504 let line = format_line(UNIX_EPOCH, Level::Info, "t", &"é".repeat(MAX_MESSAGE_BYTES));
505 assert!(line.ends_with(" [truncated]\n"));
506 assert!(line.len() < MAX_MESSAGE_BYTES + 100);
507 }
508
509 #[test]
510 fn timestamps_are_utc_dates() {
511 assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z");
512 let leap = UNIX_EPOCH + std::time::Duration::from_millis(951_782_400_123);
513 assert_eq!(timestamp(leap), "2000-02-29T00:00:00.123Z");
514 let later = UNIX_EPOCH + std::time::Duration::from_secs(1_790_294_399);
515 assert_eq!(timestamp(later), "2026-09-24T23:59:59.000Z");
516 }
517
518 #[test]
519 fn own_targets_are_kept_at_info_and_others_at_warn() {
520 assert!(level_for("toolblox_lib") >= LevelFilter::Info);
521 assert!(level_for("toolblox_lib::startup") >= LevelFilter::Info);
522 assert!(level_for("interface") >= LevelFilter::Info);
523 assert!(level_for("widget:rogue_lineage") >= LevelFilter::Info);
524 assert_eq!(level_for("tauri::manager"), LevelFilter::Warn);
525 assert_eq!(level_for("reqwest"), LevelFilter::Warn);
526 }
527
528 #[test]
529 fn rotates_and_tails_across_files() {
530 let directory = tempfile::tempdir().unwrap();
531 let logger = FileLogger {
532 directory: directory.path().to_path_buf(),
533 file: Mutex::new(None),
534 };
535 let line = format!("{}\n", "x".repeat(99_999));
536 for _ in 0..45 {
537 logger.append(&line);
538 }
539 logger.append("last\n");
540 let names = |index: usize| directory.path().join(format!("{FILE_NAME}.{index}"));
541 assert!(names(1).exists() && names(2).exists() && names(3).exists());
542 assert!(!names(4).exists());
543 for path in [directory.path().join(FILE_NAME), names(1)] {
544 assert!(fs::metadata(path).unwrap().len() <= MAX_FILE_BYTES);
545 }
546 let tail = tail_in(directory.path(), 12).unwrap();
547 let lines: Vec<_> = tail.lines().collect();
548 assert_eq!(lines.len(), 12);
549 assert_eq!(lines.last(), Some(&"last"));
550 let stored: usize = [
551 directory.path().join(FILE_NAME),
552 names(1),
553 names(2),
554 names(3),
555 ]
556 .iter()
557 .map(|path| fs::read_to_string(path).unwrap().lines().count())
558 .sum();
559 let all = tail_in(directory.path(), usize::MAX).unwrap();
560 assert_eq!(all.lines().count(), stored);
561 assert_eq!(all.lines().last(), Some("last"));
562 }
563
564 #[test]
565 fn records_reach_the_file_redacted_and_filtered() {
566 let directory = tempfile::tempdir().unwrap();
567 init(directory.path()).unwrap();
568 log::info!("joined with roblox-player:1+gameinfo:SECRET-TICKET+launchtime:1");
569 log::warn!(target: "widget:sample", "cookie: .ROBLOSECURITY=SECRET-COOKIE");
570 log::info!(target: "tauri::noise", "dropped below warn");
571 log::logger().flush();
572 let tail = tail(Some(10)).unwrap();
573 assert!(
574 tail.contains("INFO logs::tests: joined with roblox-player:[redacted]"),
575 "{tail}"
576 );
577 assert!(
578 tail.contains("WARN widget:sample: cookie: [redacted]"),
579 "{tail}"
580 );
581 assert!(
582 !tail.contains("SECRET") && !tail.contains("dropped"),
583 "{tail}"
584 );
585 }
586
587 #[test]
588 fn tail_of_a_missing_log_is_empty() {
589 let directory = tempfile::tempdir().unwrap();
590 assert_eq!(tail_in(directory.path(), 10).unwrap(), "");
591 }
592}