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
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
use std::time::Duration;

use reqwest::{Method, header};
use serde_json::Value;
use url::Url;

use super::{
    SubscriptionDevice, SubscriptionDocument, SubscriptionInfo, SubscriptionJson,
    SubscriptionMetadata, SubscriptionResponse,
};
use crate::{
    Error, ProxyConfig, Result, SubscriptionSettings,
    transport::{self, ErrorUrlPolicy},
};

const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const DEFAULT_USER_AGENT: &str = concat!("xui-rs/", env!("CARGO_PKG_VERSION"));

/// Default maximum public subscription response body size: 64 MiB.
pub const DEFAULT_SUBSCRIPTION_RESPONSE_BODY_LIMIT: usize = 64 * 1024 * 1024;

/// Builder for a public standalone [`SubscriptionClient`].
#[must_use]
pub struct SubscriptionClientBuilder {
    base_url: Url,
    raw_path: String,
    json_path: String,
    clash_path: String,
    timeout: Duration,
    connect_timeout: Duration,
    accept_invalid_certs: bool,
    proxy: Option<ProxyConfig>,
    response_body_limit: usize,
    device: Option<SubscriptionDevice>,
}

impl SubscriptionClientBuilder {
    fn new(base_url: impl AsRef<str>) -> Result<Self> {
        Ok(Self {
            base_url: normalize_server_url(base_url.as_ref())?,
            raw_path: "sub/".to_owned(),
            json_path: "json/".to_owned(),
            clash_path: "clash/".to_owned(),
            timeout: DEFAULT_TIMEOUT,
            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
            accept_invalid_certs: false,
            proxy: None,
            response_body_limit: DEFAULT_SUBSCRIPTION_RESPONSE_BODY_LIMIT,
            device: None,
        })
    }

    /// Sets the configured raw subscription path (default `/sub/`).
    pub fn raw_path(mut self, path: impl Into<String>) -> Self {
        self.raw_path = path.into();
        self
    }

    /// Sets the configured JSON subscription path (default `/json/`).
    pub fn json_path(mut self, path: impl Into<String>) -> Self {
        self.json_path = path.into();
        self
    }

    /// Sets the configured Clash subscription path (default `/clash/`).
    pub fn clash_path(mut self, path: impl Into<String>) -> Self {
        self.clash_path = path.into();
        self
    }

    /// Sets the total timeout for one subscription request.
    pub const fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Sets the timeout for establishing a connection.
    pub const fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// Accepts invalid TLS certificates for this subscription server.
    ///
    /// This weakens transport security for credential-bearing documents and
    /// should only be used with an explicitly trusted self-signed deployment.
    pub const fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
        self.accept_invalid_certs = accept;
        self
    }

    /// Routes subscription HTTP requests through an explicit proxy.
    ///
    /// Environment proxy variables are never consulted.
    pub fn proxy(mut self, proxy: ProxyConfig) -> Self {
        self.proxy = Some(proxy);
        self
    }

    /// Parses and configures a credential-free proxy URL.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Configuration`] for an invalid proxy URL.
    pub fn proxy_url(self, proxy_url: impl AsRef<str>) -> Result<Self> {
        Ok(self.proxy(ProxyConfig::new(proxy_url)?))
    }

    /// Removes a previously configured explicit proxy.
    pub fn no_proxy(mut self) -> Self {
        self.proxy = None;
        self
    }

    /// Sets the maximum in-memory size of a subscription response body.
    ///
    /// Both declared `Content-Length` and actually received chunked or
    /// decompressed bytes are checked.
    pub const fn response_body_limit(mut self, limit: usize) -> Self {
        self.response_body_limit = limit;
        self
    }

    /// Sends subscription-device headers used by 3x-ui's optional HWID gate.
    pub fn device(mut self, device: SubscriptionDevice) -> Self {
        self.device = Some(device);
        self
    }

    /// Removes previously configured subscription-device metadata.
    pub fn no_device(mut self) -> Self {
        self.device = None;
        self
    }

    /// Builds the standalone client.
    ///
    /// # Errors
    ///
    /// Returns an error when a configured path or HTTP-client option is
    /// invalid.
    pub fn build(self) -> Result<SubscriptionClient> {
        let raw_prefix = prefix_from_path(&self.base_url, &self.raw_path, "raw")?;
        let json_prefix = prefix_from_path(&self.base_url, &self.json_path, "JSON")?;
        let clash_prefix = prefix_from_path(&self.base_url, &self.clash_path, "Clash")?;
        SubscriptionClient::from_parts(
            &self.base_url,
            [&self.raw_path, &self.json_path, &self.clash_path],
            raw_prefix,
            json_prefix,
            clash_prefix,
            SubscriptionTransportConfig {
                timeout: self.timeout,
                connect_timeout: self.connect_timeout,
                accept_invalid_certs: self.accept_invalid_certs,
                proxy: self.proxy.as_ref(),
                response_body_limit: self.response_body_limit,
                device: self.device.as_ref(),
            },
        )
    }
}

