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
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
#![allow(clippy::struct_excessive_bools)]

use std::{collections::BTreeMap, fmt};

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

/// Panel listener, session, and outbound settings.
#[derive(Clone, Default, Deserialize, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct WebSettings {
    /// Listener IP, or an empty string for all interfaces.
    pub web_listen: String,
    /// Public panel domain.
    pub web_domain: String,
    /// Panel TCP port.
    pub web_port: u16,
    /// TLS certificate path.
    pub web_cert_file: String,
    /// TLS private-key path.
    pub web_key_file: String,
    /// Secret panel base path.
    pub web_base_path: String,
    /// Session lifetime in minutes.
    pub session_max_age: u32,
    /// Comma-separated trusted reverse-proxy CIDRs.
    #[serde(rename = "trustedProxyCIDRs")]
    pub trusted_proxy_cidrs: String,
    /// Xray outbound tag used by panel-originated traffic.
    pub panel_outbound: String,
}

impl fmt::Debug for WebSettings {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("WebSettings")
            .field("web_listen", &self.web_listen)
            .field("web_domain", &self.web_domain)
            .field("web_port", &self.web_port)
            .field("web_cert_file", &self.web_cert_file)
            .field("web_key_file", &"[REDACTED]")
            .field("web_base_path", &"[REDACTED]")
            .field("session_max_age", &self.session_max_age)
            .field("trusted_proxy_cidrs", &self.trusted_proxy_cidrs)
            .field("panel_outbound", &"[REDACTED]")
            .finish_non_exhaustive()
    }
}

/// Panel display and warning thresholds.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct DisplaySettings {
    /// Rows per page.
    pub page_size: u32,
    /// Expiration warning window.
    pub expire_diff: u32,
    /// Traffic warning percentage.
    pub traffic_diff: u8,
    /// Inbound remark template.
    pub remark_template: String,
    /// Shows client identity on every generated link.
    pub sub_show_identity_on_all_links: bool,
    /// Date picker calendar identifier.
    pub datepicker: String,
}

/// Telegram notification settings.
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct TelegramSettings {
    /// Enables the Telegram bot.
    pub tg_bot_enable: bool,
    /// Telegram bot token. A blank update preserves the stored token.
    pub tg_bot_token: String,
    /// Optional bot proxy URL.
    pub tg_bot_proxy: String,
    /// Optional Telegram-compatible API server.
    #[serde(rename = "tgBotAPIServer")]
    pub tg_bot_api_server: String,
    /// Target chat identifier.
    pub tg_bot_chat_id: String,
    /// Scheduled report time.
    pub tg_run_time: String,
    /// Enables database backups through Telegram.
    pub tg_bot_backup: bool,
    /// CPU warning percentage.
    pub tg_cpu: u8,
    /// Memory warning percentage.
    pub tg_memory: u8,
    /// Notification language.
    pub tg_lang: String,
    /// Comma-separated enabled event identifiers.
    pub tg_enabled_events: String,
}

impl fmt::Debug for TelegramSettings {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TelegramSettings")
            .field("tg_bot_enable", &self.tg_bot_enable)
            .field("tg_bot_token", &"[REDACTED]")
            .field("tg_bot_proxy", &"[REDACTED]")
            .field("tg_bot_api_server", &self.tg_bot_api_server)
            .field("tg_bot_chat_id", &self.tg_bot_chat_id)
            .field("tg_run_time", &self.tg_run_time)
            .field("tg_bot_backup", &self.tg_bot_backup)
            .field("tg_cpu", &self.tg_cpu)
            .field("tg_memory", &self.tg_memory)
            .field("tg_lang", &self.tg_lang)
            .field("tg_enabled_events", &self.tg_enabled_events)
            .finish()
    }
}

/// SMTP notification settings.
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct SmtpSettings {
    /// Enables SMTP notifications.
    pub smtp_enable: bool,
    /// SMTP server host.
    pub smtp_host: String,
    /// SMTP server port.
    pub smtp_port: u16,
    /// SMTP username.
    pub smtp_username: String,
    /// SMTP password. A blank update preserves the stored password.
    pub smtp_password: String,
    /// Envelope sender address.
    pub smtp_from: String,
    /// Display name for the sender.
    pub smtp_from_name: String,
    /// Recipient address list.
    pub smtp_to: String,
    /// Encryption mode understood by 3x-ui.
    pub smtp_encryption_type: String,
    /// Comma-separated enabled event identifiers.
    pub smtp_enabled_events: String,
    /// CPU warning percentage.
    pub smtp_cpu: u8,
    /// Memory warning percentage.
    pub smtp_memory: u8,
}

impl fmt::Debug for SmtpSettings {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SmtpSettings")
            .field("smtp_enable", &self.smtp_enable)
            .field("smtp_host", &self.smtp_host)
            .field("smtp_port", &self.smtp_port)
            .field("smtp_username", &self.smtp_username)
            .field("smtp_password", &"[REDACTED]")
            .field("smtp_from", &self.smtp_from)
            .field("smtp_from_name", &self.smtp_from_name)
            .field("smtp_to", &self.smtp_to)
            .field("smtp_encryption_type", &self.smtp_encryption_type)
            .field("smtp_enabled_events", &self.smtp_enabled_events)
            .field("smtp_cpu", &self.smtp_cpu)
            .field("smtp_memory", &self.smtp_memory)
            .finish()
    }
}

