xui-rs 2.0.0

A modern, typed async Rust SDK for the 3x-ui panel API
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
use std::fmt;

use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;

fn deserialize_null_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de> + Default,
{
    Option::<T>::deserialize(deserializer).map(Option::unwrap_or_default)
}

/// Current state of the managed Xray process.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ProcessState {
    /// Xray is running normally.
    Running,
    /// Xray is stopped.
    Stop,
    /// Xray failed to start or reload.
    Error,
    /// A newer server returned a state unknown to this SDK version.
    #[default]
    #[serde(other)]
    Unknown,
}

/// Used and total bytes for memory, swap, or disk capacity.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct ResourceUsage {
    /// Bytes currently used.
    pub current: u64,
    /// Total available bytes.
    pub total: u64,
}

/// Cumulative disk IO counters.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct DiskIo {
    /// Bytes read.
    pub read: u64,
    /// Bytes written.
    pub write: u64,
}

/// Current network IO rates and packet rates.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct NetworkIo {
    /// Upload bytes per sample interval.
    pub up: u64,
    /// Download bytes per sample interval.
    pub down: u64,
    /// Uploaded packets per sample interval.
    pub pkt_up: u64,
    /// Downloaded packets per sample interval.
    pub pkt_down: u64,
}

/// Cumulative network traffic counters.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct NetworkTraffic {
    /// Bytes sent.
    pub sent: u64,
    /// Bytes received.
    pub recv: u64,
    /// Packets sent.
    pub pkt_sent: u64,
    /// Packets received.
    pub pkt_recv: u64,
}

/// Managed Xray process state included in [`ServerStatus`].
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct XrayStatus {
    /// Process state.
    pub state: ProcessState,
    /// Last startup or reload error.
    pub error_msg: String,
    /// Installed Xray version.
    pub version: String,
}

/// Live activity for one peer of an embedded `AmneziaWG` interface.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct AmneziaWgPeerActivity {
    /// Kernel interface name.
    #[serde(rename = "interface")]
    pub interface_name: String,
    /// Xray-compatible inbound tag.
    pub tag: String,
    /// Parent inbound identifier.
    pub inbound_id: i64,
    /// Client email/name.
    pub email: String,
    /// Most recently observed remote endpoint.
    pub endpoint: String,
    /// Peer tunnel addresses.
    #[serde(rename = "allowedIPs")]
    pub allowed_ips: String,
    /// Latest handshake timestamp in Unix milliseconds.
    pub handshake: i64,
    /// Received bytes, exposed as upload traffic by 3x-ui.
    pub up: i64,
    /// Transmitted bytes, exposed as download traffic by 3x-ui.
    pub down: i64,
    /// Whether the handshake is within the panel's three-minute window.
    pub online: bool,
}

/// `AmneziaWG` peer activity and recent panel lifecycle events.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct AmneziaWgLogs {
    /// Live peer rows, newest handshake first.
    pub peers: Vec<AmneziaWgPeerActivity>,
    /// Recent panel log lines related to `AmneziaWG`.
    pub events: Vec<String>,
    /// Whether at least one embedded interface is running.
    pub running: bool,
}

/// Embedded `AmneziaWG` subsystem state included in [`ServerStatus`].
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct AmneziaWgStatus {
    /// At least one `AmneziaWG` inbound exists.
    pub configured: bool,
    /// At least one embedded `AmneziaWG` interface is running.
    pub running: bool,
}

/// Complete assembled Xray configuration.
///
/// The inner JSON remains open-ended because it depends on the installed
/// xray-core version. `Debug` is deliberately redacted because the document can
/// contain client credentials, private keys, and certificate material.
#[derive(Clone, Deserialize, PartialEq, Serialize)]
#[serde(transparent)]
pub struct XrayConfig(Value);

impl XrayConfig {
    /// Borrows the complete Xray JSON document.
    pub const fn as_value(&self) -> &Value {
        &self.0
    }

