xui-rs 2.0.1

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
#![allow(clippy::struct_excessive_bools)]

use std::fmt;

use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
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)
}

/// TLS/security override applied to generated host links.
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum HostSecurity {
    /// Inherit security from the inbound.
    #[default]
    Same,
    /// Force TLS.
    Tls,
    /// Disable transport security.
    None,
    /// Force REALITY.
    Reality,
    /// Value introduced by a newer panel release.
    Other(String),
}

impl HostSecurity {
    /// Returns the exact 3x-ui wire value.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Same => "same",
            Self::Tls => "tls",
            Self::None => "none",
            Self::Reality => "reality",
            Self::Other(value) => value,
        }
    }
}

impl Serialize for HostSecurity {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for HostSecurity {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Ok(match value.as_str() {
            "" | "same" => Self::Same,
            "tls" => Self::Tls,
            "none" => Self::None,
            "reality" => Self::Reality,
            _ => Self::Other(value),
        })
    }
}

/// IP-family preference emitted for Mihomo subscriptions.
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum MihomoIpVersion {
    /// No override.
    #[default]
    Inherit,
    /// Dual stack without preference.
    Dual,
    /// IPv4 only.
    Ipv4,
    /// IPv6 only.
    Ipv6,
    /// Dual stack preferring IPv4.
    Ipv4Prefer,
    /// Dual stack preferring IPv6.
    Ipv6Prefer,
    /// Value introduced by a newer panel release.
    Other(String),
}

impl MihomoIpVersion {
    /// Returns the exact 3x-ui wire value.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Inherit => "",
            Self::Dual => "dual",
            Self::Ipv4 => "ipv4",
            Self::Ipv6 => "ipv6",
            Self::Ipv4Prefer => "ipv4-prefer",
            Self::Ipv6Prefer => "ipv6-prefer",
            Self::Other(value) => value,
        }
    }
}

impl Serialize for MihomoIpVersion {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for MihomoIpVersion {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Ok(match value.as_str() {
            "" => Self::Inherit,
            "dual" => Self::Dual,
            "ipv4" => Self::Ipv4,
            "ipv6" => Self::Ipv6,
            "ipv4-prefer" => Self::Ipv4Prefer,
            "ipv6-prefer" => Self::Ipv6Prefer,
            _ => Self::Other(value),
        })
    }
}

/// Subscription representation from which a host should be excluded.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum SubscriptionFormat {
    /// Raw share-link subscription.
    Raw,
    /// JSON subscription.
    Json,
    /// Clash/Mihomo subscription.
    Clash,
    /// Value introduced by a newer panel release.
    Other(String),
}

impl SubscriptionFormat {
    /// Returns the exact 3x-ui wire value.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Raw => "raw",
            Self::Json => "json",
            Self::Clash => "clash",
            Self::Other(value) => value,
        }
    }
}

impl Serialize for SubscriptionFormat {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for SubscriptionFormat {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Ok(match value.as_str() {
            "raw" => Self::Raw,
            "json" => Self::Json,
            "clash" => Self::Clash,
            _ => Self::Other(value),
        })
    }
}

/// Optional VLESS route port embedded into generated subscription identities.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct VlessRoute(Option<u16>);

impl VlessRoute {
    /// Creates a configured route port.
    pub const fn new(port: u16) -> Self {
        Self(Some(port))
    }

    /// Returns the configured port, or `None` when the override is disabled.
    pub const fn port(self) -> Option<u16> {
        self.0
    }
}

impl From<u16> for VlessRoute {
    fn from(port: u16) -> Self {
        Self::new(port)
    }
}

impl Serialize for VlessRoute {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self.0 {
            Some(port) => serializer.serialize_str(&port.to_string()),
            None => serializer.serialize_str(""),
        }
    }
}

impl<'de> Deserialize<'de> for VlessRoute {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct Visitor;

        impl de::Visitor<'_> for Visitor {
            type Value = VlessRoute;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("an empty string or a port from 0 through 65535")
            }

            fn visit_none<E>(self) -> Result<Self::Value, E> {
                Ok(VlessRoute::default())
            }

            fn visit_unit<E>(self) -> Result<Self::Value, E> {
                Ok(VlessRoute::default())
            }

            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                u16::try_from(value)
                    .map(VlessRoute::new)
                    .map_err(|_| E::custom("VLESS route is outside the port range"))
            }

            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                u16::try_from(value)
                    .map(VlessRoute::new)
                    .map_err(|_| E::custom("VLESS route is outside the port range"))
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                if value.is_empty() {
                    return Ok(VlessRoute::default());
                }
                value.parse::<u16>().map(VlessRoute::new).map_err(E::custom)
            }
        }

        deserializer.deserialize_any(Visitor)
    }
}

/// JSON override stored by 3x-ui as a string field.
///
/// The SDK preserves the raw value for forward compatibility while offering
/// structured construction and parsing, so callers never have to stringify
/// JSON manually.
#[derive(Clone, Default, Eq, PartialEq)]
pub struct HostJsonOverride(String);