/// Security, time-zone, and integration health settings.
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct SecuritySettings {
    /// Comma-separated host:port candidates for REALITY scans.
    pub reality_scan_candidates: String,
    /// Percentage below which an outbound is treated as down.
    pub outbound_down_threshold: u8,
    /// Comma-separated addresses or CIDRs exempt from client IP limits.
    pub ip_limit_allowlist: String,
    /// IANA time-zone name.
    pub time_location: String,
    /// Enables two-factor authentication.
    pub two_factor_enable: bool,
    /// Two-factor seed. It is redacted on reads.
    pub two_factor_token: String,
    /// Automatic WARP IP update interval.
    pub warp_update_interval: u32,
}

impl fmt::Debug for SecuritySettings {
    /// Formats security settings without exposing the two-factor authentication seed.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SecuritySettings")
            .field("reality_scan_candidates", &self.reality_scan_candidates)
            .field("outbound_down_threshold", &self.outbound_down_threshold)
            .field("ip_limit_allowlist", &self.ip_limit_allowlist)
            .field("time_location", &self.time_location)
            .field("two_factor_enable", &self.two_factor_enable)
            .field("two_factor_token", &"[REDACTED]")
            .field("warp_update_interval", &self.warp_update_interval)
            .finish()
    }
}

/// Subscription server and generated-format settings.
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct SubscriptionSettings {
    /// Enables local Happ Crypt5 link generation.
    pub happ_link_enable: bool,
    /// Adds a synthetic usage/status node to subscriptions.
    pub sub_info_node_enable: bool,
    /// Presents calendar expiry as the inclusive end of the previous month.
    pub sub_calendar_expire_inclusive: bool,
    /// Subscription template for expired clients.
    pub sub_expired_template: String,
    /// Subscription template for clients with depleted traffic.
    pub sub_traffic_depleted_template: String,
    /// Happ application settings, flattened on the wire.
    #[serde(flatten)]
    pub happ: HappSettings,
    /// Enables the subscription server.
    pub sub_enable: bool,
    /// Enables JSON subscriptions.
    pub sub_json_enable: bool,
    /// Auto-detects JSON subscription clients.
    pub sub_json_auto_detect: bool,
    /// Always emits a JSON array.
    pub sub_json_always_array: bool,
    /// User-agent regex for JSON subscriptions.
    pub sub_json_user_agent_regex: String,
    /// Auto-detects Clash clients.
    pub sub_clash_auto_detect: bool,
    /// User-agent regex for Clash subscriptions.
    pub sub_clash_user_agent_regex: String,
    /// Subscription title.
    pub sub_title: String,
    /// Support URL.
    pub sub_support_url: String,
    /// Profile page mode: `none` (default), `builtin`, or `custom`.
    pub sub_profile_mode: String,
    /// Profile URL.
    pub sub_profile_url: String,
    /// Announcement text.
    pub sub_announce: String,
    /// Enables base subscription routing rules.
    pub sub_enable_routing: bool,
    /// Base subscription routing rules.
    pub sub_routing_rules: String,
    /// Enables Incy routing rules.
    pub sub_incy_enable_routing: bool,
    /// Incy routing rules.
    pub sub_incy_routing_rules: String,
    /// Subscription listener IP.
    pub sub_listen: String,
    /// Subscription server port.
    pub sub_port: u16,
    /// Base subscription path.
    pub sub_path: String,
    /// Subscription domain.
    pub sub_domain: String,
    /// Subscription TLS certificate path.
    pub sub_cert_file: String,
    /// Subscription TLS private-key path.
    pub sub_key_file: String,
    /// Subscription update interval.
    pub sub_updates: u32,
    /// Enables external traffic reporting.
    pub external_traffic_inform_enable: bool,
    /// External traffic reporting URI.
    #[serde(rename = "externalTrafficInformURI")]
    pub external_traffic_inform_uri: String,
    /// Restarts Xray when a client is disabled.
    pub restart_xray_on_client_disable: bool,
    /// Encrypts subscription identifiers.
    pub sub_encrypt: bool,
    /// Public base subscription URI.
    #[serde(rename = "subURI")]
    pub sub_uri: String,
    /// JSON subscription path.
    pub sub_json_path: String,
    /// Public JSON subscription URI.
    #[serde(rename = "subJsonURI")]
    pub sub_json_uri: String,
    /// Enables Clash subscriptions.
    pub sub_clash_enable: bool,
    /// Clash subscription path.
    pub sub_clash_path: String,
    /// Public Clash subscription URI.
    #[serde(rename = "subClashURI")]
    pub sub_clash_uri: String,
    /// Enables Clash routing.
    pub sub_clash_enable_routing: bool,
    /// Clash routing rules.
    pub sub_clash_rules: String,
    /// JSON mux template.
    pub sub_json_mux: String,
    /// JSON routing rules.
    pub sub_json_rules: String,
    /// Additional JSON subscription routing rules.
    pub sub_json_routing_rules: String,
    /// DNS servers included in JSON subscriptions.
    pub sub_json_dns: String,
    /// JSON final-mask template.
    pub sub_json_final_mask: String,
    /// JSON observatory template merged into generated subscriptions.
    pub sub_json_observatory: String,
    /// Subscription theme directory.
    pub sub_theme_dir: String,
    /// Hides settings from subscription output.
    pub sub_hide_settings: bool,
}