impl std::fmt::Debug for SubscriptionClientBuilder {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("SubscriptionClientBuilder")
            .field("server_origin", &origin(&self.base_url))
            .field("raw_path", &"[REDACTED]")
            .field("json_path", &"[REDACTED]")
            .field("clash_path", &"[REDACTED]")
            .field("timeout", &self.timeout)
            .field("connect_timeout", &self.connect_timeout)
            .field("accept_invalid_certs", &self.accept_invalid_certs)
            .field("proxy", &self.proxy.as_ref().map(ProxyConfig::scheme))
            .field("response_body_limit", &self.response_body_limit)
            .field("device", &self.device)
            .finish()
    }
}

/// Public client for the separate 3x-ui subscription HTTP/HTTPS server.
///
/// This client intentionally has no panel authentication or cookie state. The
/// subscription identifier embedded into every request path is redacted from
/// SDK errors.
#[derive(Clone)]
pub struct SubscriptionClient {
    http: reqwest::Client,
    raw_prefix: Url,
    json_prefix: Url,
    clash_prefix: Url,
    response_body_limit: usize,
    mihomo_prefix: Option<Url>,
    legacy_prefix: Option<Url>,
}

impl SubscriptionClient {
    /// Creates a client using the default `/sub/`, `/json/`, and `/clash/`
    /// paths below `server_url`.
    ///
    /// # Errors
    ///
    /// Returns an error when the URL or HTTP-client configuration is invalid.
    pub fn new(server_url: impl AsRef<str>) -> Result<Self> {
        Self::builder(server_url)?.build()
    }

    /// Starts configuring a standalone subscription client.
    ///
    /// # Errors
    ///
    /// Returns an error when `server_url` is not an absolute HTTP(S) URL.
    pub fn builder(server_url: impl AsRef<str>) -> Result<SubscriptionClientBuilder> {
        SubscriptionClientBuilder::new(server_url)
    }

    /// Creates a client from the absolute public URIs and fallback paths in a
    /// panel settings snapshot.
    ///
    /// # Errors
    ///
    /// Returns an error when `subURI` is not an absolute HTTP(S) prefix or any
    /// configured URI/HTTP option is invalid.
    pub fn from_settings(settings: &SubscriptionSettings) -> Result<Self> {
        let raw_prefix = normalize_prefix_uri(&settings.sub_uri, "subURI")?;
        let server_url = origin_url(&raw_prefix);
        let json_prefix = if settings.sub_json_uri.trim().is_empty() {
            prefix_from_path(&server_url, &settings.sub_json_path, "JSON")?
        } else {
            normalize_prefix_uri(&settings.sub_json_uri, "subJsonURI")?
        };
        let clash_prefix = if settings.sub_clash_uri.trim().is_empty() {
            prefix_from_path(&server_url, &settings.sub_clash_path, "Clash")?
        } else {
            normalize_prefix_uri(&settings.sub_clash_uri, "subClashURI")?
        };
        Self::from_parts(
            &origin_url(&clash_prefix),
            [
                &settings.sub_path,
                &settings.sub_json_path,
                &settings.sub_clash_path,
            ],
            raw_prefix,
            json_prefix,
            clash_prefix,
            SubscriptionTransportConfig::default(),
        )
    }

