1#![deny(missing_docs)]
2#![cfg_attr(not(debug_assertions), allow(unused_imports, dead_code))]
7pub mod bridge;
46#[cfg(feature = "sqlite")]
48pub mod database;
49pub mod error;
50pub mod js_bridge;
52pub mod mcp;
54mod memory;
55pub mod privacy;
57
58pub mod filmstrip;
60pub mod redaction;
62pub mod screencast;
63pub(crate) mod screenshot;
64mod tools;
65
66pub mod auth;
68pub mod introspection;
70
71use std::collections::{HashMap, HashSet};
72use std::sync::Arc;
73use std::sync::atomic::{AtomicBool, AtomicU16, AtomicU64};
74use tauri::plugin::{Builder, TauriPlugin};
75use tauri::{Listener, Manager, RunEvent, Runtime};
76use tokio::sync::{Mutex, oneshot, watch};
77use victauri_core::{CommandRegistry, EventLog, EventRecorder};
78
79pub use error::BuilderError;
80pub use privacy::PrivacyProfile;
81
82pub use victauri_core::CommandInfo;
83pub use victauri_macros::inspectable;
84
85#[macro_export]
106macro_rules! register_commands {
107 ($app:expr, $($schema_call:expr),+ $(,)?) => {{
108 if let Some(state) = $app.try_state::<std::sync::Arc<$crate::VictauriState>>() {
112 $(
113 state.registry.register($schema_call);
114 )+
115 }
116 }};
117}
118
119const DEFAULT_PORT: u16 = 7373;
120const DEFAULT_EVENT_CAPACITY: usize = 10_000;
121const DEFAULT_RECORDER_CAPACITY: usize = 50_000;
122const DEFAULT_EVAL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
123const MAX_EVENT_CAPACITY: usize = 1_000_000;
124const MAX_RECORDER_CAPACITY: usize = 1_000_000;
125const MAX_EVAL_TIMEOUT_SECS: u64 = 300;
126
127pub type PendingCallbacks = Arc<Mutex<HashMap<String, oneshot::Sender<String>>>>;
130
131pub struct VictauriState {
133 pub event_log: EventLog,
135 pub registry: CommandRegistry,
137 pub port: AtomicU16,
139 pub pending_evals: PendingCallbacks,
141 pub recorder: EventRecorder,
143 pub privacy: privacy::PrivacyConfig,
145 pub eval_timeout: std::time::Duration,
147 pub shutdown_tx: watch::Sender<bool>,
149 pub started_at: std::time::Instant,
151 pub tool_invocations: AtomicU64,
153 pub allow_file_navigation: bool,
157 pub command_timings: introspection::CommandTimings,
159 pub fault_registry: introspection::FaultRegistry,
161 pub contract_store: introspection::ContractStore,
163 pub startup_timeline: introspection::StartupTimeline,
165 pub event_bus: introspection::EventBusMonitor,
167 pub task_tracker: introspection::TaskTracker,
169 pub bridge_ready: AtomicBool,
171 pub bridge_notify: tokio::sync::Notify,
173 pub screencast: Arc<screencast::Screencast>,
175 pub db_search_paths: Vec<std::path::PathBuf>,
182 pub probes: introspection::AppStateProbes,
185}
186
187pub struct VictauriBuilder {
199 port: Option<u16>,
200 event_capacity: usize,
201 recorder_capacity: usize,
202 eval_timeout: std::time::Duration,
203 auth_token: Option<String>,
204 auth_explicitly_enabled: bool,
205 auth_explicitly_disabled: bool,
206 disabled_tools: Vec<String>,
207 command_allowlist: Option<Vec<String>>,
208 command_blocklist: Vec<String>,
209 storage_key_blocklist: Vec<String>,
210 redaction_patterns: Vec<String>,
211 redaction_enabled: bool,
212 strict_privacy: bool,
213 privacy_profile: Option<privacy::PrivacyProfile>,
214 bridge_capacities: js_bridge::BridgeCapacities,
215 on_ready: Option<Box<dyn FnOnce(u16) + Send + 'static>>,
216 commands: Vec<victauri_core::CommandInfo>,
217 allow_file_navigation: bool,
218 listen_events: Vec<String>,
219 db_search_paths: Vec<std::path::PathBuf>,
220 probes: Vec<(String, std::sync::Arc<introspection::ProbeFn>)>,
221}
222
223impl Default for VictauriBuilder {
224 fn default() -> Self {
225 Self {
226 port: None,
227 event_capacity: DEFAULT_EVENT_CAPACITY,
228 recorder_capacity: DEFAULT_RECORDER_CAPACITY,
229 eval_timeout: DEFAULT_EVAL_TIMEOUT,
230 auth_token: None,
231 auth_explicitly_enabled: false,
232 auth_explicitly_disabled: false,
233 disabled_tools: Vec::new(),
234 command_allowlist: None,
235 command_blocklist: Vec::new(),
236 storage_key_blocklist: Vec::new(),
237 redaction_patterns: Vec::new(),
238 redaction_enabled: false,
239 strict_privacy: false,
240 privacy_profile: None,
241 bridge_capacities: js_bridge::BridgeCapacities::default(),
242 on_ready: None,
243 commands: Vec::new(),
244 allow_file_navigation: false,
245 listen_events: Vec::new(),
246 db_search_paths: Vec::new(),
247 probes: Vec::new(),
248 }
249 }
250}
251
252impl VictauriBuilder {
253 #[must_use]
255 pub fn new() -> Self {
256 Self::default()
257 }
258
259 #[must_use]
261 pub fn port(mut self, port: u16) -> Self {
262 self.port = Some(port);
263 self
264 }
265
266 #[must_use]
268 pub fn event_capacity(mut self, capacity: usize) -> Self {
269 self.event_capacity = capacity;
270 self
271 }
272
273 #[must_use]
275 pub fn recorder_capacity(mut self, capacity: usize) -> Self {
276 self.recorder_capacity = capacity;
277 self
278 }
279
280 #[must_use]
282 pub fn eval_timeout(mut self, timeout: std::time::Duration) -> Self {
283 self.eval_timeout = timeout;
284 self
285 }
286
287 #[must_use]
291 pub fn auth_token(mut self, token: impl Into<String>) -> Self {
292 self.auth_token = Some(token.into());
293 self
294 }
295
296 #[must_use]
304 pub fn auth_enabled(mut self) -> Self {
305 self.auth_explicitly_enabled = true;
306 self
307 }
308
309 #[must_use]
311 pub fn generate_auth_token(mut self) -> Self {
312 self.auth_explicitly_enabled = true;
313 self
314 }
315
316 #[must_use]
326 pub fn auth_disabled(mut self) -> Self {
327 self.auth_explicitly_disabled = true;
328 self
329 }
330
331 #[must_use]
333 pub fn disable_tools(mut self, tools: &[&str]) -> Self {
334 self.disabled_tools = tools.iter().map(std::string::ToString::to_string).collect();
335 self
336 }
337
338 #[must_use]
340 pub fn command_allowlist(mut self, commands: &[&str]) -> Self {
341 self.command_allowlist = Some(
342 commands
343 .iter()
344 .map(std::string::ToString::to_string)
345 .collect(),
346 );
347 self
348 }
349
350 #[must_use]
352 pub fn command_blocklist(mut self, commands: &[&str]) -> Self {
353 self.command_blocklist = commands
354 .iter()
355 .map(std::string::ToString::to_string)
356 .collect();
357 self
358 }
359
360 #[must_use]
365 pub fn storage_key_blocklist(mut self, keys: &[&str]) -> Self {
366 self.storage_key_blocklist = keys.iter().map(std::string::ToString::to_string).collect();
367 self
368 }
369
370 #[must_use]
372 pub fn add_redaction_pattern(mut self, pattern: impl Into<String>) -> Self {
373 self.redaction_patterns.push(pattern.into());
374 self
375 }
376
377 #[must_use]
379 pub fn enable_redaction(mut self) -> Self {
380 self.redaction_enabled = true;
381 self
382 }
383
384 #[must_use]
391 pub fn strict_privacy_mode(mut self) -> Self {
392 self.strict_privacy = true;
393 self.privacy_profile = Some(privacy::PrivacyProfile::Observe);
394 self
395 }
396
397 #[must_use]
406 pub fn privacy_profile(mut self, profile: privacy::PrivacyProfile) -> Self {
407 self.privacy_profile = Some(profile);
408 if matches!(
409 profile,
410 privacy::PrivacyProfile::Observe | privacy::PrivacyProfile::Test
411 ) {
412 self.redaction_enabled = true;
413 }
414 self
415 }
416
417 #[must_use]
419 pub fn console_log_capacity(mut self, capacity: usize) -> Self {
420 self.bridge_capacities.console_logs = capacity;
421 self
422 }
423
424 #[must_use]
426 pub fn network_log_capacity(mut self, capacity: usize) -> Self {
427 self.bridge_capacities.network_log = capacity;
428 self
429 }
430
431 #[must_use]
433 pub fn navigation_log_capacity(mut self, capacity: usize) -> Self {
434 self.bridge_capacities.navigation_log = capacity;
435 self
436 }
437
438 #[must_use]
453 pub fn commands(mut self, schemas: &[victauri_core::CommandInfo]) -> Self {
454 self.commands = schemas.to_vec();
455 self
456 }
457
458 #[must_use]
474 pub fn register_command_names(mut self, names: &[&str]) -> Self {
475 self.commands
476 .extend(names.iter().map(|n| victauri_core::CommandInfo::new(*n)));
477 self
478 }
479
480 #[must_use]
496 pub fn auto_discover(mut self) -> Self {
497 self.commands
498 .extend(victauri_core::auto_discovered_commands());
499 self
500 }
501
502 #[must_use]
513 pub fn listen_events(mut self, events: &[&str]) -> Self {
514 self.listen_events = events
515 .iter()
516 .map(std::string::ToString::to_string)
517 .collect();
518 self
519 }
520
521 #[must_use]
530 pub fn allow_file_navigation(mut self) -> Self {
531 self.allow_file_navigation = true;
532 self
533 }
534
535 #[must_use]
548 pub fn db_search_paths<I, P>(mut self, paths: I) -> Self
549 where
550 I: IntoIterator<Item = P>,
551 P: Into<std::path::PathBuf>,
552 {
553 self.db_search_paths
554 .extend(paths.into_iter().map(Into::into));
555 self
556 }
557
558 #[must_use]
582 pub fn probe<F>(mut self, name: impl Into<String>, probe: F) -> Self
583 where
584 F: Fn() -> serde_json::Value + Send + Sync + 'static,
585 {
586 self.probes.push((name.into(), std::sync::Arc::new(probe)));
587 self
588 }
589
590 #[must_use]
593 pub fn on_ready(mut self, f: impl FnOnce(u16) + Send + 'static) -> Self {
594 self.on_ready = Some(Box::new(f));
595 self
596 }
597
598 fn resolve_port(&self) -> u16 {
599 self.port
600 .or_else(|| std::env::var("VICTAURI_PORT").ok()?.parse().ok())
601 .unwrap_or(DEFAULT_PORT)
602 }
603
604 fn resolve_auth_token(&self) -> Option<String> {
605 if self.auth_explicitly_disabled {
606 return None;
607 }
608 if let Some(ref token) = self.auth_token
614 && !token.trim().is_empty()
615 {
616 return Some(token.clone());
617 }
618 if let Ok(token) = std::env::var("VICTAURI_AUTH_TOKEN")
619 && !token.trim().is_empty()
620 {
621 return Some(token);
622 }
623 Some(auth::generate_token())
624 }
625
626 fn resolve_eval_timeout(&self) -> std::time::Duration {
627 std::env::var("VICTAURI_EVAL_TIMEOUT")
628 .ok()
629 .and_then(|s| s.parse::<u64>().ok())
630 .map_or(self.eval_timeout, std::time::Duration::from_secs)
631 }
632
633 fn build_privacy_config(&self) -> privacy::PrivacyConfig {
634 let profile = self
635 .privacy_profile
636 .unwrap_or(privacy::PrivacyProfile::FullControl);
637
638 let redaction_enabled = self.redaction_enabled
639 || self.strict_privacy
640 || matches!(
641 profile,
642 privacy::PrivacyProfile::Observe | privacy::PrivacyProfile::Test
643 );
644
645 privacy::PrivacyConfig {
646 profile,
647 command_allowlist: self
648 .command_allowlist
649 .as_ref()
650 .map(|v| v.iter().cloned().collect::<HashSet<String>>()),
651 command_blocklist: self.command_blocklist.iter().cloned().collect(),
652 disabled_tools: self.disabled_tools.iter().cloned().collect(),
653 storage_key_blocklist: self.storage_key_blocklist.iter().cloned().collect(),
654 redactor: redaction::Redactor::new(&self.redaction_patterns),
655 redaction_enabled,
656 }
657 }
658
659 fn validate(&self) -> Result<(), BuilderError> {
660 let port = self.resolve_port();
661 if port == 0 {
662 return Err(BuilderError::InvalidPort {
663 port,
664 reason: "port 0 is reserved".to_string(),
665 });
666 }
667
668 if self.event_capacity == 0 || self.event_capacity > MAX_EVENT_CAPACITY {
669 return Err(BuilderError::InvalidEventCapacity {
670 capacity: self.event_capacity,
671 reason: format!("must be between 1 and {MAX_EVENT_CAPACITY}"),
672 });
673 }
674
675 if self.recorder_capacity == 0 || self.recorder_capacity > MAX_RECORDER_CAPACITY {
676 return Err(BuilderError::InvalidRecorderCapacity {
677 capacity: self.recorder_capacity,
678 reason: format!("must be between 1 and {MAX_RECORDER_CAPACITY}"),
679 });
680 }
681
682 let timeout = self.resolve_eval_timeout();
683 if timeout.as_secs() == 0 || timeout.as_secs() > MAX_EVAL_TIMEOUT_SECS {
684 return Err(BuilderError::InvalidEvalTimeout {
685 timeout_secs: timeout.as_secs(),
686 reason: format!("must be between 1 and {MAX_EVAL_TIMEOUT_SECS} seconds"),
687 });
688 }
689
690 Ok(())
691 }
692
693 pub fn build<R: Runtime>(self) -> Result<TauriPlugin<R>, BuilderError> {
703 #[cfg(not(debug_assertions))]
704 {
705 Ok(Builder::new("victauri").build())
706 }
707
708 #[cfg(debug_assertions)]
709 {
710 if env_truthy("VICTAURI_DISABLE") {
714 tracing::info!("Victauri disabled via VICTAURI_DISABLE — returning no-op plugin");
715 return Ok(Builder::new("victauri").build());
716 }
717
718 self.validate()?;
719
720 let port = self.resolve_port();
721 let event_capacity = self.event_capacity;
722 let recorder_capacity = self.recorder_capacity;
723 let eval_timeout = self.resolve_eval_timeout();
724 let auth_token = self.resolve_auth_token();
725 let privacy_config = self.build_privacy_config();
726 let allow_file_navigation = self.allow_file_navigation;
727 let db_search_paths = self.db_search_paths;
728 let on_ready = self.on_ready;
729 let commands = self.commands;
730 let listen_events = self.listen_events;
731 let probes = self.probes;
732 let js_init = js_bridge::init_script(&self.bridge_capacities);
733
734 Ok(Builder::new("victauri")
735 .setup(move |app, _api| {
736 let startup_timeline = introspection::StartupTimeline::new();
737 let event_log = EventLog::new(event_capacity);
738 startup_timeline.mark("event_log_created");
739 let registry = CommandRegistry::new();
740 startup_timeline.mark("registry_created");
741 let (shutdown_tx, shutdown_rx) = watch::channel(false);
742
743 let state = Arc::new(VictauriState {
744 event_log,
745 registry,
746 port: AtomicU16::new(port),
747 pending_evals: Arc::new(Mutex::new(HashMap::new())),
748 recorder: EventRecorder::new(recorder_capacity),
749 privacy: privacy_config,
750 eval_timeout,
751 shutdown_tx,
752 started_at: std::time::Instant::now(),
753 tool_invocations: AtomicU64::new(0),
754 allow_file_navigation,
755 command_timings: introspection::CommandTimings::new(),
756 fault_registry: introspection::FaultRegistry::new(),
757 contract_store: introspection::ContractStore::new(),
758 startup_timeline,
759 event_bus: introspection::EventBusMonitor::default(),
760 task_tracker: introspection::TaskTracker::new(),
761 bridge_ready: AtomicBool::new(false),
762 bridge_notify: tokio::sync::Notify::new(),
763 screencast: Arc::new(screencast::Screencast::default()),
764 db_search_paths,
765 probes: introspection::AppStateProbes::default(),
766 });
767 state.startup_timeline.mark("state_created");
768
769 for (name, probe) in probes {
770 state.probes.register(name, probe);
771 }
772
773 app.manage(state.clone());
774
775 for cmd in commands {
776 state.registry.register(cmd);
777 }
778 state.startup_timeline.mark("commands_registered");
779
780 for event_name in &listen_events {
782 let bus = state.event_bus.clone();
783 let name = event_name.clone();
784 app.listen_any(event_name.clone(), move |event| {
785 let payload =
786 serde_json::from_str::<serde_json::Value>(event.payload())
787 .map_or_else(
788 |_| event.payload().to_string(),
789 |v| v.to_string(),
790 );
791 bus.push(introspection::CapturedTauriEvent {
792 name: name.clone(),
793 payload,
794 timestamp: chrono::Utc::now()
795 .to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
796 });
797 });
798 }
799 state
800 .startup_timeline
801 .mark("event_bus_listeners_registered");
802
803 if let Some(ref token) = auth_token {
804 let prefix_len = token.len().min(8);
805 let suffix_start = token.len().saturating_sub(4);
806 tracing::info!(
807 "Victauri MCP server auth enabled — token: {}…{}",
808 &token[..prefix_len],
809 &token[suffix_start..]
810 );
811 } else {
812 tracing::warn!(
813 "Victauri MCP server running WITHOUT auth — any localhost process can \
814 access all tools. Use VictauriBuilder::auth_enabled() or set \
815 VICTAURI_AUTH_TOKEN for shared/CI environments."
816 );
817 }
818
819 state.startup_timeline.mark("server_spawning");
820 let app_handle = app.clone();
821 let ready_state = state.clone();
822 let server_finished = state.task_tracker.track("mcp_server");
823 tauri::async_runtime::spawn(async move {
824 match mcp::start_server_with_options(
825 app_handle,
826 state,
827 port,
828 auth_token,
829 shutdown_rx,
830 )
831 .await
832 {
833 Ok(()) => {
834 tracing::info!("Victauri MCP server stopped");
835 }
836 Err(e) => {
837 tracing::error!("Victauri MCP server failed: {e}");
838 }
839 }
840 server_finished.store(true, std::sync::atomic::Ordering::Relaxed);
841 });
842
843 if let Some(cb) = on_ready {
844 let ready_finished = ready_state.task_tracker.track("on_ready_probe");
845 tauri::async_runtime::spawn(async move {
846 for _ in 0..50 {
847 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
848 let actual_port =
849 ready_state.port.load(std::sync::atomic::Ordering::Relaxed);
850 if tokio::net::TcpStream::connect(format!(
851 "127.0.0.1:{actual_port}"
852 ))
853 .await
854 .is_ok()
855 {
856 cb(actual_port);
857 ready_finished
858 .store(true, std::sync::atomic::Ordering::Relaxed);
859 return;
860 }
861 }
862 let actual_port =
863 ready_state.port.load(std::sync::atomic::Ordering::Relaxed);
864 tracing::warn!(
865 "Victauri on_ready: server did not become ready within 5s"
866 );
867 cb(actual_port);
868 ready_finished.store(true, std::sync::atomic::Ordering::Relaxed);
869 });
870 }
871
872 emit_security_banner(port);
873 Ok(())
874 })
875 .on_event(|app, event| {
876 let Some(state) = app.try_state::<Arc<VictauriState>>() else {
877 return;
878 };
879 match event {
880 RunEvent::Exit => {
881 let _ = state.shutdown_tx.send(true);
882 tracing::info!("Victauri shutdown signal sent");
883 }
884 RunEvent::ExitRequested { .. } => {
885 state.event_bus.push(introspection::CapturedTauriEvent {
886 name: "tauri://exit-requested".to_string(),
887 payload: String::new(),
888 timestamp: chrono::Utc::now()
889 .to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
890 });
891 }
892 RunEvent::WindowEvent {
893 label,
894 event: win_event,
895 ..
896 } => {
897 let (name, payload) = format_window_event(label, win_event);
898 state.event_bus.push(introspection::CapturedTauriEvent {
899 name,
900 payload,
901 timestamp: chrono::Utc::now()
902 .to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
903 });
904 }
905 _ => {}
906 }
907 })
908 .js_init_script(js_init)
909 .invoke_handler(tauri::generate_handler![
910 tools::victauri_eval_js,
911 tools::victauri_eval_callback,
912 tools::victauri_get_window_state,
913 tools::victauri_list_windows,
914 tools::victauri_get_ipc_log,
915 tools::victauri_get_registry,
916 tools::victauri_get_memory_stats,
917 tools::victauri_dom_snapshot,
918 tools::victauri_verify_state,
919 tools::victauri_detect_ghost_commands,
920 tools::victauri_check_ipc_integrity,
921 ])
922 .build())
923 }
924 }
925}
926
927#[cfg(debug_assertions)]
928fn format_window_event(label: &str, event: &tauri::WindowEvent) -> (String, String) {
929 match event {
930 tauri::WindowEvent::Resized(size) => (
931 format!("window:{label}:resized"),
932 serde_json::json!({"width": size.width, "height": size.height}).to_string(),
933 ),
934 tauri::WindowEvent::Moved(pos) => (
935 format!("window:{label}:moved"),
936 serde_json::json!({"x": pos.x, "y": pos.y}).to_string(),
937 ),
938 tauri::WindowEvent::CloseRequested { .. } => {
939 (format!("window:{label}:close-requested"), String::new())
940 }
941 tauri::WindowEvent::Destroyed => (format!("window:{label}:destroyed"), String::new()),
942 tauri::WindowEvent::Focused(focused) => (
943 format!("window:{label}:focused"),
944 serde_json::json!({"focused": focused}).to_string(),
945 ),
946 tauri::WindowEvent::ScaleFactorChanged { scale_factor, .. } => (
947 format!("window:{label}:scale-factor-changed"),
948 serde_json::json!({"scale_factor": scale_factor}).to_string(),
949 ),
950 tauri::WindowEvent::ThemeChanged(theme) => (
951 format!("window:{label}:theme-changed"),
952 serde_json::json!({"theme": format!("{theme:?}")}).to_string(),
953 ),
954 tauri::WindowEvent::DragDrop(drag_event) => (
955 format!("window:{label}:drag-drop"),
956 format!("{drag_event:?}"),
957 ),
958 _ => (format!("window:{label}:other"), format!("{event:?}")),
959 }
960}
961
962#[cfg(debug_assertions)]
966fn env_truthy(name: &str) -> bool {
967 std::env::var(name).is_ok_and(|v| {
968 matches!(
969 v.trim().to_ascii_lowercase().as_str(),
970 "1" | "true" | "yes" | "on"
971 )
972 })
973}
974
975#[cfg(debug_assertions)]
984fn emit_security_banner(port: u16) {
985 tracing::warn!(
986 "┌─ VICTAURI INTROSPECTION SERVER ACTIVE ─────────────────────────────\n\
987 │ Listening on http://127.0.0.1:{port} — exposes JS eval, IPC, the\n\
988 │ filesystem, and SQLite to local clients. DEBUG-ONLY developer tool;\n\
989 │ it must never reach end users.\n\
990 │ Seeing this in a shipped/release build means your release profile has\n\
991 │ `debug-assertions = true`. Turn that off, or hard-disable Victauri\n\
992 │ with the VICTAURI_DISABLE=1 environment variable.\n\
993 └────────────────────────────────────────────────────────────────────"
994 );
995}
996
997#[must_use]
1017pub fn init<R: Runtime>() -> TauriPlugin<R> {
1018 VictauriBuilder::new()
1019 .build()
1020 .expect("default Victauri configuration is always valid")
1021}
1022
1023#[must_use]
1032pub fn init_auto_discover<R: Runtime>() -> TauriPlugin<R> {
1033 VictauriBuilder::new()
1034 .auto_discover()
1035 .build()
1036 .expect("default Victauri configuration is always valid")
1037}
1038
1039#[cfg(test)]
1040mod tests {
1041 use super::*;
1042
1043 #[test]
1044 fn builder_default_values() {
1045 let builder = VictauriBuilder::new();
1046 assert_eq!(builder.event_capacity, DEFAULT_EVENT_CAPACITY);
1047 assert_eq!(builder.recorder_capacity, DEFAULT_RECORDER_CAPACITY);
1048 assert!(builder.auth_token.is_none());
1049 assert!(!builder.auth_explicitly_enabled);
1050 assert!(!builder.auth_explicitly_disabled);
1051 let resolved = builder.resolve_auth_token();
1052 assert!(
1053 resolved.is_some(),
1054 "auth should be enabled by default (auto-generated token)"
1055 );
1056 assert_eq!(
1057 resolved.unwrap().len(),
1058 36,
1059 "auto-generated token should be UUID v4"
1060 );
1061 assert!(builder.disabled_tools.is_empty());
1062 assert!(builder.command_allowlist.is_none());
1063 assert!(builder.command_blocklist.is_empty());
1064 assert!(!builder.redaction_enabled);
1065 assert!(!builder.strict_privacy);
1066 }
1067
1068 #[test]
1069 fn builder_port_override() {
1070 let builder = VictauriBuilder::new().port(9090);
1071 assert_eq!(builder.resolve_port(), 9090);
1072 }
1073
1074 #[test]
1075 #[allow(unsafe_code)]
1076 fn builder_default_port() {
1077 let builder = VictauriBuilder::new();
1078 unsafe { std::env::remove_var("VICTAURI_PORT") };
1080 assert_eq!(builder.resolve_port(), DEFAULT_PORT);
1081 }
1082
1083 #[test]
1084 fn builder_auth_token_explicit() {
1085 let builder = VictauriBuilder::new().auth_token("my-secret");
1086 assert_eq!(builder.resolve_auth_token(), Some("my-secret".to_string()));
1087 }
1088
1089 #[cfg(debug_assertions)]
1093 #[test]
1094 #[allow(unsafe_code)]
1095 fn env_truthy_recognizes_kill_switch_values() {
1096 let key = "VICTAURI_TEST_KILL_SWITCH";
1098 unsafe { std::env::remove_var(key) };
1100 assert!(!env_truthy(key), "unset should be false");
1101
1102 for v in ["1", "true", "TRUE", " yes ", "On"] {
1103 unsafe { std::env::set_var(key, v) };
1105 assert!(env_truthy(key), "{v:?} should be truthy");
1106 }
1107 for v in ["0", "false", "", "nope"] {
1108 unsafe { std::env::set_var(key, v) };
1110 assert!(!env_truthy(key), "{v:?} should be falsy");
1111 }
1112 unsafe { std::env::remove_var(key) };
1114 }
1115
1116 #[test]
1117 fn builder_auth_enabled() {
1118 let builder = VictauriBuilder::new().auth_enabled();
1119 assert!(builder.auth_explicitly_enabled);
1120 let token = builder.resolve_auth_token().unwrap();
1121 assert_eq!(token.len(), 36, "auto-generated token should be a UUID");
1122 }
1123
1124 #[test]
1125 fn builder_auth_generate_token() {
1126 let builder = VictauriBuilder::new().generate_auth_token();
1127 let token = builder.resolve_auth_token().unwrap();
1128 assert_eq!(token.len(), 36);
1129 }
1130
1131 #[test]
1132 fn builder_auth_disabled_suppresses_default_token() {
1133 let builder = VictauriBuilder::new().auth_disabled();
1134 assert!(
1135 builder.resolve_auth_token().is_none(),
1136 "auth_disabled must suppress the default auto-generated token (auth is ON by default)"
1137 );
1138 }
1139
1140 #[test]
1141 fn builder_auth_disabled_returns_none() {
1142 let builder = VictauriBuilder::new().auth_disabled();
1143 assert!(
1144 builder.resolve_auth_token().is_none(),
1145 "auth_disabled should suppress auto-generated token"
1146 );
1147 }
1148
1149 #[test]
1150 fn builder_auth_disabled_overrides_explicit_token() {
1151 let builder = VictauriBuilder::new()
1152 .auth_token("my-secret")
1153 .auth_disabled();
1154 assert!(
1155 builder.resolve_auth_token().is_none(),
1156 "auth_disabled should override explicit token"
1157 );
1158 }
1159
1160 #[test]
1161 fn builder_empty_explicit_token_does_not_disable_auth() {
1162 for blank in ["", " ", "\t\n"] {
1165 let resolved = VictauriBuilder::new()
1166 .auth_token(blank)
1167 .resolve_auth_token();
1168 assert!(
1169 resolved.as_deref().is_some_and(|t| !t.trim().is_empty()),
1170 "empty explicit token {blank:?} must resolve to a generated token, not no-auth"
1171 );
1172 }
1173 }
1174
1175 #[test]
1176 fn builder_capacities() {
1177 let builder = VictauriBuilder::new()
1178 .event_capacity(500)
1179 .recorder_capacity(2000);
1180 assert_eq!(builder.event_capacity, 500);
1181 assert_eq!(builder.recorder_capacity, 2000);
1182 }
1183
1184 #[test]
1185 fn builder_disable_tools() {
1186 let builder = VictauriBuilder::new().disable_tools(&["eval_js", "screenshot"]);
1187 assert_eq!(builder.disabled_tools.len(), 2);
1188 assert!(builder.disabled_tools.contains(&"eval_js".to_string()));
1189 }
1190
1191 #[test]
1192 fn builder_command_allowlist() {
1193 let builder = VictauriBuilder::new().command_allowlist(&["greet", "increment"]);
1194 assert!(builder.command_allowlist.is_some());
1195 assert_eq!(builder.command_allowlist.as_ref().unwrap().len(), 2);
1196 }
1197
1198 #[test]
1199 fn builder_command_blocklist() {
1200 let builder = VictauriBuilder::new().command_blocklist(&["dangerous_cmd"]);
1201 assert_eq!(builder.command_blocklist.len(), 1);
1202 }
1203
1204 #[test]
1205 fn builder_redaction() {
1206 let builder = VictauriBuilder::new()
1207 .add_redaction_pattern(r"SECRET_\w+")
1208 .enable_redaction();
1209 assert!(builder.redaction_enabled);
1210 assert_eq!(builder.redaction_patterns.len(), 1);
1211 }
1212
1213 #[test]
1214 fn builder_strict_privacy_config() {
1215 let builder = VictauriBuilder::new().strict_privacy_mode();
1216 let config = builder.build_privacy_config();
1217 assert!(config.redaction_enabled);
1218 assert_eq!(config.profile, crate::privacy::PrivacyProfile::Observe);
1219 assert!(!config.is_tool_enabled("eval_js"));
1220 assert!(!config.is_tool_enabled("screenshot"));
1221 assert!(!config.is_tool_enabled("interact"));
1222 assert!(config.is_tool_enabled("dom_snapshot"));
1223 }
1224
1225 #[test]
1226 fn builder_normal_privacy_config() {
1227 let builder = VictauriBuilder::new()
1228 .command_blocklist(&["secret_cmd"])
1229 .disable_tools(&["eval_js"]);
1230 let config = builder.build_privacy_config();
1231 assert!(config.command_blocklist.contains("secret_cmd"));
1232 assert!(!config.is_tool_enabled("eval_js"));
1233 assert!(!config.redaction_enabled);
1234 }
1235
1236 #[test]
1237 fn builder_strict_with_extra_blocklist() {
1238 let builder = VictauriBuilder::new()
1239 .strict_privacy_mode()
1240 .command_blocklist(&["extra_dangerous"]);
1241 let config = builder.build_privacy_config();
1242 assert!(config.command_blocklist.contains("extra_dangerous"));
1243 assert!(!config.is_tool_enabled("eval_js"));
1244 }
1245
1246 #[test]
1247 fn builder_test_profile() {
1248 let builder = VictauriBuilder::new().privacy_profile(crate::privacy::PrivacyProfile::Test);
1249 let config = builder.build_privacy_config();
1250 assert_eq!(config.profile, crate::privacy::PrivacyProfile::Test);
1251 assert!(config.redaction_enabled);
1252 assert!(config.is_tool_enabled("interact"));
1253 assert!(config.is_tool_enabled("fill"));
1254 assert!(config.is_tool_enabled("recording"));
1255 assert!(!config.is_tool_enabled("eval_js"));
1256 assert!(!config.is_tool_enabled("screenshot"));
1257 assert!(!config.is_tool_enabled("navigate.go_to"));
1260 }
1261
1262 #[test]
1263 fn builder_profile_with_extra_disables() {
1264 let builder = VictauriBuilder::new()
1265 .privacy_profile(crate::privacy::PrivacyProfile::Test)
1266 .disable_tools(&["interact"]);
1267 let config = builder.build_privacy_config();
1268 assert!(!config.is_tool_enabled("interact"));
1269 assert!(config.is_tool_enabled("fill"));
1270 }
1271
1272 #[test]
1273 fn builder_bridge_capacities() {
1274 let builder = VictauriBuilder::new()
1275 .console_log_capacity(5000)
1276 .network_log_capacity(2000)
1277 .navigation_log_capacity(500);
1278 assert_eq!(builder.bridge_capacities.console_logs, 5000);
1279 assert_eq!(builder.bridge_capacities.network_log, 2000);
1280 assert_eq!(builder.bridge_capacities.navigation_log, 500);
1281 assert_eq!(builder.bridge_capacities.mutation_log, 500);
1282 assert_eq!(builder.bridge_capacities.dialog_log, 100);
1283 }
1284
1285 #[test]
1286 fn builder_on_ready_sets_callback() {
1287 let builder = VictauriBuilder::new().on_ready(|_port| {});
1288 assert!(builder.on_ready.is_some());
1289 }
1290
1291 #[test]
1292 fn builder_file_navigation_disabled_by_default() {
1293 let builder = VictauriBuilder::new();
1294 assert!(
1295 !builder.allow_file_navigation,
1296 "file navigation should be disabled by default"
1297 );
1298 }
1299
1300 #[test]
1301 fn builder_allow_file_navigation() {
1302 let builder = VictauriBuilder::new().allow_file_navigation();
1303 assert!(builder.allow_file_navigation);
1304 }
1305
1306 #[test]
1307 fn builder_listen_events() {
1308 let builder =
1309 VictauriBuilder::new().listen_events(&["notification-added", "settings-changed"]);
1310 assert_eq!(builder.listen_events.len(), 2);
1311 assert!(
1312 builder
1313 .listen_events
1314 .contains(&"notification-added".to_string())
1315 );
1316 assert!(
1317 builder
1318 .listen_events
1319 .contains(&"settings-changed".to_string())
1320 );
1321 }
1322
1323 #[test]
1324 fn builder_listen_events_empty_by_default() {
1325 let builder = VictauriBuilder::new();
1326 assert!(builder.listen_events.is_empty());
1327 }
1328
1329 #[test]
1330 fn init_script_contains_custom_capacities() {
1331 let caps = js_bridge::BridgeCapacities {
1332 console_logs: 3000,
1333 mutation_log: 750,
1334 network_log: 5000,
1335 navigation_log: 400,
1336 dialog_log: 250,
1337 long_tasks: 200,
1338 };
1339 let script = js_bridge::init_script(&caps);
1340 assert!(script.contains("CAP_CONSOLE = 3000"));
1341 assert!(script.contains("CAP_MUTATION = 750"));
1342 assert!(script.contains("CAP_NETWORK = 5000"));
1343 assert!(script.contains("CAP_NAVIGATION = 400"));
1344 assert!(script.contains("CAP_DIALOG = 250"));
1345 assert!(script.contains("CAP_LONG_TASKS = 200"));
1346 }
1347
1348 #[test]
1349 fn init_script_default_contains_standard_capacities() {
1350 let caps = js_bridge::BridgeCapacities::default();
1351 let script = js_bridge::init_script(&caps);
1352 assert!(script.contains("CAP_CONSOLE = 1000"));
1353 assert!(script.contains("CAP_NETWORK = 1000"));
1354 assert!(script.contains("window.__VICTAURI__"));
1355 }
1356
1357 #[test]
1358 fn builder_validates_defaults() {
1359 let builder = VictauriBuilder::new();
1360 assert!(builder.validate().is_ok());
1361 }
1362
1363 #[test]
1364 fn builder_rejects_zero_port() {
1365 let builder = VictauriBuilder::new().port(0);
1366 let err = builder.validate().unwrap_err();
1367 assert!(matches!(err, BuilderError::InvalidPort { port: 0, .. }));
1368 }
1369
1370 #[test]
1371 fn builder_rejects_zero_event_capacity() {
1372 let builder = VictauriBuilder::new().event_capacity(0);
1373 let err = builder.validate().unwrap_err();
1374 assert!(matches!(
1375 err,
1376 BuilderError::InvalidEventCapacity { capacity: 0, .. }
1377 ));
1378 }
1379
1380 #[test]
1381 fn builder_rejects_excessive_event_capacity() {
1382 let builder = VictauriBuilder::new().event_capacity(2_000_000);
1383 assert!(builder.validate().is_err());
1384 }
1385
1386 #[test]
1387 fn builder_rejects_zero_recorder_capacity() {
1388 let builder = VictauriBuilder::new().recorder_capacity(0);
1389 assert!(builder.validate().is_err());
1390 }
1391
1392 #[test]
1393 fn builder_rejects_zero_eval_timeout() {
1394 let builder = VictauriBuilder::new().eval_timeout(std::time::Duration::from_secs(0));
1395 assert!(builder.validate().is_err());
1396 }
1397
1398 #[test]
1399 fn builder_rejects_excessive_eval_timeout() {
1400 let builder = VictauriBuilder::new().eval_timeout(std::time::Duration::from_secs(600));
1401 assert!(builder.validate().is_err());
1402 }
1403
1404 #[test]
1405 fn builder_accepts_edge_values() {
1406 let builder = VictauriBuilder::new()
1407 .port(1)
1408 .event_capacity(1)
1409 .recorder_capacity(1)
1410 .eval_timeout(std::time::Duration::from_secs(1));
1411 assert!(builder.validate().is_ok());
1412
1413 let builder = VictauriBuilder::new()
1414 .port(65535)
1415 .event_capacity(MAX_EVENT_CAPACITY)
1416 .recorder_capacity(MAX_RECORDER_CAPACITY)
1417 .eval_timeout(std::time::Duration::from_secs(MAX_EVAL_TIMEOUT_SECS));
1418 assert!(builder.validate().is_ok());
1419 }
1420}