impl fmt::Debug for SubscriptionSettings {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SubscriptionSettings")
            .field("sub_enable", &self.sub_enable)
            .field("sub_json_enable", &self.sub_json_enable)
            .field("sub_json_auto_detect", &self.sub_json_auto_detect)
            .field("sub_json_always_array", &self.sub_json_always_array)
            .field("sub_clash_auto_detect", &self.sub_clash_auto_detect)
            .field("sub_title", &self.sub_title)
            .field("sub_listen", &self.sub_listen)
            .field("sub_port", &self.sub_port)
            .field("sub_domain", &self.sub_domain)
            .field("sub_updates", &self.sub_updates)
            .field(
                "external_traffic_inform_enable",
                &self.external_traffic_inform_enable,
            )
            .field(
                "restart_xray_on_client_disable",
                &self.restart_xray_on_client_disable,
            )
            .field("sub_encrypt", &self.sub_encrypt)
            .field("sub_clash_enable", &self.sub_clash_enable)
            .field("sub_clash_enable_routing", &self.sub_clash_enable_routing)
            .field("sub_hide_settings", &self.sub_hide_settings)
            .field("paths_uris_rules_and_key_material", &"[REDACTED]")
            .finish_non_exhaustive()
    }
}

/// LDAP synchronization and client defaults.
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct LdapSettings {
    /// Enables LDAP synchronization.
    pub ldap_enable: bool,
    /// LDAP host.
    pub ldap_host: String,
    /// LDAP port.
    pub ldap_port: u16,
    /// Enables LDAP TLS.
    #[serde(rename = "ldapUseTLS")]
    pub ldap_use_tls: bool,
    /// Disables LDAP certificate verification.
    pub ldap_insecure_skip_verify: bool,
    /// Bind distinguished name.
    #[serde(rename = "ldapBindDN")]
    pub ldap_bind_dn: String,
    /// Bind password. A blank update preserves the stored password.
    pub ldap_password: String,
    /// Search base distinguished name.
    #[serde(rename = "ldapBaseDN")]
    pub ldap_base_dn: String,
    /// LDAP user filter.
    pub ldap_user_filter: String,
    /// LDAP username attribute.
    pub ldap_user_attr: String,
    /// LDAP field used for VLESS identity.
    pub ldap_vless_field: String,
    /// Synchronization cron expression.
    pub ldap_sync_cron: String,
    /// LDAP enabled/disabled flag field.
    pub ldap_flag_field: String,
    /// Values treated as true for the flag field.
    pub ldap_truthy_values: String,
    /// Inverts the LDAP flag.
    pub ldap_invert_flag: bool,
    /// Inbound tags assigned to synchronized clients.
    pub ldap_inbound_tags: String,
    /// Creates missing panel clients.
    pub ldap_auto_create: bool,
    /// Deletes panel clients absent from LDAP.
    pub ldap_auto_delete: bool,
    /// Default traffic quota in gigabytes.
    #[serde(rename = "ldapDefaultTotalGB")]
    pub ldap_default_total_gb: u64,
    /// Default expiry in days.
    pub ldap_default_expiry_days: u32,
    /// Default IP limit.
    #[serde(rename = "ldapDefaultLimitIP")]
    pub ldap_default_limit_ip: u32,
}

impl fmt::Debug for LdapSettings {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("LdapSettings")
            .field("ldap_enable", &self.ldap_enable)
            .field("ldap_host", &self.ldap_host)
            .field("ldap_port", &self.ldap_port)
            .field("ldap_use_tls", &self.ldap_use_tls)
            .field("ldap_insecure_skip_verify", &self.ldap_insecure_skip_verify)
            .field("ldap_bind_dn", &self.ldap_bind_dn)
            .field("ldap_password", &"[REDACTED]")
            .field("ldap_base_dn", &self.ldap_base_dn)
            .field("ldap_user_filter", &self.ldap_user_filter)
            .field("ldap_user_attr", &self.ldap_user_attr)
            .field("ldap_vless_field", &self.ldap_vless_field)
            .field("ldap_sync_cron", &self.ldap_sync_cron)
            .field("ldap_flag_field", &self.ldap_flag_field)
            .field("ldap_truthy_values", &self.ldap_truthy_values)
            .field("ldap_invert_flag", &self.ldap_invert_flag)
            .field("ldap_inbound_tags", &self.ldap_inbound_tags)
            .field("ldap_auto_create", &self.ldap_auto_create)
            .field("ldap_auto_delete", &self.ldap_auto_delete)
            .field("ldap_default_total_gb", &self.ldap_default_total_gb)
            .field("ldap_default_expiry_days", &self.ldap_default_expiry_days)
            .field("ldap_default_limit_ip", &self.ldap_default_limit_ip)
            .finish()
    }
}

/// Discord notification and bot settings.
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct DiscordSettings {
    /// Comma-separated Discord administrator user IDs.
    pub discord_admin_ids: String,
    /// Enables database backups through Discord.
    pub discord_bot_backup: bool,
    /// Enables the Discord notification bot.
    pub discord_bot_enable: bool,
    /// Discord bot token (blank updates preserve the stored token).
    pub discord_bot_token: String,
    /// Discord channel ID for notifications.
    pub discord_channel_id: String,
    /// CPU warning threshold in percent.
    pub discord_cpu: u8,
    /// Comma-separated enabled notification event names.
    pub discord_enabled_events: String,
    /// Notification language.
    pub discord_lang: String,
    /// Memory warning threshold in percent.
    pub discord_memory: u8,
    /// Scheduled report time.
    pub discord_run_time: String,
}

impl fmt::Debug for DiscordSettings {
    /// Identifies Discord settings in diagnostics without exposing their configuration or credentials.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DiscordSettings")
            .field("settings", &"[REDACTED]")
            .finish_non_exhaustive()
    }
}