    /// Consumes the wrapper and returns the complete Xray JSON document.
    pub fn into_value(self) -> Value {
        self.0
    }
}

impl From<Value> for XrayConfig {
    fn from(value: Value) -> Self {
        Self(value)
    }
}

impl fmt::Debug for XrayConfig {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("XrayConfig")
            .field(&"[REDACTED]")
            .finish()
    }
}

/// Public addresses detected by the panel.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct PublicAddresses {
    /// Detected IPv4 address.
    pub ipv4: String,
    /// Detected IPv6 address.
    pub ipv6: String,
}

/// Runtime resource use of the panel process itself.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct AppStats {
    /// Number of Go runtime threads.
    pub threads: u32,
    /// Resident memory in bytes.
    pub mem: u64,
    /// Panel process uptime in seconds.
    pub uptime: u64,
}

/// Complete cached machine and Xray status snapshot.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct ServerStatus {
    /// CPU use percentage.
    pub cpu: f64,
    /// Physical CPU core count.
    pub cpu_cores: i32,
    /// Logical processor count.
    pub logical_pro: i32,
    /// Reported CPU speed in MHz.
    pub cpu_speed_mhz: f64,
    /// Memory usage.
    pub mem: ResourceUsage,
    /// Swap usage.
    pub swap: ResourceUsage,
    /// Disk usage.
    pub disk: ResourceUsage,
    /// Cumulative disk IO.
    #[serde(rename = "diskIO")]
    pub disk_io: DiskIo,
    /// Disk throughput since the previous sample.
    pub disk_traffic: DiskIo,
    /// Xray state.
    pub xray: XrayStatus,
    /// Embedded `AmneziaWG` subsystem state.
    pub amneziawg: AmneziaWgStatus,
    /// Running panel version.
    pub panel_version: String,
    /// Stable panel identifier.
    pub panel_guid: String,
    /// Host uptime in seconds.
    pub uptime: u64,
    /// Load averages reported by the host.
    #[serde(deserialize_with = "deserialize_null_default")]
    pub loads: Vec<f64>,
    /// Open TCP connection count.
    pub tcp_count: i32,
    /// Open UDP connection count.
    pub udp_count: i32,
    /// Current network IO.
    #[serde(rename = "netIO")]
    pub net_io: NetworkIo,
    /// Cumulative network traffic.
    pub net_traffic: NetworkTraffic,
    /// Detected public addresses.
    #[serde(rename = "publicIP")]
    pub public_ip: PublicAddresses,
    /// Panel process statistics.
    pub app_stats: AppStats,
}

/// History windows accepted by v3.8.5 history endpoints.
///
/// Every response contains at most 60 points. The wire value is the bucket size
/// in seconds, while variant names describe the resulting history window shown
/// by the panel UI.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum HistoryBucket {
    /// Approximately two minutes at two-second resolution.
    Minutes2,
    /// Approximately thirty minutes at thirty-second resolution.
    Minutes30,
    /// Approximately one hour at one-minute resolution.
    Hour1,
    /// Approximately three hours at three-minute resolution.
    Hours3,
    /// Approximately six hours at six-minute resolution.
    Hours6,
    /// Approximately twelve hours at twelve-minute resolution.
    Hours12,
    /// Approximately one day at 24-minute resolution.
    Day1,
    /// Approximately two days at 48-minute resolution.
    Days2,
    /// Approximately seven days at 168-minute resolution.
    Days7,
}

impl HistoryBucket {
    pub(crate) const fn seconds(self) -> u32 {
        match self {
            Self::Minutes2 => 2,
            Self::Minutes30 => 30,
            Self::Hour1 => 60,
            Self::Hours3 => 180,
            Self::Hours6 => 360,
            Self::Hours12 => 720,
            Self::Day1 => 1_440,
            Self::Days2 => 2_880,
            Self::Days7 => 10_080,
        }
    }
}

