-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
1485 lines (1350 loc) · 48.2 KB
/
Copy pathmain.rs
File metadata and controls
1485 lines (1350 loc) · 48.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! On Windows, the default console subsystem spawns a second (blank) window next to the WebView.
#![cfg_attr(target_os = "windows", windows_subsystem = "windows")]
#[cfg(target_os = "linux")]
mod gdk_log_suppress;
#[cfg(target_os = "linux")]
mod linux_webkit_env;
mod app_prefs;
mod backup;
mod license;
mod plugins;
mod proxmux_ws_proxy;
mod host_metadata;
mod known_hosts;
mod sftp_export;
mod key_crypto;
mod quick_ssh;
mod sftp;
mod sftp_transfer_ops;
#[cfg(test)]
mod testutil;
mod layout_profiles;
mod launch_cli;
mod secure_store;
mod session;
mod ssh_config;
mod ssh_home;
mod store_models;
mod view_profiles;
mod sensitive;
use app_prefs::AppPreferences;
use backup::{create_backup_payload, export_encrypted_backup, import_encrypted_backup};
use host_metadata::{load_metadata, save_metadata, touch_host_last_used as touch_host_last_used_backend, HostMetadataStore};
use layout_profiles::{
delete_layout_profile as delete_layout_profile_backend, load_layout_profiles,
save_layout_profile as save_layout_profile_backend, LayoutProfile,
};
use quick_ssh::QuickSshSessionRequest;
use secure_store::{
assign_host_binding as assign_host_binding_backend, create_encrypted_key as create_encrypted_key_backend,
delete_key as delete_key_backend, ensure_ssh_session_identity_ready,
export_resolved_openssh_config as export_resolved_openssh_config_backend,
export_resolved_openssh_config_to_path as export_resolved_openssh_config_to_path_backend,
list_groups as list_groups_backend, list_store_objects as list_store_objects_backend,
list_tags as list_tags_backend, list_users as list_users_backend, resolve_host_config_for_session,
save_store_objects as save_store_objects_backend, unlock_key_material as unlock_key_material_backend,
};
use sftp::{
copy_local_file as sftp_copy_local_file_backend,
create_local_dir as sftp_create_local_dir_backend,
create_local_text_file as sftp_create_local_text_file_backend,
delete_local_entry as sftp_delete_local_entry_backend,
delete_local_entry_with_mode as sftp_delete_local_entry_with_mode_backend,
download_remote_file as sftp_download_remote_file_backend,
get_local_home_canonical_path as sftp_get_local_home_canonical_path_backend,
list_local_dir as sftp_list_local_dir_backend,
list_remote_dir as sftp_list_remote_dir_backend,
open_local_entry_in_os as sftp_open_local_entry_in_os_backend,
open_remote_file_in_os as sftp_open_remote_file_in_os_backend,
read_local_text_file as sftp_read_local_text_file_backend,
rename_local_entry as sftp_rename_local_entry_backend,
sftp_create_dir as sftp_create_dir_backend,
sftp_create_text_file as sftp_create_text_file_backend,
sftp_delete_entry as sftp_delete_entry_backend,
sftp_delete_entry_with_mode as sftp_delete_entry_with_mode_backend,
sftp_read_text_file as sftp_read_text_file_backend,
sftp_rename_entry as sftp_rename_entry_backend,
sftp_write_text_file as sftp_write_text_file_backend,
upload_remote_file as sftp_upload_remote_file_backend,
write_local_text_file as sftp_write_local_text_file_backend,
DeleteEntryMode,
DeleteTreeResult,
RemoteSshSpec,
};
use known_hosts::KnownHostEntry;
use session::SessionState;
use ssh_home::SshDirInfo;
use ssh_config::{
delete_host_from_file, load_hosts, load_ssh_config_raw, save_host_to_file, write_ssh_config_raw,
HostConfig,
};
use sftp_export::{export_local_archive, export_remote_archive};
use view_profiles::{
delete_view_profile as delete_view_profile_backend, load_view_profiles,
reorder_view_profiles as reorder_view_profiles_backend, save_view_profile as save_view_profile_backend,
ViewProfile,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
use tauri::Emitter;
use tauri::Manager;
use tauri::State;
use tauri::WebviewUrl;
use tauri::webview::{PageLoadEvent, WebviewWindowBuilder};
use store_models::{EntityStore, HostBinding, SshKeyObject, TagObject, UserObject, GroupObject};
use serde::Deserialize;
use serde_json::Value as JsonValue;
#[derive(serde::Deserialize)]
struct BackupIpcArgs {
path: String,
/// Wire key stays `password` for the TypeScript `invoke(..., { path, password })` payload.
#[serde(rename = "password")]
secret: String,
}
#[derive(serde::Serialize)]
struct SessionStarted {
session_id: String,
}
#[tauri::command]
fn list_hosts() -> Result<Vec<HostConfig>, String> {
load_hosts().map_err(|err| err.to_string())
}
#[tauri::command]
fn save_host(host: HostConfig) -> Result<(), String> {
save_host_to_file(&host).map_err(|err| err.to_string())
}
#[tauri::command]
fn delete_host(host_name: String) -> Result<(), String> {
delete_host_from_file(&host_name).map_err(|err| err.to_string())
}
#[tauri::command]
fn get_ssh_config_raw() -> Result<String, String> {
load_ssh_config_raw().map_err(|err| err.to_string())
}
#[tauri::command]
fn save_ssh_config_raw(content: String) -> Result<(), String> {
write_ssh_config_raw(&content).map_err(|err| err.to_string())
}
#[tauri::command]
fn get_ssh_dir_info() -> Result<SshDirInfo, String> {
ssh_home::get_ssh_dir_info_for_ipc().map_err(|err| err.to_string())
}
#[tauri::command]
fn set_ssh_dir_override(path: Option<String>) -> Result<(), String> {
ssh_home::apply_ssh_dir_override_from_ipc(path).map_err(|err| err.to_string())?;
app_prefs::reload_from_disk();
Ok(())
}
#[tauri::command]
fn list_host_metadata() -> Result<HostMetadataStore, String> {
load_metadata().map_err(|err| err.to_string())
}
#[tauri::command]
fn save_host_metadata(metadata: HostMetadataStore) -> Result<(), String> {
save_metadata(&metadata).map_err(|err| err.to_string())
}
#[tauri::command]
fn touch_host_last_used(host_alias: String) -> Result<(), String> {
touch_host_last_used_backend(&host_alias).map_err(|err| err.to_string())
}
fn validate_external_http_url(url: &str) -> Result<(), String> {
let t = url.trim();
if t.is_empty() {
return Err("URL is empty".into());
}
if t.len() > 8192 {
return Err("URL is too long".into());
}
let lower = t.to_ascii_lowercase();
if lower.starts_with("http://") || lower.starts_with("https://") {
return Ok(());
}
Err("URL must start with http:// or https://".into())
}
#[tauri::command]
fn open_external_url(url: String) -> Result<(), String> {
validate_external_http_url(&url)?;
open::that(url.trim()).map_err(|e| e.to_string())
}
fn sanitize_terminal_clipboard_text(s: String) -> Option<String> {
if s.contains('\u{FFFD}') {
return None;
}
let mut out = String::with_capacity(s.len());
for ch in s.chars() {
if ch == '\0' {
continue;
}
if matches!(ch, '\n' | '\r' | '\t') {
out.push(ch);
continue;
}
if ch.is_control() {
continue;
}
out.push(ch);
}
(!out.is_empty()).then_some(out)
}
/// Read primary selection (middle-click) or clipboard text.
///
/// On Linux the function shells out to `wl-paste` (Wayland) / `xclip` (X11)
/// because the in-process `wl-clipboard-rs` crate conflicts with the
/// WebKit/GTK Wayland event loop and can crash or deadlock the app.
/// Subprocess calls are isolated, fast (<5 ms), and work on every compositor.
/// `wl-paste` / `xclip` use explicit **text** targets so binary offers are skipped.
/// Returned text is sanitized (no NUL / control bytes) so xterm and GTK selection export stay stable.
/// arboard (X11-only, no Wayland backend) is the last-resort fallback,
/// wrapped in `catch_unwind` so a panic can never take down the process.
#[tauri::command]
fn read_terminal_middle_click_paste_text() -> Option<String> {
#[cfg(target_os = "linux")]
{
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
if let Some(t) = clipboard_from_command(
"wl-paste",
&["--primary", "--no-newline", "--type", "text/plain"],
) {
return sanitize_terminal_clipboard_text(t);
}
if let Some(t) = clipboard_from_command("wl-paste", &["--no-newline", "--type", "text/plain"]) {
return sanitize_terminal_clipboard_text(t);
}
if let Some(t) = clipboard_from_command("wl-paste", &["--primary", "--no-newline"]) {
return sanitize_terminal_clipboard_text(t);
}
if let Some(t) = clipboard_from_command("wl-paste", &["--no-newline"]) {
return sanitize_terminal_clipboard_text(t);
}
}
if let Some(t) = clipboard_from_command("xclip", &["-selection", "primary", "-t", "UTF8_STRING", "-o"]) {
return sanitize_terminal_clipboard_text(t);
}
if let Some(t) = clipboard_from_command("xclip", &["-selection", "primary", "-o"]) {
return sanitize_terminal_clipboard_text(t);
}
if let Some(t) = clipboard_from_command("xclip", &["-selection", "clipboard", "-t", "UTF8_STRING", "-o"]) {
return sanitize_terminal_clipboard_text(t);
}
if let Some(t) = clipboard_from_command("xclip", &["-selection", "clipboard", "-o"]) {
return sanitize_terminal_clipboard_text(t);
}
}
let fallback = std::panic::catch_unwind(|| {
use arboard::Clipboard;
let mut cb = Clipboard::new().ok()?;
cb.get_text().ok().filter(|s| !s.is_empty())
})
.ok()
.flatten();
fallback.and_then(sanitize_terminal_clipboard_text)
}
#[cfg(target_os = "linux")]
fn clipboard_from_command(cmd: &str, args: &[&str]) -> Option<String> {
let mut timeout_args: Vec<&str> = vec!["--kill-after=2", "1", cmd];
timeout_args.extend(args);
let output = std::process::Command::new("timeout")
.args(&timeout_args)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.output()
.ok()?;
if !output.status.success() {
return None;
}
let text = String::from_utf8_lossy(&output.stdout).into_owned();
if text.is_empty() { None } else { Some(text) }
}
/// Copy terminal selection to the system clipboard (and primary on Linux) so **Ctrl+Shift+C** works
/// without relying on the WebView clipboard API. Uses `wl-copy` / `xclip` on Linux (same family as
/// paste) and arboard elsewhere.
#[tauri::command]
fn write_terminal_selection_clipboard(text: String) -> Result<(), String> {
if text.is_empty() {
return Ok(());
}
#[cfg(target_os = "linux")]
{
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
if clipboard_write_wl_copy(false, &text).is_ok() {
let _ = clipboard_write_wl_copy(true, &text);
return Ok(());
}
}
if clipboard_write_xclip_stdin("clipboard", &text).is_ok() {
let _ = clipboard_write_xclip_stdin("primary", &text);
return Ok(());
}
}
arboard_set_clipboard_text(&text)
}
#[cfg(target_os = "linux")]
fn clipboard_write_wl_copy(primary: bool, text: &str) -> Result<(), String> {
use std::io::Write;
use std::process::{Command, Stdio};
let mut cmd = Command::new("timeout");
cmd.args(["--kill-after=2", "5", "wl-copy"]);
if primary {
cmd.arg("--primary");
}
cmd.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null());
let mut child = cmd.spawn().map_err(|e| e.to_string())?;
let mut stdin = child.stdin.take().ok_or_else(|| "wl-copy stdin".to_string())?;
stdin.write_all(text.as_bytes()).map_err(|e| e.to_string())?;
drop(stdin);
let st = child.wait().map_err(|e| e.to_string())?;
if st.success() {
Ok(())
} else {
Err(format!("wl-copy failed: {st}"))
}
}
#[cfg(target_os = "linux")]
fn clipboard_write_xclip_stdin(selection: &str, text: &str) -> Result<(), String> {
use std::io::Write;
use std::process::{Command, Stdio};
let mut cmd = Command::new("timeout");
cmd.args(["--kill-after=2", "5", "xclip", "-selection", selection]);
cmd.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null());
let mut child = cmd.spawn().map_err(|e| e.to_string())?;
let mut stdin = child.stdin.take().ok_or_else(|| "xclip stdin".to_string())?;
stdin.write_all(text.as_bytes()).map_err(|e| e.to_string())?;
drop(stdin);
let st = child.wait().map_err(|e| e.to_string())?;
if st.success() {
Ok(())
} else {
Err(format!("xclip failed: {st}"))
}
}
fn arboard_set_clipboard_text(text: &str) -> Result<(), String> {
std::panic::catch_unwind(|| {
use arboard::Clipboard;
let mut cb = Clipboard::new().ok()?;
cb.set_text(text.to_owned()).ok()
})
.ok()
.flatten()
.ok_or_else(|| "clipboard unavailable".to_string())
}
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
))]
fn webkit_set_tls_errors_ignored_for_window<R: tauri::Runtime>(
win: &tauri::WebviewWindow<R>,
) -> Result<(), String> {
win.with_webview(|webview| {
use webkit2gtk::{TLSErrorsPolicy, WebContextExt, WebViewExt, WebsiteDataManagerExt};
if let Some(ctx) = webview.inner().web_context() {
if let Some(mgr) = ctx.website_data_manager() {
mgr.set_tls_errors_policy(TLSErrorsPolicy::Ignore);
}
}
})
.map_err(|e| e.to_string())
}
#[cfg(not(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
)))]
fn webkit_set_tls_errors_ignored_for_window<R: tauri::Runtime>(
_win: &tauri::WebviewWindow<R>,
) -> Result<(), String> {
Ok(())
}
/// Proxmox ExtJS UI typically sets a non-empty URL fragment after web login (`#v1:…`).
fn proxmox_url_has_nonempty_fragment(url: &tauri::Url) -> bool {
url.fragment()
.map(|f| !f.trim().is_empty())
.unwrap_or(false)
}
fn proxmox_url_query_has_console(url: &tauri::Url) -> bool {
url.query()
.map(|q| q.contains("console="))
.unwrap_or(false)
}
/// True when a finished load or navigation URL should trigger auto-console (not already the console document).
fn proxmox_should_trigger_auto_console_nav(url: &tauri::Url) -> bool {
if proxmox_url_query_has_console(url) {
return false;
}
proxmox_url_has_nonempty_fragment(url)
}
fn proxmox_origin_base_uri(url: &tauri::Url) -> String {
let mut u = url.clone();
u.set_path("/");
u.set_query(None);
u.set_fragment(None);
let s = u.to_string();
if s.ends_with('/') {
s
} else {
format!("{s}/")
}
}
fn finish_proxmox_auto_console_navigation<R: tauri::Runtime>(
app: &tauri::AppHandle<R>,
webview_label: &str,
console_s: String,
state: &Arc<Mutex<PendingProxmoxAutoConsole>>,
_trigger: &'static str,
) {
let Some(win) = app.get_webview_window(webview_label) else {
if let Ok(mut st) = state.lock() {
st.done = false;
}
return;
};
let parsed_console = match tauri::Url::parse(console_s.trim()) {
Ok(p) => p,
Err(_) => {
if let Ok(mut st) = state.lock() {
st.done = false;
}
return;
}
};
if win.navigate(parsed_console).is_err() {
if let Ok(mut st) = state.lock() {
st.done = false;
}
return;
}
let emit_payload = ProxmoxAssistAutoConsolePayload {
webview_label: webview_label.to_string(),
console_url: console_s,
};
let _ = app.emit("proxmox-web-assist-auto-console", emit_payload);
}
fn try_fire_proxmox_auto_console<R: tauri::Runtime>(
app: &tauri::AppHandle<R>,
webview_label: &str,
candidate_url: &tauri::Url,
state: &Arc<Mutex<PendingProxmoxAutoConsole>>,
trigger: &'static str,
) {
let mut st = match state.lock() {
Ok(g) => g,
Err(_) => return,
};
if st.done {
return;
}
if !proxmox_should_trigger_auto_console_nav(candidate_url) {
return;
}
let console_s = st.console_url.clone();
st.done = true;
drop(st);
finish_proxmox_auto_console_navigation(app, webview_label, console_s, state, trigger);
}
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
))]
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
))]
fn try_fire_proxmox_auto_console_when_cookies_have_ticket<R: tauri::Runtime>(
app: &tauri::AppHandle<R>,
webview_label: &str,
state: &Arc<Mutex<PendingProxmoxAutoConsole>>,
has_pve_auth_cookie: bool,
trigger: &'static str,
) {
if !has_pve_auth_cookie {
return;
}
let mut st = match state.lock() {
Ok(g) => g,
Err(_) => return,
};
if st.done {
return;
}
let console_s = st.console_url.clone();
st.done = true;
drop(st);
finish_proxmox_auto_console_navigation(app, webview_label, console_s, state, trigger);
}
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
))]
fn webkit_attach_proxmox_pve_auth_cookie_listener<R: tauri::Runtime>(
win: &tauri::WebviewWindow<R>,
app: tauri::AppHandle<R>,
webview_label: String,
cookie_lookup_uri: String,
state: Arc<Mutex<PendingProxmoxAutoConsole>>,
) -> Result<(), String> {
win.with_webview(move |platform| {
use webkit2gtk::gio;
use webkit2gtk::{CookieManagerExt, WebContextExt, WebViewExt};
let webview = platform.inner();
let Some(ctx) = webview.web_context() else {
return;
};
let Some(cm) = ctx.cookie_manager() else {
return;
};
let cm_probe = cm.clone();
let probe_uri = cookie_lookup_uri.clone();
let app_probe = app.clone();
let label_probe = webview_label.clone();
let state_probe = Arc::clone(&state);
cm_probe.cookies(&probe_uri, None::<&gio::Cancellable>, move |res| {
if let Ok(mut list) = res {
let has_ticket = list.iter_mut().any(|c| {
c.name()
.as_ref()
.is_some_and(|n| n.as_str() == "PVEAuthCookie" || n.as_str().ends_with("PVEAuthCookie"))
});
try_fire_proxmox_auto_console_when_cookies_have_ticket(
&app_probe,
&label_probe,
&state_probe,
has_ticket,
"pve_auth_cookie_probe",
);
}
});
let app0 = app.clone();
let label0 = webview_label.clone();
let uri0 = cookie_lookup_uri.clone();
let state0 = Arc::clone(&state);
cm.connect_changed(move |cm| {
let uri = uri0.clone();
let app_c = app0.clone();
let label_c = label0.clone();
let state_c = Arc::clone(&state0);
cm.cookies(&uri, None::<&gio::Cancellable>, move |res| {
if let Ok(mut list) = res {
let has_ticket = list.iter_mut().any(|c| {
c.name().as_ref().is_some_and(|n| {
n.as_str() == "PVEAuthCookie" || n.as_str().ends_with("PVEAuthCookie")
})
});
try_fire_proxmox_auto_console_when_cookies_have_ticket(
&app_c,
&label_c,
&state_c,
has_ticket,
"pve_auth_cookie_changed",
);
}
});
});
})
.map_err(|e| e.to_string())
}
#[cfg(not(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
)))]
fn webkit_attach_proxmox_pve_auth_cookie_listener<R: tauri::Runtime>(
_win: &tauri::WebviewWindow<R>,
_app: tauri::AppHandle<R>,
_webview_label: String,
_cookie_lookup_uri: String,
_state: Arc<Mutex<PendingProxmoxAutoConsole>>,
) -> Result<(), String> {
Ok(())
}
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct ProxmoxAssistAutoConsolePayload {
webview_label: String,
console_url: String,
}
struct PendingProxmoxAutoConsole {
console_url: String,
done: bool,
}
/// Opens `http`/`https` in a new app-owned webview window (top-level document), avoiding iframe embedding limits.
///
/// Returns the webview **label** for [`navigate_in_app_webview_window`] (e.g. continue to a console URL after Proxmox web login).
///
/// Uses separate `title` / `url` parameters so the frontend can `invoke(..., { title, url })` (Tauri maps one JSON key per argument; a single struct parameter named `args` would require a nested `args` object).
///
/// When `allow_insecure_tls` is true (Proxmox cluster **Allow insecure TLS**), WebKitGTK is configured to ignore TLS certificate errors for that window (Linux/BSD only). You still log in in that window; API tokens are not shared with the web UI.
///
/// When `auto_console_url` is set, after Proxmox web login the webview navigates to the console URL and emits `proxmox-web-assist-auto-console` so the host UI can dismiss the login assist banner.
///
/// Detection: on Linux/BSD, WebKitGTK’s cookie store is watched for the **`PVEAuthCookie`** session ticket (including `__Host-`-prefixed names). HttpOnly cookies are visible there but not to page JavaScript. A finished load with a non-empty URL fragment is still used as a secondary signal when it occurs.
///
/// We do **not** use [`WebviewWindowBuilder::on_navigation`] on fragment changes: Proxmox sets `#v1:…` during ExtJS bootstrap before a ticket exists, which would navigate to the console too early (**401 No ticket**).
#[tauri::command]
fn open_in_app_webview_window(
app: tauri::AppHandle,
title: String,
url: String,
allow_insecure_tls: bool,
tls_trusted_cert_pem: Option<String>,
auto_console_url: Option<String>,
) -> Result<String, String> {
validate_external_http_url(&url)?;
if let Some(ref a) = auto_console_url {
validate_external_http_url(a)?;
}
let t = url.trim();
let parsed = tauri::Url::parse(t).map_err(|e| format!("Invalid URL: {e}"))?;
let parsed_login_for_cookie = parsed.clone();
let label = format!("web-{}", uuid::Uuid::new_v4());
let window_title: String = title.trim().chars().take(120).collect();
let window_title = if window_title.is_empty() {
"Web console".to_string()
} else {
window_title
};
let mut builder = WebviewWindowBuilder::new(&app, &label, WebviewUrl::External(parsed))
.title(window_title)
.inner_size(1200.0, 800.0);
let mut proxmox_auto_state: Option<Arc<Mutex<PendingProxmoxAutoConsole>>> = None;
if let Some(ref auto_s) = auto_console_url {
let state = Arc::new(Mutex::new(PendingProxmoxAutoConsole {
console_url: auto_s.clone(),
done: false,
}));
proxmox_auto_state = Some(Arc::clone(&state));
let state_cb = Arc::clone(&state);
let app_emit = app.clone();
let label_evt = label.clone();
builder = builder.on_page_load(move |_win, payload| {
if payload.event() != PageLoadEvent::Finished {
return;
}
try_fire_proxmox_auto_console(&app_emit, &label_evt, payload.url(), &state_cb, "page_load_finished");
});
}
let win = builder.build().map_err(|e| e.to_string())?;
if let Some(state) = proxmox_auto_state {
let _ = webkit_attach_proxmox_pve_auth_cookie_listener(
&win,
app.clone(),
label.clone(),
proxmox_origin_base_uri(&parsed_login_for_cookie),
state,
);
}
if allow_insecure_tls || tls_trusted_cert_pem.filter(|s| !s.trim().is_empty()).is_some() {
webkit_set_tls_errors_ignored_for_window(&win)?;
let _ = win.reload();
}
let _ = win.set_focus();
Ok(label)
}
/// Navigates an existing in-app webview window opened by [`open_in_app_webview_window`] (use its returned label).
#[tauri::command]
fn navigate_in_app_webview_window(app: tauri::AppHandle, label: String, url: String) -> Result<(), String> {
validate_external_http_url(&url)?;
let win = app
.get_webview_window(&label)
.ok_or_else(|| "Webview window was closed or not found.".to_string())?;
let t = url.trim();
let parsed = tauri::Url::parse(t).map_err(|e| format!("Invalid URL: {e}"))?;
win.navigate(parsed).map_err(|e| e.to_string())?;
let _ = win.set_focus();
Ok(())
}
fn spice_payload_to_virt_viewer_ini(data: &JsonValue) -> Result<String, String> {
let obj = data
.as_object()
.ok_or_else(|| "SPICE payload must be a JSON object".to_string())?;
let mut out = String::from("[virt-viewer]\n");
for (k, v) in obj {
let val_str = match v {
JsonValue::String(x) => x.clone(),
JsonValue::Number(n) => n.to_string(),
JsonValue::Bool(b) => b.to_string(),
JsonValue::Null => String::new(),
_ => continue,
};
out.push_str(k);
out.push('=');
out.push_str(&val_str);
out.push('\n');
}
Ok(out)
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct OpenSpicePayloadArgs {
spice_data: JsonValue,
}
#[tauri::command]
fn open_virt_viewer_from_spice_payload(args: OpenSpicePayloadArgs) -> Result<(), String> {
let content = spice_payload_to_virt_viewer_ini(&args.spice_data)?;
let name = format!("nosuckshell-spice-{}.vv", uuid::Uuid::new_v4());
let path = std::env::temp_dir().join(name);
std::fs::write(&path, &content).map_err(|e| e.to_string())?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = std::fs::metadata(&path)
.map_err(|e| e.to_string())?
.permissions();
perms.set_mode(0o600);
std::fs::set_permissions(&path, perms).map_err(|e| e.to_string())?;
}
open::that(&path).map_err(|e| e.to_string())
}
#[tauri::command]
fn start_session(
app: tauri::AppHandle,
sessions: State<'_, SessionState>,
host: HostConfig,
) -> Result<SessionStarted, String> {
ensure_ssh_session_identity_ready(&host).map_err(|err| err.to_string())?;
let resolved_host = resolve_host_config_for_session(&host).map_err(|err| err.to_string())?;
let session_id = sessions
.start(app, resolved_host, None)
.map_err(|err| err.to_string())?;
Ok(SessionStarted { session_id })
}
#[tauri::command]
fn start_local_session(
app: tauri::AppHandle,
sessions: State<'_, SessionState>,
) -> Result<SessionStarted, String> {
let session_id = sessions.start_local(app).map_err(|err| err.to_string())?;
Ok(SessionStarted { session_id })
}
#[tauri::command]
fn start_quick_ssh_session(
app: tauri::AppHandle,
sessions: State<'_, SessionState>,
request: QuickSshSessionRequest,
) -> Result<SessionStarted, String> {
let (host, policy) = quick_ssh::normalize_quick_ssh_request(request)?;
let session_id = sessions
.start(app, host, policy)
.map_err(|err| err.to_string())?;
Ok(SessionStarted { session_id })
}
#[tauri::command]
fn sftp_list_remote_dir(spec: RemoteSshSpec, path: String) -> Result<Vec<sftp::SftpDirEntry>, String> {
sftp_list_remote_dir_backend(spec, path)
}
#[tauri::command]
fn list_local_dir(path: String) -> Result<Vec<sftp::LocalDirEntry>, String> {
sftp_list_local_dir_backend(path)
}
#[tauri::command]
fn get_local_home_canonical_path() -> Result<String, String> {
sftp_get_local_home_canonical_path_backend()
}
#[tauri::command]
fn sftp_download_file(
app: tauri::AppHandle,
spec: RemoteSshSpec,
remote_file_path: String,
dest_dir_path: String,
transfer_id: Option<String>,
) -> Result<String, String> {
sftp_download_remote_file_backend(&app, spec, remote_file_path, dest_dir_path, transfer_id)
}
#[tauri::command]
fn sftp_open_remote_file_in_os(spec: RemoteSshSpec, parent_path: String, name: String) -> Result<(), String> {
sftp_open_remote_file_in_os_backend(spec, parent_path, name)
}
#[tauri::command]
fn sftp_export_paths_archive(
spec: RemoteSshSpec,
parent_path: String,
names: Vec<String>,
format: String,
dest_dir_path: String,
local_output_base_name: Option<String>,
) -> Result<String, String> {
export_remote_archive(
spec,
parent_path,
names,
format,
dest_dir_path,
local_output_base_name,
)
}
#[tauri::command]
fn local_export_paths_archive(
parent_path_key: String,
names: Vec<String>,
format: String,
dest_dir_path: String,
local_output_base_name: Option<String>,
) -> Result<String, String> {
export_local_archive(
parent_path_key,
names,
format,
dest_dir_path,
local_output_base_name,
)
}
#[tauri::command]
fn sftp_upload_file(
app: tauri::AppHandle,
spec: RemoteSshSpec,
local_dir_path: String,
local_file_name: String,
remote_file_path: String,
transfer_id: Option<String>,
) -> Result<(), String> {
sftp_upload_remote_file_backend(
&app,
spec,
local_dir_path,
local_file_name,
remote_file_path,
transfer_id,
)
}
#[tauri::command]
fn copy_local_file(
app: tauri::AppHandle,
src_dir_path: String,
src_name: String,
dest_dir_path: String,
dest_name: String,
transfer_id: Option<String>,
) -> Result<String, String> {
sftp_copy_local_file_backend(&app, src_dir_path, src_name, dest_dir_path, dest_name, transfer_id)
}
#[tauri::command]
fn nss_xfer_cancel(transfer_id: String) -> Result<(), String> {
if let Some(h) = sftp_transfer_ops::try_handles(&transfer_id) {
h.cancel.store(true, std::sync::atomic::Ordering::SeqCst);
}
Ok(())
}
#[tauri::command]
fn nss_xfer_set_paused(transfer_id: String, paused: bool) -> Result<(), String> {
if let Some(h) = sftp_transfer_ops::try_handles(&transfer_id) {
h.pause.store(paused, std::sync::atomic::Ordering::SeqCst);
}
Ok(())
}
#[tauri::command]
fn nss_xfer_begin_transfer(transfer_id: String) -> Result<(), String> {
sftp_transfer_ops::ensure_registered(&transfer_id);
Ok(())
}
#[tauri::command]
fn nss_xfer_release_transfer(transfer_id: String) -> Result<(), String> {
sftp_transfer_ops::release_transfer(&transfer_id);
Ok(())
}
#[tauri::command]
fn create_local_dir(parent_path_key: String, dir_name: String) -> Result<(), String> {
sftp_create_local_dir_backend(parent_path_key, dir_name)
}
#[tauri::command]
fn delete_local_entry(parent_path_key: String, name: String) -> Result<(), String> {
sftp_delete_local_entry_backend(parent_path_key, name)
}
#[tauri::command]
fn delete_local_entry_with_mode(
parent_path_key: String,
name: String,
mode: DeleteEntryMode,
) -> Result<DeleteTreeResult, String> {
sftp_delete_local_entry_with_mode_backend(parent_path_key, name, mode)
}
#[tauri::command]
fn rename_local_entry(parent_path_key: String, old_name: String, new_name: String) -> Result<(), String> {
sftp_rename_local_entry_backend(parent_path_key, old_name, new_name)
}
#[tauri::command]
fn open_local_entry_in_os(parent_path_key: String, name: String) -> Result<(), String> {
sftp_open_local_entry_in_os_backend(parent_path_key, name)
}
#[tauri::command]
fn read_local_text_file(parent_path_key: String, name: String) -> Result<String, String> {
sftp_read_local_text_file_backend(parent_path_key, name)
}
#[tauri::command]
fn write_local_text_file(parent_path_key: String, name: String, content: String) -> Result<(), String> {
sftp_write_local_text_file_backend(parent_path_key, name, content)
}
#[tauri::command]
fn create_local_text_file(parent_path_key: String, name: String, content: String) -> Result<(), String> {
sftp_create_local_text_file_backend(parent_path_key, name, content)
}
#[tauri::command]
fn sftp_create_dir(spec: RemoteSshSpec, parent_path: String, dir_name: String) -> Result<(), String> {
sftp_create_dir_backend(spec, parent_path, dir_name)
}
#[tauri::command]
fn sftp_remove_known_host_entries(hosts: Vec<String>) -> Result<(), String> {
known_hosts::remove_by_host(hosts)
}
#[tauri::command]
fn list_known_hosts_entries() -> Result<(String, Vec<KnownHostEntry>), String> {
known_hosts::list_entries()
}
#[tauri::command]
fn remove_known_hosts_line(line_number: usize) -> Result<(), String> {
known_hosts::remove_line(line_number)
}
#[tauri::command]
fn add_known_host_entry(hostname: String, port: u16, key_type: String, key_base64: String) -> Result<(), String> {