/// Happ application management and routing settings.
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct HappSettings {
    /// Always requests device identification from Happ.
    pub sub_happ_always_hwid: bool,
    /// Automatically connects after importing the subscription.
    pub sub_happ_auto_connect: bool,
    /// Automatic connection selection policy.
    pub sub_happ_auto_connect_type: String,
    /// Emits Happ headers when its user agent is detected.
    pub sub_happ_auto_detect: bool,
    /// Application color profile.
    pub sub_happ_color_profile: String,
    /// Bypasses Apple Push Notification traffic.
    pub sub_happ_exclude_apns: bool,
    /// Routes excluded from the tunnel.
    pub sub_happ_exclude_routes: String,
    /// Fallback subscription URL.
    pub sub_happ_fallback_url: String,
    /// Replacement subscription URL.
    pub sub_happ_new_url: String,
    /// Enables the Happ no-limit indicator.
    pub sub_happ_no_limit: bool,
    /// Enables subscription expiry notifications.
    pub sub_happ_notification_expire: bool,
    /// Applications selected for per-app proxy rules.
    pub sub_happ_per_app_list: String,
    /// Per-app proxy policy: off, include, or exclude.
    pub sub_happ_per_app_mode: String,
    /// Latency probe mode.
    pub sub_happ_ping_type: String,
    /// Subscription provider identifier.
    pub sub_happ_provider_id: String,
    /// Enables the subscription expiry notice.
    pub sub_happ_sub_expire: bool,
    /// URL opened by the expiry notice button.
    pub sub_happ_sub_expire_button_link: String,
    /// URL opened by the subscription information button.
    pub sub_happ_sub_info_button_link: String,
    /// Subscription information button label.
    pub sub_happ_sub_info_button_text: String,
    /// Subscription information notice color.
    pub sub_happ_sub_info_color: String,
    /// Subscription information notice text.
    pub sub_happ_sub_info_text: String,
    /// Requested TUN mode.
    pub sub_happ_tun_mode: String,
    /// Requested TUN implementation.
    pub sub_happ_tun_type: String,
}

impl fmt::Debug for HappSettings {
    /// Identifies Happ settings in diagnostics without exposing application routing or subscription data.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("HappSettings")
            .field("settings", &"[REDACTED]")
            .finish_non_exhaustive()
    }
}

/// Complete persisted panel settings, grouped ergonomically but flattened on the wire.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(default)]
pub struct PanelSettings {
    /// Web listener and session settings.
    #[serde(flatten)]
    pub web: WebSettings,
    /// Display settings.
    #[serde(flatten)]
    pub display: DisplaySettings,
    /// Telegram settings.
    #[serde(flatten)]
    pub telegram: TelegramSettings,
    /// SMTP settings.
    #[serde(flatten)]
    pub smtp: SmtpSettings,
    /// Discord notification settings.
    #[serde(flatten)]
    pub discord: DiscordSettings,
    /// Security and integration settings.
    #[serde(flatten)]
    pub security: SecuritySettings,
    /// Subscription server settings.
    #[serde(flatten)]
    pub subscriptions: SubscriptionSettings,
    /// LDAP settings.
    #[serde(flatten)]
    pub ldap: LdapSettings,
}

/// Browser-safe settings view with secret-presence indicators.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PanelSettingsView {
    /// Redacted settings.
    #[serde(flatten)]
    pub settings: PanelSettings,
    /// A Telegram token is stored.
    pub has_tg_bot_token: bool,
    /// A two-factor seed is stored.
    pub has_two_factor_token: bool,
    /// An LDAP password is stored.
    pub has_ldap_password: bool,
    /// At least one API token exists.
    pub has_api_token: bool,
    /// WARP credentials are stored.
    pub has_warp_secret: bool,
    /// `NordVPN` credentials are stored.
    pub has_nord_secret: bool,
    /// A Discord bot token is stored.
    pub has_discord_bot_token: bool,
    /// An SMTP password is stored.
    pub has_smtp_password: bool,
}

/// Full-replacement settings update plus request-only secret controls.
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PanelSettingsUpdate {
    /// Complete settings replacement.
    #[serde(flatten)]
    pub settings: PanelSettings,
    /// Current 2FA code, required when disabling 2FA.
    pub two_factor_code: String,
    /// Explicitly clears the stored Discord bot token.
    pub clear_discord_bot_token: bool,
    /// Explicitly clears the stored Telegram token.
    pub clear_tg_bot_token: bool,
    /// Explicitly clears the stored LDAP password.
    pub clear_ldap_password: bool,
    /// Explicitly clears the stored SMTP password.
    pub clear_smtp_password: bool,
}

impl PanelSettingsUpdate {
    /// Creates an update that preserves redacted blank secrets.
    pub fn new(settings: PanelSettings) -> Self {
        Self {
            settings,
            ..Self::default()
        }
    }
}

/// Host-derived defaults used by the panel UI.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct EffectiveDefaults {
    /// Expiration warning window.
    pub expire_diff: i64,
    /// Traffic warning percentage.
    pub traffic_diff: i64,
    /// Page size.
    pub page_size: i64,
    /// Default certificate path.
    pub default_cert: String,
    /// Default key path.
    pub default_key: String,
    /// Whether Telegram is enabled.
    pub tg_bot_enable: bool,
    /// Subscription theme directory.
    pub sub_theme_dir: String,
    /// Whether the subscription server is enabled.
    pub sub_enable: bool,
    /// Whether JSON subscriptions are enabled.
    pub sub_json_enable: bool,
    /// Whether Clash subscriptions are enabled.
    pub sub_clash_enable: bool,
    /// Subscription title.
    pub sub_title: String,
    /// Base subscription URI.
    #[serde(rename = "subURI")]
    pub sub_uri: String,
    /// JSON subscription URI.
    #[serde(rename = "subJsonURI")]
    pub sub_json_uri: String,
    /// Clash subscription URI.
    #[serde(rename = "subClashURI")]
    pub sub_clash_uri: String,
    /// Calendar type.
    pub datepicker: String,
    /// Whether IP limits are active.
    pub ip_limit_enable: bool,
    /// Whether access logging is active.
    pub access_log_enable: bool,
    /// Web domain.
    pub web_domain: String,
    /// Subscription domain.
    pub sub_domain: String,
    /// Whether the development update channel is enabled.
    pub dev_channel_enable: bool,
    /// Whether this panel is a development build.
    pub is_dev_build: bool,
}