/// Host metric accepted by the uniform system history endpoint.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum SystemMetric {
    /// CPU percentage.
    Cpu,
    /// Memory usage.
    Memory,
    /// Swap usage.
    Swap,
    /// Upload rate.
    NetworkUp,
    /// Download rate.
    NetworkDown,
    /// Uploaded packet rate.
    PacketUp,
    /// Downloaded packet rate.
    PacketDown,
    /// Disk read throughput.
    DiskRead,
    /// Disk write throughput.
    DiskWrite,
    /// Disk usage.
    DiskUsage,
    /// Open TCP connection count.
    TcpCount,
    /// Open UDP connection count.
    UdpCount,
    /// Online client count.
    Online,
    /// One-minute load average.
    Load1,
    /// Five-minute load average.
    Load5,
    /// Fifteen-minute load average.
    Load15,
}

impl SystemMetric {
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Cpu => "cpu",
            Self::Memory => "mem",
            Self::Swap => "swap",
            Self::NetworkUp => "netUp",
            Self::NetworkDown => "netDown",
            Self::PacketUp => "pktUp",
            Self::PacketDown => "pktDown",
            Self::DiskRead => "diskRead",
            Self::DiskWrite => "diskWrite",
            Self::DiskUsage => "diskUsage",
            Self::TcpCount => "tcpCount",
            Self::UdpCount => "udpCount",
            Self::Online => "online",
            Self::Load1 => "load1",
            Self::Load5 => "load5",
            Self::Load15 => "load15",
        }
    }
}

/// Xray expvar metric accepted by its history endpoint.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum XrayMetric {
    /// Allocated heap bytes.
    Alloc,
    /// Bytes obtained from the operating system.
    Sys,
    /// Live heap object count.
    HeapObjects,
    /// Completed garbage collection cycles.
    NumGc,
    /// Garbage collector pause time.
    PauseNs,
}

impl XrayMetric {
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Alloc => "xrAlloc",
            Self::Sys => "xrSys",
            Self::HeapObjects => "xrHeapObjects",
            Self::NumGc => "xrNumGC",
            Self::PauseNs => "xrPauseNs",
        }
    }
}

/// One uniform time-series sample.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct MetricPoint {
    /// Unix timestamp in seconds.
    #[serde(rename = "t")]
    pub timestamp: i64,
    /// Aggregated value.
    #[serde(rename = "v")]
    pub value: f64,
}

/// One sample returned by the legacy CPU-only history route.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct LegacyCpuPoint {
    /// Unix timestamp in seconds.
    #[serde(rename = "t")]
    pub timestamp: i64,
    /// Aggregated CPU percentage.
    pub cpu: f64,
}

/// Xray metrics discovery and collection state.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct XrayMetricsState {
    /// Whether Xray metrics are configured and reachable.
    pub enabled: bool,
    /// Configured metrics listen address.
    pub listen: String,
    /// Explanation when metrics are unavailable.
    pub reason: String,
}

/// Latest observatory health snapshot for one outbound.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct XrayObservatoryEntry {
    /// Outbound tag.
    pub tag: String,
    /// Whether the latest probe succeeded.
    pub alive: bool,
    /// Probe delay in milliseconds.
    pub delay: i64,
    /// Last successful probe timestamp.
    pub last_seen_time: i64,
    /// Last attempted probe timestamp.
    pub last_try_time: i64,
    /// Snapshot update timestamp.
    pub updated_at: i64,
}

/// Available panel update information.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PanelUpdateInfo {
    /// `stable` or `dev`.
    pub channel: String,
    /// Installed version label.
    pub current_version: String,
    /// Latest available version label.
    pub latest_version: String,
    /// Installed commit for the dev channel.
    pub current_commit: String,
    /// Latest commit for the dev channel.
    pub latest_commit: String,
    /// Whether an update is available.
    pub update_available: bool,
}

/// Identifier returned after starting a panel self-update.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PanelUpdateRun {
    /// Decimal update run identifier.
    pub run_id: String,
}