    /// Builds an unauthenticated subscription transport from validated format prefixes.
    /// Resolves fixed aliases below `alias_base` and marks conflicting aliases unavailable,
    /// while allowing the configured Clash handler to serve Mihomo.
    ///
    /// # Errors
    ///
    /// Returns a configuration error for invalid device headers, alias URLs, or HTTP options.
    fn from_parts(
        alias_base: &Url,
        configured_paths: [&str; 3],
        raw_prefix: Url,
        json_prefix: Url,
        clash_prefix: Url,
        transport: SubscriptionTransportConfig<'_>,
    ) -> Result<Self> {
        let mut default_headers = header::HeaderMap::new();
        let user_agent = if let Some(device) = transport.device {
            if device.hwid().len() < 6 {
                return Err(Error::Configuration(
                    "subscription device HWID must contain at least 6 bytes".to_owned(),
                ));
            }
            insert_device_header(&mut default_headers, "x-hwid", device.hwid(), "HWID")?;
            insert_device_header(
                &mut default_headers,
                "x-device-os",
                &device.device_os,
                "device OS",
            )?;
            insert_device_header(
                &mut default_headers,
                "x-ver-os",
                &device.os_version,
                "OS version",
            )?;
            insert_device_header(
                &mut default_headers,
                "x-device-model",
                &device.device_model,
                "device model",
            )?;
            if device.user_agent.is_empty() {
                DEFAULT_USER_AGENT
            } else {
                device.user_agent.as_str()
            }
        } else {
            DEFAULT_USER_AGENT
        };
        let mut http_builder = reqwest::Client::builder()
            .no_proxy()
            .default_headers(default_headers)
            .timeout(transport.timeout)
            .connect_timeout(transport.connect_timeout)
            .user_agent(user_agent)
            .danger_accept_invalid_certs(transport.accept_invalid_certs);
        if let Some(proxy) = transport.proxy {
            http_builder = http_builder.proxy(proxy.reqwest_proxy()?);
        }
        let http = http_builder
            .build()
            .map_err(|error| Error::Configuration(error.to_string()))?;
        let prefixes = [&raw_prefix, &json_prefix, &clash_prefix];
        let alias_prefix = |path: &str, label: &str, owner_count: usize| -> Result<Option<Url>> {
            let candidate = prefix_from_path(alias_base, path, label)?;
            let shadowed = prefixes[..owner_count].iter().any(|prefix| {
                prefix.path().trim_matches('/') == candidate.path().trim_matches('/')
            }) || configured_paths[..owner_count]
                .iter()
                .any(|configured| configured.trim().trim_matches('/') == path.trim_matches('/'));
            Ok((!shadowed).then_some(candidate))
        };
        // The configured Clash handler already serves Mihomo, but it cannot
        // substitute for the distinct legacy renderer.
        let mihomo_prefix = alias_prefix("mihomo/", "Mihomo", 2)?;
        let legacy_prefix = alias_prefix("clash-legacy/", "legacy Clash", 3)?;
        Ok(Self {
            http,
            mihomo_prefix,
            legacy_prefix,
            raw_prefix,
            json_prefix,
            clash_prefix,
            response_body_limit: transport.response_body_limit,
        })
    }

    /// Returns the configured maximum subscription response body size.
    pub const fn response_body_limit(&self) -> usize {
        self.response_body_limit
    }

    /// Fetches the raw subscription body.
    ///
    /// The body is base64 when the panel's `subEncrypt` setting is enabled.
    ///
    /// # Errors
    ///
    /// Returns an error for transport or unsuccessful HTTP status.
    pub async fn raw(
        &self,
        subscription_id: &str,
    ) -> Result<SubscriptionResponse<SubscriptionDocument>> {
        self.text(
            Method::GET,
            Format::Raw,
            subscription_id,
            None,
            "text/plain",
        )
        .await
    }