/// Factory defaults keyed by their 3x-ui setting names.
pub type FactoryDefaults = BTreeMap<String, String>;

/// Current and replacement panel credentials.
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserCredentialsUpdate {
    /// Current username.
    pub old_username: String,
    /// Current password.
    pub old_password: String,
    /// Replacement username.
    pub new_username: String,
    /// Replacement password.
    pub new_password: String,
    /// Current 2FA code when enabled.
    pub two_factor_code: String,
}

impl fmt::Debug for UserCredentialsUpdate {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("UserCredentialsUpdate")
            .field("old_username", &self.old_username)
            .field("old_password", &"[REDACTED]")
            .field("new_username", &self.new_username)
            .field("new_password", &"[REDACTED]")
            .field("two_factor_code", &"[REDACTED]")
            .finish()
    }
}

/// Metadata for a panel API token. The plaintext token is never returned by list calls.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiTokenMetadata {
    /// Database identifier.
    pub id: i64,
    /// User-provided token name.
    pub name: String,
    /// Whether authentication with this token is enabled.
    pub enabled: bool,
    /// Unix creation timestamp in seconds.
    pub created_at: i64,
    /// Authorization scope enforced by 3x-ui.
    #[serde(default)]
    pub scope: ApiTokenScope,
    /// Expiration timestamp in Unix milliseconds; zero means no expiry.
    #[serde(default)]
    pub expires_at: i64,
}

/// Authorization scope assigned to a 3x-ui API token.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum ApiTokenScope {
    /// Full panel API access.
    #[default]
    Admin,
    /// Read-only monitoring access.
    Monitor,
    /// Node synchronization access.
    NodeSync,
}

impl ApiTokenScope {
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Admin => "admin",
            Self::Monitor => "monitor",
            Self::NodeSync => "node-sync",
        }
    }
}

/// Options used when creating an API token.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiTokenCreateRequest {
    /// User-visible token name.
    pub name: String,
    /// Authorization scope.
    #[serde(default)]
    pub scope: ApiTokenScope,
    /// Expiration timestamp in Unix milliseconds; zero means no expiry.
    #[serde(default)]
    pub expires_at: i64,
}

impl ApiTokenCreateRequest {
    /// Creates a non-expiring administrative token request.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            scope: ApiTokenScope::Admin,
            expires_at: 0,
        }
    }
}

/// Newly created API token, whose plaintext value is shown exactly once.
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreatedApiToken {
    /// Database identifier.
    pub id: i64,
    /// User-provided token name.
    pub name: String,
    /// Plaintext bearer token.
    pub token: String,
    /// Whether authentication with this token is enabled.
    pub enabled: bool,
    /// Unix creation timestamp in seconds.
    pub created_at: i64,
    /// Authorization scope enforced by 3x-ui.
    pub scope: ApiTokenScope,
    /// Expiration timestamp in Unix milliseconds; zero means no expiry.
    pub expires_at: i64,
}

impl fmt::Debug for CreatedApiToken {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CreatedApiToken")
            .field("id", &self.id)
            .field("name", &self.name)
            .field("token", &"[REDACTED]")
            .field("enabled", &self.enabled)
            .field("created_at", &self.created_at)
            .field("scope", &self.scope)
            .field("expires_at", &self.expires_at)
            .finish()
    }
}

/// One geodata database resolved from Xray's asset directory.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct GeoFile {
    /// Basename inside the asset directory.
    pub name: String,
    /// Detected database kind, normally `site` or `ip`.
    pub kind: String,
    /// File size in bytes.
    pub size: i64,
    /// Modification timestamp in Unix milliseconds.
    pub modified_at: i64,
    /// Number of indexed categories.
    pub categories: i32,
    /// Parse error for a file that could not be indexed.
    pub error: String,
}

/// One category in a geosite or geoip database.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct GeoCategory {
    /// Case-insensitive category code.
    pub code: String,
    /// Number of contained entries.
    pub entries: i32,
    /// Domain attributes present in this category.
    pub attributes: Vec<String>,
}

/// Page of geodata categories.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct GeoCategoryPage {
    /// Selected category rows.
    pub items: Vec<GeoCategory>,
    /// Total matching row count before paging.
    pub total: i32,
}

/// One rule inside a geodata category.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct GeoEntry {
    /// Rule kind such as `domain`, `full`, `keyword`, `regexp`, or `cidr`.
    pub kind: String,
    /// Domain expression or CIDR value.
    pub value: String,
}

/// Page of rules inside a geodata category.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct GeoEntryPage {
    /// Selected rules.
    pub items: Vec<GeoEntry>,
    /// Total matching rule count before paging.
    pub total: i32,
}

/// One invalid or non-resolving routing token.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct GeodataTokenIssue {
    /// Original routing token.
    pub token: String,
    /// Stable reason such as `syntax`, `fileMissing`, or `categoryMissing`.
    pub reason: String,
    /// Referenced database filename, when parsed.
    pub file: String,
    /// Referenced category or missing attribute, when parsed.
    pub code: String,
}

/// Country represented in PIA's signed server catalog.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct PiaCountry {
    /// ISO 3166-1 alpha-2 country code.
    pub code: String,
}

/// PIA region metadata.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct PiaRegion {
    /// Provider region identifier.
    pub id: String,
    /// User-visible region name.
    pub name: String,
}