/// State of a panel self-update.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum PanelUpdateState {
    /// Update is still running.
    Pending,
    /// Update completed successfully.
    Success,
    /// Update failed.
    Failed,
    /// A newer panel returned an unknown state.
    #[default]
    #[serde(other)]
    Unknown,
}

/// Outcome of the most recently started panel self-update.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PanelUpdateStatus {
    /// Decimal update run identifier.
    pub run_id: String,
    /// Current outcome.
    pub state: PanelUpdateState,
    /// Updater process exit code.
    pub exit_code: i32,
    /// Completion timestamp in Unix seconds, or zero while pending.
    pub finished_at: i64,
}

/// Whether IP-limit enforcement is available on this host.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
#[allow(clippy::struct_excessive_bools)]
pub struct Fail2banStatus {
    /// Whether integration is enabled by environment configuration.
    pub enabled: bool,
    /// Whether Fail2ban is installed.
    pub installed: bool,
    /// Whether client IP limits can be enforced.
    pub usable: bool,
    /// Whether the panel is running on Windows.
    pub windows: bool,
}

/// Read-only identity and health of a descendant panel node.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct NodeSummary {
    /// Stable node GUID.
    pub guid: String,
    /// Stable GUID of its managing panel.
    pub parent_guid: String,
    /// Display name.
    pub name: String,
    /// Host or IP address.
    pub address: String,
    /// HTTP scheme.
    pub scheme: String,
    /// HTTP port.
    pub port: i32,
    /// Connectivity state.
    pub status: String,
    /// Last heartbeat in Unix seconds.
    pub last_heartbeat: i64,
    /// Last heartbeat latency in milliseconds.
    pub latency_ms: i32,
    /// Panel version.
    pub panel_version: String,
    /// Xray version.
    pub xray_version: String,
    /// Xray process state.
    pub xray_state: String,
    /// Last Xray error.
    pub xray_error: String,
}

/// One recently observed client source IP.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ClientIpObservation {
    /// IP address.
    pub ip: String,
    /// Last-seen Unix timestamp in seconds.
    pub timestamp: i64,
}

/// Cluster-wide IP observations for one client.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct ClientIpRecord {
    /// Database row identifier. Remote identifiers are ignored during merge.
    pub id: i32,
    /// Unique client email/name.
    pub client_email: String,
    /// Recently observed source IPs; old/invalid panel rows may return `null`.
    #[serde(deserialize_with = "deserialize_null_default")]
    pub ips: Vec<ClientIpObservation>,
}

/// Generated X25519 Reality keypair.
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct X25519KeyPair {
    /// Private key.
    pub private_key: String,
    /// Public key.
    pub public_key: String,
}

impl fmt::Debug for X25519KeyPair {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("X25519KeyPair")
            .field("private_key", &"[REDACTED]")
            .field("public_key", &self.public_key)
            .finish()
    }
}

/// Generated ML-DSA-65 material.
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
pub struct Mldsa65KeyPair {
    /// Signing seed.
    pub seed: String,
    /// Verification key.
    pub verify: String,
}

impl fmt::Debug for Mldsa65KeyPair {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Mldsa65KeyPair")
            .field("seed", &"[REDACTED]")
            .field("verify", &self.verify)
            .finish()
    }
}

/// Generated ML-KEM-768 material.
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
pub struct Mlkem768KeyPair {
    /// Server seed.
    pub seed: String,
    /// Client key.
    pub client: String,
}

impl fmt::Debug for Mlkem768KeyPair {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Mlkem768KeyPair")
            .field("seed", &"[REDACTED]")
            .field("client", &self.client)
            .finish()
    }
}

/// Generated ECH server key and public config list.
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EchKeyPair {
    /// Private ECH server keys.
    pub ech_server_keys: String,
    /// Public ECH configuration list.
    pub ech_config_list: String,
}

impl fmt::Debug for EchKeyPair {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("EchKeyPair")
            .field("ech_server_keys", &"[REDACTED]")
            .field("ech_config_list", &self.ech_config_list)
            .finish()
    }
}