    /// Fetches the browser HTML information page.
    ///
    /// # Errors
    ///
    /// Returns an error for transport, unsuccessful HTTP status, or invalid
    /// UTF-8.
    pub async fn html(
        &self,
        subscription_id: &str,
    ) -> Result<SubscriptionResponse<SubscriptionDocument>> {
        self.text(Method::GET, Format::Raw, subscription_id, None, "text/html")
            .await
    }

    /// Fetches the typed `format=info` status view without imported link data.
    ///
    /// # Errors
    ///
    /// Returns an error for transport, unsuccessful HTTP status, or invalid
    /// JSON.
    pub async fn info(&self, subscription_id: &str) -> Result<SubscriptionInfo> {
        Ok(self.info_with_metadata(subscription_id).await?.content)
    }

    /// Fetches the typed information view together with common and HWID headers.
    ///
    /// Prefer this method when device-limit state is relevant to the caller.
    ///
    /// # Errors
    ///
    /// Returns an error for transport, unsuccessful HTTP status, or invalid JSON.
    pub async fn info_with_metadata(
        &self,
        subscription_id: &str,
    ) -> Result<SubscriptionResponse<SubscriptionInfo>> {
        let (headers, bytes, method, redacted_url) = self
            .send(
                Method::GET,
                Format::Raw,
                subscription_id,
                Some(("format", "info")),
                "application/json",
            )
            .await?;
        let content = serde_json::from_slice(&bytes).map_err(|source| Error::Decode {
            method,
            url: Box::new(redacted_url),
            source,
        })?;
        Ok(SubscriptionResponse {
            content,
            metadata: SubscriptionMetadata::from_headers(&headers),
        })
    }

    /// Fetches and parses the Xray JSON subscription document.
    ///
    /// The raw-download view is requested to avoid browser content negotiation.
    ///
    /// # Errors
    ///
    /// Returns an error for transport, unsuccessful HTTP status, or invalid
    /// JSON.
    pub async fn json(
        &self,
        subscription_id: &str,
    ) -> Result<SubscriptionResponse<SubscriptionJson>> {
        let (headers, bytes, method, redacted_url) = self
            .send(
                Method::GET,
                Format::Json,
                subscription_id,
                Some(("view", "raw")),
                "application/json",
            )
            .await?;
        let value: Value = serde_json::from_slice(&bytes).map_err(|source| Error::Decode {
            method,
            url: Box::new(redacted_url),
            source,
        })?;
        Ok(SubscriptionResponse {
            content: SubscriptionJson::new(value),
            metadata: SubscriptionMetadata::from_headers(&headers),
        })
    }

    /// Fetches the Clash/Mihomo YAML subscription document.
    ///
    /// The raw-download view is requested to avoid browser content negotiation.
    ///
    /// # Errors
    ///
    /// Returns an error for transport, unsuccessful HTTP status, or invalid
    /// UTF-8.
    pub async fn clash(
        &self,
        subscription_id: &str,
    ) -> Result<SubscriptionResponse<SubscriptionDocument>> {
        self.text(
            Method::GET,
            Format::Clash,
            subscription_id,
            Some(("view", "raw")),
            "application/yaml",
        )
        .await
    }

    /// Fetches the Mihomo alias (`/mihomo/`), when enabled and not shadowed by a configured path.
    ///
    /// # Errors
    ///
    /// Returns a configuration error when the alias is shadowed, or an error
    /// for transport, unsuccessful HTTP status, or invalid UTF-8.
    pub async fn mihomo(
        &self,
        subscription_id: &str,
    ) -> Result<SubscriptionResponse<SubscriptionDocument>> {
        self.text(
            Method::GET,
            Format::Mihomo,
            subscription_id,
            Some(("view", "raw")),
            "application/yaml",
        )
        .await
    }

    /// Retrieves response headers from the mihomo alias.
    ///
    /// # Errors
    ///
    /// Returns a configuration error when the alias is shadowed, or an error
    /// for transport or unsuccessful HTTP status.
    pub async fn mihomo_metadata(&self, subscription_id: &str) -> Result<SubscriptionMetadata> {
        self.head(Format::Mihomo, subscription_id).await
    }