/// One PIA `WireGuard` server.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PiaServer {
    /// Provider hostname.
    pub hostname: String,
    /// Provider IP address.
    pub ip: String,
    /// Parent region identifier.
    pub region_id: String,
    /// Parent region name.
    pub region_name: String,
}

/// PIA regions and `WireGuard` servers for a selected country.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct PiaServers {
    /// Matching provider regions.
    pub regions: Vec<PiaRegion>,
    /// Matching `WireGuard` servers.
    pub servers: Vec<PiaServer>,
}

/// Redacted view of the stored PIA account.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PiaAccount {
    /// Stored PIA username.
    pub username: String,
    /// Masked username suitable for display.
    pub account_hint: String,
}

/// `WireGuard` material registered with one PIA server.
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PiaKey {
    /// Stable suggested Xray outbound tag.
    pub tag: String,
    /// Provider server hostname.
    pub hostname: String,
    /// Generated `WireGuard` private key.
    pub secret_key: String,
    /// Assigned peer address.
    pub address: String,
    /// Provider `WireGuard` public key.
    pub public_key: String,
    /// Provider `WireGuard` endpoint.
    pub endpoint: String,
}

impl fmt::Debug for PiaKey {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PiaKey")
            .field("tag", &self.tag)
            .field("hostname", &self.hostname)
            .field("secret_key", &"[REDACTED]")
            .field("address", &self.address)
            .field("public_key", &self.public_key)
            .field("endpoint", &self.endpoint)
            .finish()
    }
}

/// Structured result of the panel's SMTP connection test.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct SmtpTestResult {
    /// Whether every test stage succeeded.
    pub success: bool,
    /// Stage that succeeded or failed.
    #[serde(default)]
    pub stage: String,
    /// Human-readable result message.
    #[serde(default, rename = "msg")]
    pub message: String,
}

/// Open-ended Xray JSON returned by an integration action.
#[derive(Clone, Deserialize, PartialEq, Serialize)]
#[serde(transparent)]
pub struct SensitivePayload(String);

impl SensitivePayload {
    /// Borrows the original response string.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Parses the response as JSON when the action returned JSON.
    ///
    /// # Errors
    ///
    /// Returns a JSON decoding error when the response is empty or not JSON.
    pub fn json(&self) -> serde_json::Result<Value> {
        serde_json::from_str(&self.0)
    }
}

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

/// WARP key material used for registration.
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WarpRegistration {
    /// Existing WARP private key, or an empty string to generate one.
    pub private_key: String,
    /// Existing WARP public key, or an empty string to generate one.
    pub public_key: String,
}

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

/// Standard geodata download preset supplied by the panel.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct GeodataSource {
    /// Download URL.
    pub url: String,
    /// Destination database filename.
    pub file: String,
}

/// Decoded Xray settings response, including runtime-only subscription outbounds.
#[derive(Clone, Deserialize, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct XraySettingsSnapshot {
    /// Editable Xray template.
    pub xray_setting: crate::XrayConfig,
    /// Standard downloadable geodata source presets.
    pub geodata_sources: Vec<GeodataSource>,
    /// Known inbound tags.
    pub inbound_tags: Vec<String>,
    /// Client reverse-proxy tags.
    pub client_reverse_tags: Vec<String>,
    /// URL used for outbound tests.
    pub outbound_test_url: String,
    /// Runtime-injected subscription outbounds.
    pub subscription_outbounds: Vec<Value>,
    /// Tags of runtime-injected subscription outbounds.
    pub subscription_outbound_tags: Vec<String>,
}

impl Default for XraySettingsSnapshot {
    /// Creates an empty Xray settings snapshot with an object template and no runtime subscription outbounds.
    fn default() -> Self {
        Self {
            xray_setting: crate::XrayConfig::from(Value::Object(serde_json::Map::new())),
            inbound_tags: Vec::new(),
            geodata_sources: Vec::new(),
            client_reverse_tags: Vec::new(),
            outbound_test_url: String::new(),
            subscription_outbounds: Vec::new(),
            subscription_outbound_tags: Vec::new(),
        }
    }
}

impl fmt::Debug for XraySettingsSnapshot {
    /// Formats Xray settings metadata while redacting the template and runtime subscription outbounds.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("XraySettingsSnapshot")
            .field("geodata_sources", &self.geodata_sources)
            .field("xray_setting", &"[REDACTED]")
            .field("inbound_tags", &self.inbound_tags)
            .field("client_reverse_tags", &self.client_reverse_tags)
            .field("outbound_test_url", &self.outbound_test_url)
            .field("subscription_outbounds", &"[REDACTED]")
            .field(
                "subscription_outbound_tags",
                &self.subscription_outbound_tags,
            )
            .finish()
    }
}

/// Cumulative traffic counters for one Xray outbound.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct OutboundTraffic {
    /// Database identifier, when present.
    pub id: i64,
    /// Outbound tag.
    pub tag: String,
    /// Uploaded bytes.
    pub up: i64,
    /// Downloaded bytes.
    pub down: i64,
    /// Total byte allowance or counter.
    pub total: i64,
}

/// Probe mode for outbound tests.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum OutboundTestMode {
    /// Full HTTP probe through a temporary Xray instance.
    #[default]
    Http,
    /// Fast TCP dial-only probe.
    Tcp,
    /// Reports the cold full-request delay.
    Real,
}

impl OutboundTestMode {
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Http => "",
            Self::Tcp => "tcp",
            Self::Real => "real",
        }
    }
}

/// Result for one endpoint in a TCP-mode outbound test.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct TestEndpointResult {
    /// Endpoint address.
    pub address: String,
    /// Whether dialing succeeded.
    pub success: bool,
    /// Dial delay in milliseconds.
    pub delay: i64,
    /// Error message.
    pub error: String,
}