/// One generated VLESS encryption choice.
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
pub struct VlessEncryptionAuth {
    /// Stable choice identifier.
    pub id: String,
    /// Display label.
    pub label: String,
    /// Xray encryption value.
    pub encryption: String,
    /// Xray decryption value.
    pub decryption: String,
}

impl fmt::Debug for VlessEncryptionAuth {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("VlessEncryptionAuth")
            .field("id", &self.id)
            .field("label", &self.label)
            .field("encryption", &"[REDACTED]")
            .field("decryption", &"[REDACTED]")
            .finish()
    }
}

/// Generated VLESS encryption choices.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct VlessEncryptionOptions {
    /// Available authentication/encryption combinations.
    #[serde(deserialize_with = "deserialize_null_default")]
    pub auths: Vec<VlessEncryptionAuth>,
}

/// TLS certificate and key paths configured for the panel web server.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct WebCertificateFiles {
    /// Certificate chain path.
    pub web_cert_file: String,
    /// Private key path.
    pub web_key_file: String,
}

/// Structured result of probing a candidate REALITY target.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
#[allow(clippy::struct_excessive_bools)]
pub struct RealityScanResult {
    /// Original target.
    pub target: String,
    /// TLS server name.
    pub host: String,
    /// Resolved address.
    #[serde(rename = "ip")]
    pub ip_address: String,
    /// Target port.
    pub port: i32,
    /// Overall REALITY feasibility verdict.
    pub feasible: bool,
    /// Whether TLS 1.3 was negotiated.
    #[serde(rename = "tls13", alias = "TLS13")]
    pub tls13: bool,
    /// Negotiated TLS version.
    #[serde(rename = "tlsVersion", alias = "TLSVersion")]
    pub tls_version: String,
    /// Whether HTTP/2 was negotiated.
    #[serde(rename = "h2", alias = "H2")]
    pub h2: bool,
    /// Negotiated ALPN.
    #[serde(rename = "alpn", alias = "ALPN")]
    pub alpn: String,
    /// Whether X25519 was negotiated.
    #[serde(rename = "x25519", alias = "X25519")]
    pub x25519: bool,
    /// Negotiated curve identifier.
    #[serde(rename = "curveID", alias = "curveId")]
    pub curve_id: String,
    /// Whether the target resolved to a private address.
    pub private_target: bool,
    /// Whether the presented certificate chain is trusted, ignoring its name.
    pub cert_chain_valid: bool,
    /// Total DER certificate-chain size in bytes (ML-DSA-65 requires at least 3500).
    pub cert_chain_bytes: i32,
    /// Whether the certificate validated.
    pub cert_valid: bool,
    /// Leaf certificate subject.
    pub cert_subject: String,
    /// Leaf certificate issuer.
    pub cert_issuer: String,
    /// Certificate expiration in RFC 3339 form.
    pub not_after: String,
    /// Usable certificate server names.
    #[serde(deserialize_with = "deserialize_null_default")]
    pub server_names: Vec<String>,
    /// End-to-end probe latency in milliseconds.
    pub latency_ms: i32,
    /// Failure or infeasibility reason.
    pub reason: String,
}

/// Input for probing one REALITY target.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RealityScanRequest {
    /// Host, host:port, IP, or IP:port.
    pub target: String,
    /// Optional Xray version compatibility selector used by the panel.
    pub xray_version: i32,
}

impl RealityScanRequest {
    /// Creates a scan request using the panel's default compatibility mode.
    pub fn new(target: impl Into<String>) -> Self {
        Self {
            target: target.into(),
            xray_version: 0,
        }
    }
}

/// Panel application log level filter.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum LogLevel {
    /// No level filtering.
    #[default]
    All,
    /// Debug and above.
    Debug,
    /// Informational and above.
    Info,
    /// Warnings and errors.
    Warning,
    /// Errors only.
    Error,
}

impl LogLevel {
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::All => "",
            Self::Debug => "debug",
            Self::Info => "info",
            Self::Warning => "warning",
            Self::Error => "error",
        }
    }
}

