1use std::sync::Arc;
2use std::sync::atomic::Ordering;
3
4use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
5use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
6use tauri::Runtime;
7
8use crate::VictauriState;
9use crate::bridge::WebviewBridge;
10
11use super::{MAX_PENDING_EVALS, VictauriMcpHandler};
12
13const DEFAULT_WEBVIEW_LABEL: &str = "main";
14
15pub fn build_app(state: Arc<VictauriState>, bridge: Arc<dyn WebviewBridge>) -> axum::Router {
19 build_app_with_options(state, bridge, None)
20}
21
22pub fn build_app_with_options(
24 state: Arc<VictauriState>,
25 bridge: Arc<dyn WebviewBridge>,
26 auth_token: Option<String>,
27) -> axum::Router {
28 build_app_full(state, bridge, auth_token, None)
29}
30
31pub fn build_app_full(
33 state: Arc<VictauriState>,
34 bridge: Arc<dyn WebviewBridge>,
35 auth_token: Option<String>,
36 rate_limiter: Option<Arc<crate::auth::RateLimiterState>>,
37) -> axum::Router {
38 let handler = VictauriMcpHandler::new(state.clone(), bridge);
39
40 let mcp_service = StreamableHttpService::new(
41 move || Ok(handler.clone()),
42 Arc::new(LocalSessionManager::default()),
43 StreamableHttpServerConfig::default(),
44 );
45
46 let auth_state = Arc::new(crate::auth::AuthState {
47 token: auth_token.clone(),
48 });
49 let info_state = state.clone();
50 let info_auth = auth_token.is_some();
51
52 let privacy_enabled = !state.privacy.disabled_tools.is_empty()
53 || state.privacy.command_allowlist.is_some()
54 || !state.privacy.command_blocklist.is_empty()
55 || state.privacy.redaction_enabled;
56
57 let mut router = axum::Router::new()
58 .route_service("/mcp", mcp_service)
59 .route(
60 "/info",
61 axum::routing::get(move || {
62 let s = info_state.clone();
63 async move {
64 axum::Json(serde_json::json!({
65 "name": "victauri",
66 "version": env!("CARGO_PKG_VERSION"),
67 "protocol": "mcp",
68 "commands_registered": s.registry.count(),
69 "events_captured": s.event_log.len(),
70 "port": s.port.load(Ordering::Relaxed),
71 "auth_required": info_auth,
72 "privacy_mode": privacy_enabled,
73 }))
74 }
75 }),
76 );
77
78 if auth_token.is_some() {
79 router = router.layer(axum::middleware::from_fn_with_state(
80 auth_state,
81 crate::auth::require_auth,
82 ));
83 }
84
85 let limiter = rate_limiter.unwrap_or_else(crate::auth::default_rate_limiter);
86 router = router.layer(axum::middleware::from_fn_with_state(
87 limiter,
88 crate::auth::rate_limit,
89 ));
90
91 router
92 .route(
93 "/health",
94 axum::routing::get(|| async { axum::Json(serde_json::json!({"status": "ok"})) }),
95 )
96 .layer(axum::middleware::from_fn(crate::auth::security_headers))
97 .layer(axum::middleware::from_fn(crate::auth::origin_guard))
98 .layer(axum::middleware::from_fn(crate::auth::dns_rebinding_guard))
99}
100
101#[doc(hidden)]
102#[allow(dead_code)]
103pub mod tests_support {
104 #[must_use]
106 pub fn get_memory_stats() -> serde_json::Value {
107 crate::memory::current_stats()
108 }
109}
110
111const PORT_FALLBACK_RANGE: u16 = 10;
112
113pub async fn start_server<R: Runtime>(
120 app_handle: tauri::AppHandle<R>,
121 state: Arc<VictauriState>,
122 port: u16,
123 shutdown_rx: tokio::sync::watch::Receiver<bool>,
124) -> anyhow::Result<()> {
125 start_server_with_options(app_handle, state, port, None, shutdown_rx).await
126}
127
128pub async fn start_server_with_options<R: Runtime>(
135 app_handle: tauri::AppHandle<R>,
136 state: Arc<VictauriState>,
137 port: u16,
138 auth_token: Option<String>,
139 mut shutdown_rx: tokio::sync::watch::Receiver<bool>,
140) -> anyhow::Result<()> {
141 let bridge: Arc<dyn WebviewBridge> = Arc::new(app_handle);
142 let token_for_file = auth_token.clone();
143 let app = build_app_with_options(state.clone(), bridge.clone(), auth_token);
144
145 let (listener, actual_port) = try_bind(port).await?;
146
147 if actual_port != port {
148 tracing::warn!("Victauri: port {port} in use, fell back to {actual_port}");
149 }
150
151 state.port.store(actual_port, Ordering::Relaxed);
152 write_port_file(actual_port);
153 if let Some(ref token) = token_for_file {
154 write_token_file(token);
155 }
156
157 tracing::info!("Victauri MCP server listening on 127.0.0.1:{actual_port}");
158
159 let drain_state = state.clone();
160 let drain_bridge = bridge;
161 let drain_shutdown = state.shutdown_tx.subscribe();
162 tokio::spawn(event_drain_loop(drain_state, drain_bridge, drain_shutdown));
163
164 axum::serve(listener, app)
165 .with_graceful_shutdown(async move {
166 let _ = shutdown_rx.wait_for(|&v| v).await;
167 remove_port_file();
168 tracing::info!("Victauri MCP server shutting down gracefully");
169 })
170 .await?;
171 Ok(())
172}
173
174async fn try_bind(preferred: u16) -> anyhow::Result<(tokio::net::TcpListener, u16)> {
175 if let Ok(listener) = tokio::net::TcpListener::bind(format!("127.0.0.1:{preferred}")).await {
176 return Ok((listener, preferred));
177 }
178
179 for offset in 1..=PORT_FALLBACK_RANGE {
180 let port = preferred + offset;
181 if let Ok(listener) = tokio::net::TcpListener::bind(format!("127.0.0.1:{port}")).await {
182 return Ok((listener, port));
183 }
184 }
185
186 anyhow::bail!(
187 "could not bind to any port in range {preferred}-{}",
188 preferred + PORT_FALLBACK_RANGE
189 )
190}
191
192fn port_file_path() -> std::path::PathBuf {
193 std::env::temp_dir().join("victauri.port")
194}
195
196fn token_file_path() -> std::path::PathBuf {
197 std::env::temp_dir().join("victauri.token")
198}
199
200fn write_port_file(port: u16) {
201 if let Err(e) = std::fs::write(port_file_path(), port.to_string()) {
202 tracing::debug!("could not write port file: {e}");
203 }
204}
205
206fn write_token_file(token: &str) {
207 if let Err(e) = std::fs::write(token_file_path(), token) {
208 tracing::debug!("could not write token file: {e}");
209 }
210}
211
212fn remove_port_file() {
213 let _ = std::fs::remove_file(port_file_path());
214 let _ = std::fs::remove_file(token_file_path());
215}
216
217#[must_use]
221pub fn parse_bridge_event(ev: &serde_json::Value) -> Option<victauri_core::AppEvent> {
222 use chrono::Utc;
223 use victauri_core::AppEvent;
224
225 let event_type = ev.get("type").and_then(|t| t.as_str()).unwrap_or("");
226 let now = Utc::now();
227
228 let app_event = match event_type {
229 "console" => AppEvent::StateChange {
230 key: format!(
231 "console.{}",
232 ev.get("level").and_then(|l| l.as_str()).unwrap_or("log")
233 ),
234 timestamp: now,
235 caused_by: ev
236 .get("message")
237 .and_then(|m| m.as_str())
238 .map(std::string::ToString::to_string),
239 },
240 "dom_mutation" => AppEvent::DomMutation {
241 webview_label: DEFAULT_WEBVIEW_LABEL.to_string(),
242 timestamp: now,
243 mutation_count: ev
244 .get("count")
245 .and_then(serde_json::Value::as_u64)
246 .unwrap_or(0) as u32,
247 },
248 "ipc" => {
249 let cmd = ev
250 .get("command")
251 .and_then(|c| c.as_str())
252 .unwrap_or("unknown");
253 AppEvent::Ipc(victauri_core::IpcCall {
254 id: uuid::Uuid::new_v4().to_string(),
255 command: cmd.to_string(),
256 timestamp: now,
257 result: match ev.get("status").and_then(|s| s.as_str()) {
258 Some("ok") => victauri_core::IpcResult::Ok(serde_json::Value::Null),
259 Some("error") => victauri_core::IpcResult::Err("error".to_string()),
260 _ => victauri_core::IpcResult::Pending,
261 },
262 duration_ms: ev
263 .get("duration_ms")
264 .and_then(serde_json::Value::as_f64)
265 .map(|d| d as u64),
266 arg_size_bytes: 0,
267 webview_label: DEFAULT_WEBVIEW_LABEL.to_string(),
268 })
269 }
270 "network" => AppEvent::StateChange {
271 key: format!(
272 "network.{}",
273 ev.get("method").and_then(|m| m.as_str()).unwrap_or("GET")
274 ),
275 timestamp: now,
276 caused_by: ev
277 .get("url")
278 .and_then(|u| u.as_str())
279 .map(std::string::ToString::to_string),
280 },
281 "navigation" => AppEvent::WindowEvent {
282 label: DEFAULT_WEBVIEW_LABEL.to_string(),
283 event: format!(
284 "navigation.{}",
285 ev.get("nav_type")
286 .and_then(|n| n.as_str())
287 .unwrap_or("unknown")
288 ),
289 timestamp: now,
290 },
291 "dom_interaction" => {
292 let action_str = ev.get("action").and_then(|a| a.as_str()).unwrap_or("click");
293 let action = match action_str {
294 "click" => victauri_core::InteractionKind::Click,
295 "double_click" => victauri_core::InteractionKind::DoubleClick,
296 "fill" => victauri_core::InteractionKind::Fill,
297 "key_press" => victauri_core::InteractionKind::KeyPress,
298 "select" => victauri_core::InteractionKind::Select,
299 "navigate" => victauri_core::InteractionKind::Navigate,
300 "scroll" => victauri_core::InteractionKind::Scroll,
301 _ => victauri_core::InteractionKind::Click,
302 };
303 AppEvent::DomInteraction {
304 action,
305 selector: ev
306 .get("selector")
307 .and_then(|s| s.as_str())
308 .unwrap_or("body")
309 .to_string(),
310 value: ev
311 .get("value")
312 .and_then(|v| v.as_str())
313 .map(std::string::ToString::to_string),
314 timestamp: now,
315 webview_label: DEFAULT_WEBVIEW_LABEL.to_string(),
316 }
317 }
318 _ => return None,
319 };
320
321 Some(app_event)
322}
323
324async fn event_drain_loop(
325 state: Arc<VictauriState>,
326 bridge: Arc<dyn WebviewBridge>,
327 mut shutdown: tokio::sync::watch::Receiver<bool>,
328) {
329 let mut last_drain_ts: f64 = 0.0;
330
331 loop {
332 tokio::select! {
333 _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {}
334 _ = shutdown.changed() => break,
335 }
336
337 if !state.recorder.is_recording() {
338 continue;
339 }
340
341 let code = format!("return window.__VICTAURI__?.getEventStream({last_drain_ts})");
342 let id = uuid::Uuid::new_v4().to_string();
343 let (tx, rx) = tokio::sync::oneshot::channel();
344
345 {
346 let mut pending = state.pending_evals.lock().await;
347 if pending.len() >= MAX_PENDING_EVALS {
348 continue;
349 }
350 pending.insert(id.clone(), tx);
351 }
352
353 let inject = format!(
354 r"
355 (async () => {{
356 try {{
357 const __result = await (async () => {{ {code} }})();
358 await window.__TAURI__.core.invoke('plugin:victauri|victauri_eval_callback', {{
359 id: '{id}',
360 result: JSON.stringify(__result)
361 }});
362 }} catch (e) {{
363 await window.__TAURI__.core.invoke('plugin:victauri|victauri_eval_callback', {{
364 id: '{id}',
365 result: JSON.stringify({{ __error: e.message }})
366 }});
367 }}
368 }})();
369 "
370 );
371
372 if bridge.eval_webview(None, &inject).is_err() {
373 state.pending_evals.lock().await.remove(&id);
374 continue;
375 }
376
377 let Ok(Ok(result)) = tokio::time::timeout(std::time::Duration::from_secs(5), rx).await
378 else {
379 state.pending_evals.lock().await.remove(&id);
380 continue;
381 };
382
383 let events: Vec<serde_json::Value> = match serde_json::from_str(&result) {
384 Ok(v) => v,
385 Err(_) => continue,
386 };
387
388 for ev in &events {
389 let ts = ev
390 .get("timestamp")
391 .and_then(serde_json::Value::as_f64)
392 .unwrap_or(0.0);
393 if ts > last_drain_ts {
394 last_drain_ts = ts;
395 }
396
397 if let Some(app_event) = parse_bridge_event(ev) {
398 state.recorder.record_event(app_event);
399 }
400 }
401 }
402}
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407 use victauri_core::{AppEvent, InteractionKind, IpcResult};
408
409 #[tokio::test]
410 async fn try_bind_preferred_port_available() {
411 let (listener, port) = try_bind(0).await.unwrap();
412 let addr = listener.local_addr().unwrap();
413 assert_eq!(port, 0);
414 assert_ne!(addr.port(), 0); }
416
417 #[tokio::test]
418 async fn try_bind_falls_back_when_taken() {
419 let blocker = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
420 let blocked_port = blocker.local_addr().unwrap().port();
421
422 let (_, actual) = try_bind(blocked_port).await.unwrap();
423 assert_ne!(actual, blocked_port);
424 assert!(actual > blocked_port);
425 assert!(actual <= blocked_port + PORT_FALLBACK_RANGE);
426 }
427
428 #[test]
429 fn port_file_roundtrip() {
430 write_port_file(7777);
431 let content = std::fs::read_to_string(port_file_path()).unwrap();
432 assert_eq!(content, "7777");
433 remove_port_file();
434 assert!(!port_file_path().exists());
435 }
436
437 #[test]
440 fn parse_dom_interaction_click() {
441 let ev = serde_json::json!({
442 "type": "dom_interaction",
443 "action": "click",
444 "selector": "#submit-btn",
445 });
446 let result = parse_bridge_event(&ev).expect("should produce an event");
447 match result {
448 AppEvent::DomInteraction {
449 action,
450 selector,
451 value,
452 webview_label,
453 ..
454 } => {
455 assert_eq!(action, InteractionKind::Click);
456 assert_eq!(selector, "#submit-btn");
457 assert!(value.is_none());
458 assert_eq!(webview_label, "main");
459 }
460 other => panic!("expected DomInteraction, got {other:?}"),
461 }
462 }
463
464 #[test]
465 fn parse_dom_interaction_fill_with_value() {
466 let ev = serde_json::json!({
467 "type": "dom_interaction",
468 "action": "fill",
469 "selector": "input[name=email]",
470 "value": "test@example.com",
471 });
472 let result = parse_bridge_event(&ev).expect("should produce an event");
473 match result {
474 AppEvent::DomInteraction {
475 action,
476 selector,
477 value,
478 ..
479 } => {
480 assert_eq!(action, InteractionKind::Fill);
481 assert_eq!(selector, "input[name=email]");
482 assert_eq!(value.as_deref(), Some("test@example.com"));
483 }
484 other => panic!("expected DomInteraction, got {other:?}"),
485 }
486 }
487
488 #[test]
489 fn parse_dom_interaction_key_press() {
490 let ev = serde_json::json!({
491 "type": "dom_interaction",
492 "action": "key_press",
493 "selector": "body",
494 "value": "Enter",
495 });
496 let result = parse_bridge_event(&ev).expect("should produce an event");
497 match result {
498 AppEvent::DomInteraction { action, value, .. } => {
499 assert_eq!(action, InteractionKind::KeyPress);
500 assert_eq!(value.as_deref(), Some("Enter"));
501 }
502 other => panic!("expected DomInteraction, got {other:?}"),
503 }
504 }
505
506 #[test]
507 fn parse_dom_interaction_unknown_action_defaults_to_click() {
508 let ev = serde_json::json!({
509 "type": "dom_interaction",
510 "action": "swipe_left",
511 "selector": ".card",
512 });
513 let result = parse_bridge_event(&ev).expect("should produce an event");
514 match result {
515 AppEvent::DomInteraction { action, .. } => {
516 assert_eq!(action, InteractionKind::Click);
517 }
518 other => panic!("expected DomInteraction, got {other:?}"),
519 }
520 }
521
522 #[test]
523 fn parse_dom_interaction_missing_action_defaults_to_click() {
524 let ev = serde_json::json!({
525 "type": "dom_interaction",
526 "selector": "button",
527 });
528 let result = parse_bridge_event(&ev).expect("should produce an event");
529 match result {
530 AppEvent::DomInteraction { action, .. } => {
531 assert_eq!(action, InteractionKind::Click);
532 }
533 other => panic!("expected DomInteraction, got {other:?}"),
534 }
535 }
536
537 #[test]
538 fn parse_dom_interaction_missing_selector_defaults_to_body() {
539 let ev = serde_json::json!({
540 "type": "dom_interaction",
541 "action": "scroll",
542 });
543 let result = parse_bridge_event(&ev).expect("should produce an event");
544 match result {
545 AppEvent::DomInteraction {
546 action, selector, ..
547 } => {
548 assert_eq!(action, InteractionKind::Scroll);
549 assert_eq!(selector, "body");
550 }
551 other => panic!("expected DomInteraction, got {other:?}"),
552 }
553 }
554
555 #[test]
556 fn parse_dom_interaction_all_action_kinds() {
557 let cases = [
558 ("click", InteractionKind::Click),
559 ("double_click", InteractionKind::DoubleClick),
560 ("fill", InteractionKind::Fill),
561 ("key_press", InteractionKind::KeyPress),
562 ("select", InteractionKind::Select),
563 ("navigate", InteractionKind::Navigate),
564 ("scroll", InteractionKind::Scroll),
565 ];
566 for (action_str, expected_kind) in cases {
567 let ev = serde_json::json!({
568 "type": "dom_interaction",
569 "action": action_str,
570 "selector": "body",
571 });
572 let result = parse_bridge_event(&ev)
573 .unwrap_or_else(|| panic!("should produce event for action {action_str}"));
574 match result {
575 AppEvent::DomInteraction { action, .. } => {
576 assert_eq!(action, expected_kind, "mismatch for action {action_str}");
577 }
578 other => panic!("expected DomInteraction for {action_str}, got {other:?}"),
579 }
580 }
581 }
582
583 #[test]
586 fn parse_ipc_status_ok() {
587 let ev = serde_json::json!({
588 "type": "ipc",
589 "command": "greet",
590 "status": "ok",
591 "duration_ms": 42.0,
592 });
593 let result = parse_bridge_event(&ev).expect("should produce an event");
594 match result {
595 AppEvent::Ipc(call) => {
596 assert_eq!(call.command, "greet");
597 assert_eq!(call.result, IpcResult::Ok(serde_json::Value::Null));
598 assert_eq!(call.duration_ms, Some(42));
599 assert_eq!(call.webview_label, "main");
600 }
601 other => panic!("expected Ipc, got {other:?}"),
602 }
603 }
604
605 #[test]
606 fn parse_ipc_status_error() {
607 let ev = serde_json::json!({
608 "type": "ipc",
609 "command": "save_file",
610 "status": "error",
611 });
612 let result = parse_bridge_event(&ev).expect("should produce an event");
613 match result {
614 AppEvent::Ipc(call) => {
615 assert_eq!(call.command, "save_file");
616 assert_eq!(call.result, IpcResult::Err("error".to_string()));
617 }
618 other => panic!("expected Ipc, got {other:?}"),
619 }
620 }
621
622 #[test]
623 fn parse_ipc_status_pending() {
624 let ev = serde_json::json!({
625 "type": "ipc",
626 "command": "long_task",
627 });
628 let result = parse_bridge_event(&ev).expect("should produce an event");
629 match result {
630 AppEvent::Ipc(call) => {
631 assert_eq!(call.result, IpcResult::Pending);
632 assert!(call.duration_ms.is_none());
633 }
634 other => panic!("expected Ipc, got {other:?}"),
635 }
636 }
637
638 #[test]
641 fn parse_console_event() {
642 let ev = serde_json::json!({
643 "type": "console",
644 "level": "warn",
645 "message": "deprecated API usage",
646 });
647 let result = parse_bridge_event(&ev).expect("should produce an event");
648 match result {
649 AppEvent::StateChange { key, caused_by, .. } => {
650 assert_eq!(key, "console.warn");
651 assert_eq!(caused_by.as_deref(), Some("deprecated API usage"));
652 }
653 other => panic!("expected StateChange, got {other:?}"),
654 }
655 }
656
657 #[test]
658 fn parse_console_default_level() {
659 let ev = serde_json::json!({
660 "type": "console",
661 "message": "hello",
662 });
663 let result = parse_bridge_event(&ev).expect("should produce an event");
664 match result {
665 AppEvent::StateChange { key, .. } => {
666 assert_eq!(key, "console.log");
667 }
668 other => panic!("expected StateChange, got {other:?}"),
669 }
670 }
671
672 #[test]
675 fn parse_navigation_event() {
676 let ev = serde_json::json!({
677 "type": "navigation",
678 "nav_type": "push",
679 });
680 let result = parse_bridge_event(&ev).expect("should produce an event");
681 match result {
682 AppEvent::WindowEvent { label, event, .. } => {
683 assert_eq!(label, "main");
684 assert_eq!(event, "navigation.push");
685 }
686 other => panic!("expected WindowEvent, got {other:?}"),
687 }
688 }
689
690 #[test]
691 fn parse_navigation_default_nav_type() {
692 let ev = serde_json::json!({ "type": "navigation" });
693 let result = parse_bridge_event(&ev).expect("should produce an event");
694 match result {
695 AppEvent::WindowEvent { event, .. } => {
696 assert_eq!(event, "navigation.unknown");
697 }
698 other => panic!("expected WindowEvent, got {other:?}"),
699 }
700 }
701
702 #[test]
705 fn parse_dom_mutation_event() {
706 let ev = serde_json::json!({
707 "type": "dom_mutation",
708 "count": 15,
709 });
710 let result = parse_bridge_event(&ev).expect("should produce an event");
711 match result {
712 AppEvent::DomMutation {
713 webview_label,
714 mutation_count,
715 ..
716 } => {
717 assert_eq!(webview_label, "main");
718 assert_eq!(mutation_count, 15);
719 }
720 other => panic!("expected DomMutation, got {other:?}"),
721 }
722 }
723
724 #[test]
727 fn parse_network_event() {
728 let ev = serde_json::json!({
729 "type": "network",
730 "method": "POST",
731 "url": "https://api.example.com/data",
732 });
733 let result = parse_bridge_event(&ev).expect("should produce an event");
734 match result {
735 AppEvent::StateChange { key, caused_by, .. } => {
736 assert_eq!(key, "network.POST");
737 assert_eq!(caused_by.as_deref(), Some("https://api.example.com/data"));
738 }
739 other => panic!("expected StateChange, got {other:?}"),
740 }
741 }
742
743 #[test]
746 fn parse_unknown_type_returns_none() {
747 let ev = serde_json::json!({
748 "type": "custom_telemetry",
749 "payload": 42,
750 });
751 assert!(parse_bridge_event(&ev).is_none());
752 }
753
754 #[test]
755 fn parse_missing_type_field_returns_none() {
756 let ev = serde_json::json!({ "data": "no type here" });
757 assert!(parse_bridge_event(&ev).is_none());
758 }
759
760 #[test]
761 fn parse_empty_object_returns_none() {
762 let ev = serde_json::json!({});
763 assert!(parse_bridge_event(&ev).is_none());
764 }
765}