    /// Fetches the legacy Clash alias (`/clash-legacy/`), when enabled and not shadowed by a configured path.
    ///
    /// # Errors
    ///
    /// Returns a configuration error when the alias is shadowed, or an error
    /// for transport, unsuccessful HTTP status, or invalid UTF-8.
    pub async fn clash_legacy(
        &self,
        subscription_id: &str,
    ) -> Result<SubscriptionResponse<SubscriptionDocument>> {
        self.text(
            Method::GET,
            Format::Legacy,
            subscription_id,
            Some(("view", "raw")),
            "application/yaml",
        )
        .await
    }

    /// Retrieves response headers from the `clash_legacy` alias.
    ///
    /// # Errors
    ///
    /// Returns a configuration error when the alias is shadowed, or an error
    /// for transport or unsuccessful HTTP status.
    pub async fn clash_legacy_metadata(
        &self,
        subscription_id: &str,
    ) -> Result<SubscriptionMetadata> {
        self.head(Format::Legacy, subscription_id).await
    }

    /// Reads device-slot counts without registering or touching a device.
    ///
    /// # Errors
    ///
    /// Returns an error for transport, unsuccessful HTTP status, or malformed JSON.
    pub async fn hwid_status(&self, subscription_id: &str) -> Result<super::HwidSlotStatus> {
        let (_, bytes, method, url) = self
            .send(
                Method::GET,
                Format::HwidStatus,
                subscription_id,
                None,
                "application/json",
            )
            .await?;
        serde_json::from_slice(&bytes).map_err(|source| Error::Decode {
            method,
            url: Box::new(url),
            source,
        })
    }

    /// Checks the read-only HWID status route with HEAD.
    ///
    /// # Errors
    ///
    /// Returns an error for transport or unsuccessful HTTP status.
    pub async fn hwid_status_metadata(
        &self,
        subscription_id: &str,
    ) -> Result<SubscriptionMetadata> {
        self.head(Format::HwidStatus, subscription_id).await
    }

    /// Executes `HEAD` against the raw subscription route.
    ///
    /// # Errors
    ///
    /// Returns an error for transport or unsuccessful HTTP status.
    pub async fn raw_metadata(&self, subscription_id: &str) -> Result<SubscriptionMetadata> {
        self.head(Format::Raw, subscription_id).await
    }

    /// Executes `HEAD` against the JSON subscription route.
    ///
    /// # Errors
    ///
    /// Returns an error for transport or unsuccessful HTTP status.
    pub async fn json_metadata(&self, subscription_id: &str) -> Result<SubscriptionMetadata> {
        self.head(Format::Json, subscription_id).await
    }

    /// Executes `HEAD` against the Clash subscription route.
    ///
    /// # Errors
    ///
    /// Returns an error for transport or unsuccessful HTTP status.
    pub async fn clash_metadata(&self, subscription_id: &str) -> Result<SubscriptionMetadata> {
        self.head(Format::Clash, subscription_id).await
    }

    async fn head(&self, format: Format, subscription_id: &str) -> Result<SubscriptionMetadata> {
        let (headers, _, _, _) = self
            .send(Method::HEAD, format, subscription_id, None, "*/*")
            .await?;
        Ok(SubscriptionMetadata::from_headers(&headers))
    }

    async fn text(
        &self,
        method: Method,
        format: Format,
        subscription_id: &str,
        query: Option<(&str, &str)>,
        accept: &str,
    ) -> Result<SubscriptionResponse<SubscriptionDocument>> {
        let (headers, bytes, method, redacted_url) = self
            .send(method, format, subscription_id, query, accept)
            .await?;
        let text = String::from_utf8(bytes).map_err(|source| Error::Utf8 {
            method,
            url: Box::new(redacted_url),
            source,
        })?;
        Ok(SubscriptionResponse {
            content: SubscriptionDocument::new(text),
            metadata: SubscriptionMetadata::from_headers(&headers),
        })
    }