/// Filters for reading panel logs.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct PanelLogRequest {
    /// Maximum number of trailing lines.
    pub count: u32,
    /// Minimum log level.
    pub level: LogLevel,
    /// Read the system journal instead of the panel log file.
    pub syslog: bool,
}

/// Filters for reading Xray logs.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct XrayLogRequest {
    /// Maximum number of trailing lines.
    pub count: u32,
    /// Free-text filter.
    pub filter: String,
    /// Include direct/freedom traffic.
    pub show_direct: bool,
    /// Include blocked/blackhole traffic.
    pub show_blocked: bool,
    /// Include proxy traffic.
    pub show_proxy: bool,
}

/// Traffic classification assigned to one parsed Xray access-log entry.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum XrayLogEvent {
    /// Direct/freedom outbound.
    #[default]
    Direct,
    /// Blocked/blackhole outbound.
    Blocked,
    /// Proxied outbound.
    Proxied,
    /// A newer panel returned an unknown numeric classification.
    Unknown,
}

impl From<i32> for XrayLogEvent {
    fn from(value: i32) -> Self {
        match value {
            0 => Self::Direct,
            1 => Self::Blocked,
            2 => Self::Proxied,
            _ => Self::Unknown,
        }
    }
}

impl From<XrayLogEvent> for i32 {
    fn from(value: XrayLogEvent) -> Self {
        match value {
            XrayLogEvent::Direct => 0,
            XrayLogEvent::Blocked => 1,
            XrayLogEvent::Proxied => 2,
            XrayLogEvent::Unknown => -1,
        }
    }
}

impl<'de> Deserialize<'de> for XrayLogEvent {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        i32::deserialize(deserializer).map(Self::from)
    }
}

impl Serialize for XrayLogEvent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        i32::from(*self).serialize(serializer)
    }
}

/// One structured entry parsed from the Xray access log.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "PascalCase")]
pub struct XrayLogEntry {
    /// UTC timestamp in RFC 3339 form.
    pub date_time: String,
    /// Client source address.
    pub from_address: String,
    /// Requested destination address.
    pub to_address: String,
    /// Inbound tag.
    pub inbound: String,
    /// Outbound tag.
    pub outbound: String,
    /// Client email/name when present.
    pub email: String,
    /// Direct, blocked, or proxied classification.
    pub event: XrayLogEvent,
}

/// Binary database backup or migration downloaded from the panel.
#[derive(Clone, Default, Eq, PartialEq)]
pub struct DatabaseFile {
    /// Suggested attachment filename, when supplied by the panel.
    pub filename: Option<String>,
    /// Response content type, when supplied by the panel.
    pub content_type: Option<String>,
    /// Complete file contents.
    pub bytes: Vec<u8>,
}

impl fmt::Debug for DatabaseFile {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DatabaseFile")
            .field("filename", &self.filename)
            .field("content_type", &self.content_type)
            .field(
                "bytes",
                &format_args!("[REDACTED; {} bytes]", self.bytes.len()),
            )
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn history_variants_match_the_source_allowlists() {
        let buckets = [
            HistoryBucket::Minutes2,
            HistoryBucket::Minutes30,
            HistoryBucket::Hour1,
            HistoryBucket::Hours3,
            HistoryBucket::Hours6,
            HistoryBucket::Hours12,
            HistoryBucket::Day1,
            HistoryBucket::Days2,
            HistoryBucket::Days7,
        ]
        .map(HistoryBucket::seconds);
        assert_eq!(buckets, [2, 30, 60, 180, 360, 720, 1_440, 2_880, 10_080]);

        let metrics = [
            SystemMetric::Cpu,
            SystemMetric::Memory,
            SystemMetric::Swap,
            SystemMetric::NetworkUp,
            SystemMetric::NetworkDown,
            SystemMetric::PacketUp,
            SystemMetric::PacketDown,
            SystemMetric::DiskRead,
            SystemMetric::DiskWrite,
            SystemMetric::DiskUsage,
            SystemMetric::TcpCount,
            SystemMetric::UdpCount,
            SystemMetric::Online,
            SystemMetric::Load1,
            SystemMetric::Load5,
            SystemMetric::Load15,
        ]
        .map(SystemMetric::as_str);
        assert_eq!(
            metrics,
            [
                "cpu",
                "mem",
                "swap",
                "netUp",
                "netDown",
                "pktUp",
                "pktDown",
                "diskRead",
                "diskWrite",
                "diskUsage",
                "tcpCount",
                "udpCount",
                "online",
                "load1",
                "load5",
                "load15",
            ]
        );
    }