impl HostJsonOverride {
    /// Serializes a structured JSON override.
    ///
    /// # Errors
    ///
    /// Returns an error when the JSON value cannot be encoded.
    pub fn from_value(value: &Value) -> serde_json::Result<Self> {
        serde_json::to_string(value).map(Self)
    }

    /// Creates an empty override that inherits the panel/inbound setting.
    pub const fn empty() -> Self {
        Self(String::new())
    }

    /// Borrows the exact string stored by 3x-ui.
    pub fn as_raw(&self) -> &str {
        &self.0
    }

    /// Returns whether the override is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Parses the configured JSON, returning `None` for an empty override.
    ///
    /// # Errors
    ///
    /// Returns an error when a non-empty legacy value is not valid JSON.
    pub fn value(&self) -> serde_json::Result<Option<Value>> {
        if self.is_empty() {
            Ok(None)
        } else {
            serde_json::from_str(&self.0).map(Some)
        }
    }
}

impl fmt::Debug for HostJsonOverride {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("HostJsonOverride")
            .field(&if self.is_empty() {
                "[EMPTY]"
            } else {
                "[CONFIGURED]"
            })
            .finish()
    }
}

impl Serialize for HostJsonOverride {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for HostJsonOverride {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Option::<String>::deserialize(deserializer).map(|value| Self(value.unwrap_or_default()))
    }
}

/// Writable override fields shared by grouped and database-row host views.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct HostOptions {
    /// Group order among generated host links.
    pub sort_order: i64,
    /// User-visible name.
    pub remark: String,
    /// Optional short server description.
    pub server_description: String,
    /// Whether the host is disabled.
    pub is_disabled: bool,
    /// Whether the host is hidden from normal subscription output.
    pub is_hidden: bool,
    /// Operator-defined uppercase tags.
    #[serde(deserialize_with = "deserialize_null_default")]
    pub tags: Vec<String>,
    /// Default port used when a host string does not include one.
    pub port: u16,
    /// TLS/security override.
    pub security: HostSecurity,
    /// TLS/REALITY server name override.
    pub sni: String,
    /// HTTP Host header override.
    pub host_header: String,
    /// Transport path override.
    pub path: String,
    /// ALPN override list.
    #[serde(deserialize_with = "deserialize_null_default")]
    pub alpn: Vec<String>,
    /// uTLS fingerprint identifier.
    pub fingerprint: String,
    /// Derives SNI from each configured host address.
    pub override_sni_from_address: bool,
    /// Keeps SNI blank instead of inheriting it.
    pub keep_sni_blank: bool,
    /// Accepted peer certificate SHA-256 pins.
    #[serde(deserialize_with = "deserialize_null_default")]
    pub pinned_peer_cert_sha256: Vec<String>,
    /// Peer certificate DNS name to verify.
    pub verify_peer_cert_by_name: String,
    /// Disables peer certificate verification.
    pub allow_insecure: bool,
    /// ECH configuration list.
    pub ech_config_list: String,
    /// Xray mux override stored as nested JSON.
    pub mux_params: HostJsonOverride,
    /// Xray socket options stored as nested JSON.
    pub sockopt_params: HostJsonOverride,
    /// Xray final-mask override stored as nested JSON.
    pub final_mask: HostJsonOverride,
    /// Optional VLESS route port.
    pub vless_route: VlessRoute,
    /// Subscription formats that should omit this host.
    #[serde(deserialize_with = "deserialize_null_default")]
    pub exclude_from_sub_types: Vec<SubscriptionFormat>,
    /// Node GUID allowlist for this override.
    #[serde(deserialize_with = "deserialize_null_default")]
    pub node_guids: Vec<String>,
    /// Mihomo IP-family preference.
    #[serde(rename = "mihomoIpVersion")]
    pub mihomo_ip_version: MihomoIpVersion,
    /// Enables Mihomo X25519 output.
    pub mihomo_x25519: bool,
    /// Randomizes host selection in generated output.
    pub shuffle_host: bool,
}

/// One logical host override shared across one or more inbounds and addresses.
///
/// The same type is accepted for create and full-replacement update operations.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct HostGroup {
    /// Stable logical group identifier. Leave blank on create to generate one.
    pub group_id: String,
    /// Inbounds to which this group applies.
    #[serde(deserialize_with = "deserialize_null_default")]
    pub inbound_ids: Vec<i64>,
    /// Hostnames/IPs, optionally including per-address ports.
    #[serde(deserialize_with = "deserialize_null_default")]
    pub hosts: Vec<String>,
    /// Shared host override options.
    #[serde(flatten)]
    pub options: HostOptions,
}

impl HostGroup {
    /// Creates an enabled group that inherits inbound security.
    pub fn new(inbound_ids: Vec<i64>, remark: impl Into<String>) -> Self {
        Self {
            inbound_ids,
            options: HostOptions {
                remark: remark.into(),
                ..HostOptions::default()
            },
            ..Self::default()
        }
    }
}