    /// Requests one subscription format with a safely encoded identifier and bounded response body.
    /// Returns response headers, bytes, the method, and a URL with the identifier redacted.
    ///
    /// # Errors
    ///
    /// Rejects unavailable aliases and empty identifiers before HTTP; propagates transport,
    /// HTTP-status, and response-size errors without exposing the subscription identifier.
    async fn send(
        &self,
        method: Method,
        format: Format,
        subscription_id: &str,
        query: Option<(&str, &str)>,
        accept: &str,
    ) -> Result<(header::HeaderMap, Vec<u8>, Method, Url)> {
        let prefix = match format {
            Format::Raw | Format::HwidStatus => Some(&self.raw_prefix),
            Format::Mihomo => self.mihomo_prefix.as_ref(),
            Format::Legacy => self.legacy_prefix.as_ref(),
            Format::Json => Some(&self.json_prefix),
            Format::Clash => Some(&self.clash_prefix),
        }
        .ok_or_else(|| {
            Error::Configuration(
                "subscription alias is shadowed by a configured subscription path".into(),
            )
        })?;
        let (mut url, mut redacted_url) = endpoint(prefix, subscription_id)?;
        if matches!(format, Format::HwidStatus) {
            url.path_segments_mut()
                .expect("validated HTTP URL")
                .push("hwid-status");
            redacted_url
                .path_segments_mut()
                .expect("validated HTTP URL")
                .push("hwid-status");
        }
        if let Some((key, value)) = query {
            url.query_pairs_mut().append_pair(key, value);
            redacted_url.query_pairs_mut().append_pair(key, value);
        }
        let response = transport::send_request(
            self.http
                .request(method.clone(), url)
                .header(header::ACCEPT, accept),
            &method,
            &redacted_url,
            ErrorUrlPolicy::Redact,
        )
        .await?;
        let status = response.status();
        if !status.is_success() {
            return Err(Error::HttpStatus {
                method,
                url: Box::new(redacted_url),
                status,
            });
        }
        let headers = response.headers().clone();
        let bytes = transport::read_response_body(
            response,
            &method,
            &redacted_url,
            self.response_body_limit,
            ErrorUrlPolicy::Redact,
        )
        .await?;
        Ok((headers, bytes, method, redacted_url))
    }
}

#[derive(Clone, Copy)]
struct SubscriptionTransportConfig<'proxy> {
    timeout: Duration,
    connect_timeout: Duration,
    accept_invalid_certs: bool,
    proxy: Option<&'proxy ProxyConfig>,
    response_body_limit: usize,
    device: Option<&'proxy SubscriptionDevice>,
}

impl Default for SubscriptionTransportConfig<'_> {
    fn default() -> Self {
        Self {
            timeout: DEFAULT_TIMEOUT,
            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
            accept_invalid_certs: false,
            proxy: None,
            response_body_limit: DEFAULT_SUBSCRIPTION_RESPONSE_BODY_LIMIT,
            device: None,
        }
    }
}

fn insert_device_header(
    headers: &mut header::HeaderMap,
    name: &'static str,
    value: &str,
    label: &str,
) -> Result<()> {
    if value.is_empty() {
        return Ok(());
    }
    let value = header::HeaderValue::from_str(value)
        .map_err(|error| Error::Configuration(format!("invalid {label} header: {error}")))?;
    headers.insert(header::HeaderName::from_static(name), value);
    Ok(())
}

impl std::fmt::Debug for SubscriptionClient {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("SubscriptionClient")
            .field("server_origin", &origin(&self.raw_prefix))
            .field("paths", &"[REDACTED]")
            .field("response_body_limit", &self.response_body_limit)
            .finish_non_exhaustive()
    }
}

#[derive(Clone, Copy)]
enum Format {
    Raw,
    Json,
    Clash,
    Mihomo,
    Legacy,
    HwidStatus,
}

fn normalize_server_url(value: &str) -> Result<Url> {
    let mut url = parse_http_url(value, "subscription server URL")?;
    url.set_query(None);
    url.set_fragment(None);
    if !url.path().ends_with('/') {
        url.set_path(&format!("{}/", url.path()));
    }
    Ok(url)
}