/// Public egress identity observed by an HTTP-mode test.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct TestEgressResult {
    /// Observed IPv4 address.
    pub ipv4: String,
    /// Observed IPv6 address.
    pub ipv6: String,
    /// Observed country code.
    pub country: String,
    /// Cloudflare WARP status.
    pub warp: String,
}

/// Result of an outbound connectivity test.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct OutboundTestResult {
    /// Tested outbound tag.
    pub tag: String,
    /// Whether the probe succeeded.
    pub success: bool,
    /// End-to-end delay in milliseconds.
    pub delay: i64,
    /// Failure message.
    pub error: String,
    /// Effective probe mode.
    pub mode: String,
    /// HTTP status returned by the test URL.
    pub http_status: i32,
    /// Local test-inbound connection time in milliseconds.
    pub connect_ms: i64,
    /// Outbound-chain and target TLS time in milliseconds.
    #[serde(rename = "tlsMs")]
    pub tls_ms: i64,
    /// Time to first byte in milliseconds.
    #[serde(rename = "ttfbMs")]
    pub ttfb_ms: i64,
    /// Per-endpoint TCP results.
    pub endpoints: Vec<TestEndpointResult>,
    /// Observed egress identity.
    pub egress: Option<TestEgressResult>,
}

/// Current live status of one Xray balancer.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct BalancerStatus {
    /// Balancer tag.
    pub tag: String,
    /// Whether the balancer exists in the running core.
    pub running: bool,
    /// Forced outbound target, if any.
    #[serde(rename = "override")]
    pub override_target: String,
    /// Targets selected by the strategy.
    pub selected: Vec<String>,
}

/// Synthetic connection used to test Xray routing.
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RouteTestRequest {
    /// Simulated inbound tag.
    pub inbound_tag: String,
    /// Destination domain.
    pub domain: String,
    /// Destination IP.
    pub ip: String,
    /// Destination port.
    pub port: u16,
    /// Network, usually `tcp` or `udp`.
    pub network: String,
    /// Optional sniffed protocol.
    pub protocol: String,
    /// Optional user email.
    pub email: String,
}

/// Routing decision returned by Xray.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct RouteTestResult {
    /// Whether a routing rule matched.
    pub matched: bool,
    /// Selected outbound tag.
    pub outbound_tag: String,
    /// Balancer chain traversed by the decision.
    pub group_tags: Vec<String>,
}

/// Stored remote outbound subscription.
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct OutboundSubscription {
    /// Database identifier.
    pub id: i64,
    /// User-visible remark.
    pub remark: String,
    /// Remote subscription URL.
    pub url: String,
    /// Whether it contributes outbounds.
    pub enabled: bool,
    /// Whether private destination addresses are allowed.
    pub allow_private: bool,
    /// Whether invalid TLS certificates are accepted.
    pub allow_insecure: bool,
    /// User agent used to fetch this remote subscription.
    pub user_agent: String,
    /// Prefix applied to generated outbound tags.
    pub tag_prefix: String,
    /// Refresh interval in seconds.
    pub update_interval: i32,
    /// Merge priority.
    pub priority: i32,
    /// Whether remote outbounds precede manual outbounds.
    pub prepend: bool,
    /// Last successful refresh timestamp.
    pub last_updated: i64,
    /// Last refresh error.
    pub last_error: String,
    /// Cached raw outbounds, normally redacted by list operations.
    pub last_fetched_outbounds: String,
    /// Unix creation timestamp in milliseconds.
    pub created_at: i64,
    /// Unix update timestamp in milliseconds.
    pub updated_at: i64,
    /// Parsed outbound count.
    pub outbound_count: i32,
}

impl fmt::Debug for OutboundSubscription {
    /// Formats outbound-subscription state while redacting its URL, user agent, and cached outbounds.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("OutboundSubscription")
            .field("user_agent", &"[REDACTED]")
            .field("id", &self.id)
            .field("remark", &self.remark)
            .field("url", &"[REDACTED]")
            .field("enabled", &self.enabled)
            .field("allow_private", &self.allow_private)
            .field("allow_insecure", &self.allow_insecure)
            .field("tag_prefix", &self.tag_prefix)
            .field("update_interval", &self.update_interval)
            .field("priority", &self.priority)
            .field("prepend", &self.prepend)
            .field("last_updated", &self.last_updated)
            .field("last_error", &self.last_error)
            .field("last_fetched_outbounds", &"[REDACTED]")
            .field("created_at", &self.created_at)
            .field("updated_at", &self.updated_at)
            .field("outbound_count", &self.outbound_count)
            .finish()
    }
}

/// Full replacement payload for a remote outbound subscription.
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OutboundSubscriptionInput {
    /// User-visible remark.
    pub remark: String,
    /// Remote subscription URL.
    pub url: String,
    /// User agent used to fetch this remote subscription.
    pub user_agent: String,
    /// Prefix applied to generated tags.
    pub tag_prefix: String,
    /// Whether it contributes outbounds.
    pub enabled: bool,
    /// Whether private destination addresses are allowed.
    pub allow_private: bool,
    /// Whether invalid TLS certificates are accepted.
    pub allow_insecure: bool,
    /// Whether remote outbounds precede manual outbounds.
    pub prepend: bool,
    /// Refresh interval in seconds.
    pub update_interval: i32,
}

impl OutboundSubscriptionInput {
    /// Creates enabled subscription input with the upstream 600-second interval.
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            remark: String::new(),
            url: url.into(),
            tag_prefix: String::new(),
            user_agent: String::new(),
            enabled: true,
            allow_private: false,
            allow_insecure: false,
            prepend: false,
            update_interval: 600,
        }
    }
}