/// One physical database row created for a group/address/inbound combination.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct HostRow {
    /// Database identifier.
    pub id: i64,
    /// Logical group identifier.
    pub group_id: String,
    /// Parent inbound identifier.
    pub inbound_id: i64,
    /// Hostname or IP without its port.
    pub address: String,
    /// Shared host override options.
    #[serde(flatten)]
    pub options: HostOptions,
    /// Unix creation timestamp in milliseconds.
    pub created_at: i64,
    /// Unix update timestamp in milliseconds.
    pub updated_at: i64,
}

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

    #[test]
    fn extensible_host_enums_round_trip_known_and_future_values() {
        for value in [
            HostSecurity::Same,
            HostSecurity::Tls,
            HostSecurity::None,
            HostSecurity::Reality,
            HostSecurity::Other("future-security".into()),
        ] {
            let wire = value.as_str().to_owned();
            assert_eq!(serde_json::to_value(&value).unwrap(), wire);
            assert_eq!(
                serde_json::from_value::<HostSecurity>(json!(wire)).unwrap(),
                value
            );
        }
        assert_eq!(
            serde_json::from_value::<HostSecurity>(json!("")).unwrap(),
            HostSecurity::Same
        );

        for value in [
            MihomoIpVersion::Inherit,
            MihomoIpVersion::Dual,
            MihomoIpVersion::Ipv4,
            MihomoIpVersion::Ipv6,
            MihomoIpVersion::Ipv4Prefer,
            MihomoIpVersion::Ipv6Prefer,
            MihomoIpVersion::Other("future-ip-mode".into()),
        ] {
            let wire = value.as_str().to_owned();
            assert_eq!(serde_json::to_value(&value).unwrap(), wire);
            assert_eq!(
                serde_json::from_value::<MihomoIpVersion>(json!(wire)).unwrap(),
                value
            );
        }

        for value in [
            SubscriptionFormat::Raw,
            SubscriptionFormat::Json,
            SubscriptionFormat::Clash,
            SubscriptionFormat::Other("future-format".into()),
        ] {
            let wire = value.as_str().to_owned();
            assert_eq!(serde_json::to_value(&value).unwrap(), wire);
            assert_eq!(
                serde_json::from_value::<SubscriptionFormat>(json!(wire)).unwrap(),
                value
            );
        }
    }

    #[test]
    fn vless_route_accepts_every_upstream_representation() {
        let configured = VlessRoute::new(8443);
        assert_eq!(configured.port(), Some(8443));
        assert_eq!(VlessRoute::from(443).port(), Some(443));
        assert_eq!(serde_json::to_value(configured).unwrap(), "8443");
        assert_eq!(serde_json::to_value(VlessRoute::default()).unwrap(), "");
        assert_eq!(
            serde_json::from_value::<VlessRoute>(json!(2053))
                .unwrap()
                .port(),
            Some(2053)
        );
        assert_eq!(
            serde_json::from_value::<VlessRoute>(json!("2087"))
                .unwrap()
                .port(),
            Some(2087)
        );
        assert_eq!(
            serde_json::from_value::<VlessRoute>(Value::Null)
                .unwrap()
                .port(),
            None
        );
        assert!(serde_json::from_value::<VlessRoute>(json!(-1)).is_err());
        assert!(serde_json::from_value::<VlessRoute>(json!(70_000)).is_err());
        assert!(serde_json::from_value::<VlessRoute>(json!("invalid")).is_err());
    }

    #[test]
    fn nested_json_override_preserves_data_but_redacts_debug() {
        let value = json!({"password": "host-json-secret"});
        let configured = HostJsonOverride::from_value(&value).unwrap();
        assert!(!configured.is_empty());
        assert_eq!(configured.value().unwrap(), Some(value));
        assert!(configured.as_raw().contains("host-json-secret"));
        assert_eq!(
            format!("{configured:?}"),
            "HostJsonOverride(\"[CONFIGURED]\")"
        );

        let empty = HostJsonOverride::empty();
        assert!(empty.is_empty());
        assert_eq!(empty.value().unwrap(), None);
        assert_eq!(format!("{empty:?}"), "HostJsonOverride(\"[EMPTY]\")");
        assert_eq!(
            serde_json::from_value::<HostJsonOverride>(Value::Null).unwrap(),
            empty
        );
        let invalid: HostJsonOverride = serde_json::from_value(json!("not-json")).unwrap();
        assert!(invalid.value().is_err());
    }

    #[test]
    fn host_group_constructor_sets_only_safe_defaults() {
        let group = HostGroup::new(vec![7, 9], "production");
        assert_eq!(group.inbound_ids, [7, 9]);
        assert_eq!(group.options.remark, "production");
        assert_eq!(group.options.security, HostSecurity::Same);
        assert!(group.group_id.is_empty());
        assert!(group.hosts.is_empty());
    }
}