fn normalize_prefix_uri(value: &str, field: &str) -> Result<Url> {
    if value.trim().is_empty() {
        return Err(Error::Configuration(format!("{field} must not be empty")));
    }
    let mut url = parse_http_url(value, field)?;
    if url.query().is_some() || url.fragment().is_some() {
        return Err(Error::Configuration(format!(
            "{field} must not contain a query or fragment"
        )));
    }
    if !url.path().ends_with('/') {
        url.set_path(&format!("{}/", url.path()));
    }
    Ok(url)
}

fn parse_http_url(value: &str, field: &str) -> Result<Url> {
    let url = Url::parse(value)
        .map_err(|error| Error::Configuration(format!("invalid {field}: {error}")))?;
    if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
        return Err(Error::Configuration(format!(
            "{field} must be an absolute HTTP(S) URL"
        )));
    }
    if !url.username().is_empty() || url.password().is_some() {
        return Err(Error::Configuration(format!(
            "{field} must not contain credentials"
        )));
    }
    Ok(url)
}

fn prefix_from_path(base_url: &Url, path: &str, label: &str) -> Result<Url> {
    let path = path.trim();
    if path.is_empty() {
        return Err(Error::Configuration(format!(
            "{label} subscription path must not be empty"
        )));
    }
    if path.contains('?') || path.contains('#') {
        return Err(Error::Configuration(format!(
            "{label} subscription path must not contain a query or fragment"
        )));
    }
    let mut url = base_url
        .join(path.trim_start_matches('/'))
        .map_err(|error| Error::Configuration(format!("invalid {label} path: {error}")))?;
    if !url.path().ends_with('/') {
        url.set_path(&format!("{}/", url.path()));
    }
    Ok(url)
}

fn endpoint(prefix: &Url, subscription_id: &str) -> Result<(Url, Url)> {
    if subscription_id.is_empty() {
        return Err(Error::Configuration(
            "subscription ID must not be empty".to_owned(),
        ));
    }
    let mut url = prefix.clone();
    url.path_segments_mut()
        .map_err(|()| Error::Configuration("subscription URL cannot be a base".to_owned()))?
        .pop_if_empty()
        .push(subscription_id);
    let mut redacted = prefix.clone();
    redacted
        .path_segments_mut()
        .map_err(|()| Error::Configuration("subscription URL cannot be a base".to_owned()))?
        .pop_if_empty()
        .push("[REDACTED]");
    Ok((url, redacted))
}

fn origin_url(url: &Url) -> Url {
    let mut origin = url.clone();
    origin.set_path("/");
    origin.set_query(None);
    origin.set_fragment(None);
    origin
}