    #[test]
    fn open_xray_config_has_explicit_secret_accessors() {
        let value = serde_json::json!({"privateKey": "xray-private-secret"});
        let config = XrayConfig::from(value.clone());
        assert_eq!(config.as_value(), &value);
        assert!(!format!("{config:?}").contains("xray-private-secret"));
        assert_eq!(config.into_value(), value);
    }

    #[test]
    fn xray_metrics_and_log_filters_match_wire_vocabulary() {
        assert_eq!(
            [
                XrayMetric::Alloc,
                XrayMetric::Sys,
                XrayMetric::HeapObjects,
                XrayMetric::NumGc,
                XrayMetric::PauseNs,
            ]
            .map(XrayMetric::as_str),
            ["xrAlloc", "xrSys", "xrHeapObjects", "xrNumGC", "xrPauseNs"]
        );
        assert_eq!(
            [
                LogLevel::All,
                LogLevel::Debug,
                LogLevel::Info,
                LogLevel::Warning,
                LogLevel::Error,
            ]
            .map(LogLevel::as_str),
            ["", "debug", "info", "warning", "error"]
        );

        for (wire, event) in [
            (0, XrayLogEvent::Direct),
            (1, XrayLogEvent::Blocked),
            (2, XrayLogEvent::Proxied),
            (99, XrayLogEvent::Unknown),
        ] {
            assert_eq!(XrayLogEvent::from(wire), event);
            let expected = if event == XrayLogEvent::Unknown {
                -1
            } else {
                wire
            };
            assert_eq!(i32::from(event), expected);
            assert_eq!(serde_json::to_value(event).unwrap(), expected);
            assert_eq!(
                serde_json::from_value::<XrayLogEvent>(serde_json::json!(wire)).unwrap(),
                event
            );
        }
    }

    #[test]
    fn generated_key_material_is_redacted_selectively() {
        let x25519 = X25519KeyPair {
            private_key: "x25519-private-secret".into(),
            public_key: "x25519-public".into(),
        };
        let mldsa = Mldsa65KeyPair {
            seed: "mldsa-seed-secret".into(),
            verify: "mldsa-verify".into(),
        };
        let mlkem = Mlkem768KeyPair {
            seed: "mlkem-seed-secret".into(),
            client: "mlkem-client".into(),
        };
        let ech = EchKeyPair {
            ech_server_keys: "ech-private-secret".into(),
            ech_config_list: "ech-public".into(),
        };
        let vless = VlessEncryptionAuth {
            id: "option-1".into(),
            label: "recommended".into(),
            encryption: "vless-encryption-secret".into(),
            decryption: "vless-decryption-secret".into(),
        };
        let cases = [
            (
                format!("{x25519:?}"),
                "x25519-private-secret",
                "x25519-public",
            ),
            (format!("{mldsa:?}"), "mldsa-seed-secret", "mldsa-verify"),
            (format!("{mlkem:?}"), "mlkem-seed-secret", "mlkem-client"),
            (format!("{ech:?}"), "ech-private-secret", "ech-public"),
            (
                format!("{vless:?}"),
                "vless-encryption-secret",
                "recommended",
            ),
        ];
        for (output, secret, visible) in cases {
            assert!(!output.contains(secret));
            assert!(output.contains(visible));
        }
        assert!(!format!("{vless:?}").contains("vless-decryption-secret"));
    }
}