impl fmt::Debug for OutboundSubscriptionInput {
    /// Formats outbound-subscription options while redacting the URL and custom user agent.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("OutboundSubscriptionInput")
            .field("user_agent", &"[REDACTED]")
            .field("remark", &self.remark)
            .field("url", &"[REDACTED]")
            .field("tag_prefix", &self.tag_prefix)
            .field("enabled", &self.enabled)
            .field("allow_private", &self.allow_private)
            .field("allow_insecure", &self.allow_insecure)
            .field("prepend", &self.prepend)
            .field("update_interval", &self.update_interval)
            .finish()
    }
}

/// Direction used to reorder an outbound subscription.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum MoveDirection {
    /// Move toward lower priority numbers.
    Up,
    /// Move toward higher priority numbers.
    Down,
}

impl MoveDirection {
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Up => "up",
            Self::Down => "down",
        }
    }
}

/// Secret-bearing list of parsed Xray outbounds.
#[derive(Clone, Default, Deserialize, PartialEq, Serialize)]
#[serde(transparent)]
pub struct OutboundDocuments(Vec<Value>);

impl OutboundDocuments {
    /// Borrows parsed outbound JSON documents.
    pub fn as_slice(&self) -> &[Value] {
        &self.0
    }
    /// Consumes the wrapper.
    pub fn into_inner(self) -> Vec<Value> {
        self.0
    }
}

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

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

    #[test]
    fn secret_bearing_models_redact_debug_output() {
        let credentials = UserCredentialsUpdate {
            old_username: "old-user".into(),
            old_password: "old-password-secret".into(),
            new_username: "new-user".into(),
            new_password: "new-password-secret".into(),
            two_factor_code: "123456-secret".into(),
        };
        let created = CreatedApiToken {
            id: 7,
            name: "automation".into(),
            token: "bearer-token-secret".into(),
            enabled: true,
            created_at: 10,
            scope: ApiTokenScope::Monitor,
            expires_at: 20,
        };
        let pia_key: PiaKey = serde_json::from_value(json!({
            "tag": "pia-de",
            "hostname": "de.example.com",
            "secretKey": "pia-private-secret",
            "address": "10.0.0.2/32",
            "publicKey": "public-key",
            "endpoint": "de.example.com:1337"
        }))
        .unwrap();
        let registration = WarpRegistration {
            private_key: "warp-private-secret".into(),
            public_key: "warp-public".into(),
        };
        let outbound: OutboundSubscription = serde_json::from_value(json!({
            "id": 9,
            "remark": "remote",
            "url": "https://user:subscription-secret@example.com/sub",
            "enabled": true,
            "lastFetchedOutbounds": "outbound-private-secret"
        }))
        .unwrap();
        let input = OutboundSubscriptionInput::new(
            "https://user:input-subscription-secret@example.com/sub",
        );
        let documents: OutboundDocuments =
            serde_json::from_value(json!([{"password": "document-secret"}])).unwrap();
        let snapshot = XraySettingsSnapshot {
            xray_setting: crate::XrayConfig::from(json!({"privateKey": "xray-secret"})),
            subscription_outbounds: vec![json!({"password": "snapshot-secret"})],
            ..XraySettingsSnapshot::default()
        };

        let outputs = [
            format!("{credentials:?}"),
            format!("{created:?}"),
            format!("{pia_key:?}"),
            format!("{registration:?}"),
            format!("{outbound:?}"),
            format!("{input:?}"),
            format!("{documents:?}"),
            format!("{snapshot:?}"),
        ];
        for (output, secret) in outputs.iter().zip([
            "old-password-secret",
            "bearer-token-secret",
            "pia-private-secret",
            "warp-private-secret",
            "subscription-secret",
            "input-subscription-secret",
            "document-secret",
            "snapshot-secret",
        ]) {
            assert!(!output.contains(secret));
            assert!(output.contains("REDACTED"));
        }
    }

    #[test]
    fn helpers_preserve_wire_values_and_owned_payloads() {
        assert_eq!(ApiTokenScope::Admin.as_str(), "admin");
        assert_eq!(ApiTokenScope::Monitor.as_str(), "monitor");
        assert_eq!(ApiTokenScope::NodeSync.as_str(), "node-sync");
        let request = ApiTokenCreateRequest::new("deploy");
        assert_eq!(request.name, "deploy");
        assert_eq!(request.scope, ApiTokenScope::Admin);
        assert_eq!(request.expires_at, 0);

        let payload: SensitivePayload = serde_json::from_value(json!("{\"ok\":true}")).unwrap();
        assert_eq!(payload.as_str(), "{\"ok\":true}");
        assert_eq!(payload.json().unwrap(), json!({"ok": true}));
        assert!(
            serde_json::from_value::<SensitivePayload>(json!("not-json"))
                .unwrap()
                .json()
                .is_err()
        );
        assert!(!format!("{payload:?}").contains("ok"));

        assert_eq!(OutboundTestMode::Http.as_str(), "");
        assert_eq!(OutboundTestMode::Tcp.as_str(), "tcp");
        assert_eq!(OutboundTestMode::Real.as_str(), "real");
        assert_eq!(MoveDirection::Up.as_str(), "up");
        assert_eq!(MoveDirection::Down.as_str(), "down");

        let documents: OutboundDocuments =
            serde_json::from_value(json!([{"tag": "one"}, {"tag": "two"}])).unwrap();
        assert_eq!(documents.as_slice().len(), 2);
        assert_eq!(documents.into_inner()[1]["tag"], "two");
    }
}