fn origin(url: &Url) -> String {
    let mut value = origin_url(url);
    value.set_path("");
    value.to_string().trim_end_matches('/').to_owned()
}

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

    fn configuration_message(error: Error) -> String {
        match error {
            Error::Configuration(message) => message,
            other => panic!("expected configuration error, got {other:?}"),
        }
    }

    #[test]
    fn builder_options_are_composable_and_debug_safe() {
        let proxy = ProxyConfig::new("http://proxy.example:8080").unwrap();
        let device = SubscriptionDevice::new("device-secret", "test-agent");
        let builder = SubscriptionClient::builder("https://sub.example/root?ignored=yes#fragment")
            .unwrap()
            .raw_path("private/raw")
            .json_path("private/json")
            .clash_path("private/clash")
            .timeout(Duration::from_secs(11))
            .connect_timeout(Duration::from_secs(3))
            .danger_accept_invalid_certs(true)
            .response_body_limit(1234)
            .proxy(proxy)
            .no_proxy()
            .device(device)
            .no_device();

        assert_eq!(builder.timeout, Duration::from_secs(11));
        assert_eq!(builder.connect_timeout, Duration::from_secs(3));
        assert!(builder.accept_invalid_certs);
        assert_eq!(builder.response_body_limit, 1234);
        assert!(builder.proxy.is_none());
        assert!(builder.device.is_none());
        assert!(builder.base_url.query().is_none());
        assert!(builder.base_url.fragment().is_none());
        assert_eq!(builder.base_url.path(), "/root/");

        let debug = format!("{builder:?}");
        assert!(debug.contains("https://sub.example"));
        assert!(debug.contains("[REDACTED]"));
        assert!(!debug.contains("private/raw"));

        let client = builder.build().unwrap();
        assert_eq!(client.response_body_limit(), 1234);
        assert!(!format!("{client:?}").contains("private/raw"));
    }

    #[test]
    fn proxy_url_and_device_headers_validate_early() {
        let builder = SubscriptionClient::builder("https://sub.example")
            .unwrap()
            .proxy_url("socks5h://proxy.example:1080")
            .unwrap();
        assert_eq!(
            builder.proxy.as_ref().unwrap().scheme(),
            crate::ProxyScheme::Socks5h
        );
        assert!(builder.no_proxy().proxy.is_none());

        let error = SubscriptionClient::builder("https://sub.example")
            .unwrap()
            .proxy_url("not a proxy")
            .unwrap_err();
        assert!(configuration_message(error).contains("invalid proxy URL"));

        let short = SubscriptionDevice::new("short", "agent");
        let error = SubscriptionClient::builder("https://sub.example")
            .unwrap()
            .device(short)
            .build()
            .unwrap_err();
        assert!(configuration_message(error).contains("at least 6 bytes"));

        let invalid = SubscriptionDevice::new("bad\nsecret", "agent");
        let error = SubscriptionClient::builder("https://sub.example")
            .unwrap()
            .device(invalid)
            .build()
            .unwrap_err();
        assert!(configuration_message(error).contains("invalid HWID header"));

        let empty_optional_headers = SubscriptionDevice::new("device-secret", "");
        SubscriptionClient::builder("https://sub.example")
            .unwrap()
            .device(empty_optional_headers)
            .build()
            .unwrap();
    }

    #[test]
    fn subscription_urls_reject_ambiguous_or_credentialed_inputs() {
        for input in [
            "relative/path",
            "ftp://sub.example",
            "https://user:pass@sub.example",
        ] {
            assert!(SubscriptionClient::builder(input).is_err(), "{input}");
        }

        for raw_path in ["", "sub?format=raw", "sub#fragment"] {
            let error = SubscriptionClient::builder("https://sub.example")
                .unwrap()
                .raw_path(raw_path)
                .build()
                .unwrap_err();
            assert!(configuration_message(error).contains("raw subscription path"));
        }

        for value in [
            "",
            "https://sub.example/path?query=yes",
            "https://sub.example/path#fragment",
        ] {
            let error = normalize_prefix_uri(value, "testURI").unwrap_err();
            assert!(configuration_message(error).contains("testURI"));
        }

        let normalized = normalize_prefix_uri("https://sub.example/path", "testURI").unwrap();
        assert_eq!(normalized.as_str(), "https://sub.example/path/");
        assert_eq!(origin(&normalized), "https://sub.example");
    }

    #[test]
    fn settings_require_valid_public_prefixes_and_fallback_paths() {
        let empty = SubscriptionSettings::default();
        assert!(SubscriptionClient::from_settings(&empty).is_err());

        let invalid_json_path = SubscriptionSettings {
            sub_uri: "https://sub.example/raw/".into(),
            sub_json_path: "json?view=raw".into(),
            sub_clash_path: "clash".into(),
            ..SubscriptionSettings::default()
        };
        let error = SubscriptionClient::from_settings(&invalid_json_path).unwrap_err();
        assert!(configuration_message(error).contains("JSON subscription path"));

        let invalid_clash_uri = SubscriptionSettings {
            sub_uri: "https://sub.example/raw/".into(),
            sub_json_uri: "https://sub.example/json/".into(),
            sub_clash_uri: "https://user:pass@sub.example/clash/".into(),
            ..SubscriptionSettings::default()
        };
        let error = SubscriptionClient::from_settings(&invalid_clash_uri).unwrap_err();
        assert!(configuration_message(error).contains("subClashURI"));
    }
}