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
use std::borrow::Cow;
use std::fmt::Debug;
use std::time::Duration;

use super::http_targets::HomeserverFeatures;
use crate::{cross_log, errors::BuildError};

pub(crate) const DEFAULT_MAX_ERROR_BODY_BYTES: usize = 4096;

const DEFAULT_USER_AGENT: &str = concat!("pubky.org", "@", env!("CARGO_PKG_VERSION"),);

#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone, Default)]
struct NativeHttpConfig {
    request_timeout: Option<Duration>,
    read_timeout: Option<Duration>,
    pool_max_idle_per_host: Option<usize>,
    extra_trust_anchors: Vec<rustls::pki_types::TrustAnchor<'static>>,
}

#[derive(Debug, Clone)]
#[must_use]
/// Configures a [`PubkyHttpClient`] before construction.
///
/// Customize timeouts, user-agent, pkarr relays, native ICANN HTTPS roots,
/// and (WASM) testnet behavior.
/// Most code obtains this via [`PubkyHttpClient::builder()`], which simply returns
/// `PubkyHttpClientBuilder::default()`.
///
/// # Defaults
/// - Pkarr relays: [`crate::pkarr::DEFAULT_RELAYS`]
/// - HTTP total request timeout (native only): reqwest default (disabled) unless set via
///   [`Self::request_timeout`]
/// - HTTP read timeout (native only): reqwest default (disabled) unless set via
///   [`Self::read_timeout`]
/// - Error-body capture: 4096 bytes; see [`Self::max_error_body_bytes`].
/// - User-agent: `pubky.org@<crate-version>` plus any [`Self::user_agent_extra`]
/// - Idle keep-alive connections per host (native only): reqwest default unless set via
///   [`Self::pool_max_idle_per_host`]
/// - ICANN HTTPS trust (native only): Mozilla roots, plus any roots supplied with
///   `add_root_certificates_pem`.
/// # Example
/// ```no_run
/// # #[cfg(not(target_arch = "wasm32"))]
/// # fn example() -> Result<(), pubky::BuildError> {
/// use std::time::Duration;
/// # use pubky::{PubkyHttpClient, PubkyHttpClientBuilder};
/// let client = PubkyHttpClient::builder()
///     .request_timeout(Duration::from_secs(10))
///     .read_timeout(Duration::from_secs(5))
///     .user_agent_extra("myapp/1.2.3")
///     .pool_max_idle_per_host(10)
///     .build()?;
/// # Ok(()) }
/// ```
///
/// You can keep the default Pkarr relays or override them via the builder:
/// ```no_run
/// # use pubky::{PubkyHttpClient, PubkyHttpClientBuilder};
/// # fn main() -> Result<(), pubky::BuildError> {
/// // Start from defaults; you can also supply your own entirely.
/// let mut b = PubkyHttpClient::builder();
/// b.pkarr(|p| p.relays(&["https://pkarr.example.net/"]).expect("infallible"));
/// let _client = b.build()?;
/// # Ok(()) }
/// ```
#[derive(Default)]
pub struct PubkyHttpClientBuilder {
    pkarr: pkarr::ClientBuilder,

    /// Optional user-agent segment appended to the default UA for app-level telemetry.
    user_agent_extra: Option<String>,
    max_error_body_bytes: Option<usize>,

    #[cfg(not(target_arch = "wasm32"))]
    native_http: NativeHttpConfig,

    /// The hostname to use for testnet URL transformations (WASM only).
    #[cfg(target_arch = "wasm32")]
    testnet_host: Option<String>,
}

impl PubkyHttpClientBuilder {
    #[cfg(test)]
    pub(crate) fn isolated_pkarr_test(&mut self) -> &mut Self {
        self.pkarr
            .no_default_network()
            .bootstrap(&["127.0.0.1:1"])
            .dht_report_policy(pkarr::dht::ReportPolicy::testnet());
        self
    }

    /// Configure this builder to talk to a **local Pubky testnet** on `localhost`.
    ///
    /// Concretely:
    /// - **DHT bootstrap** to the local testnet node at: `"localhost:6881"`
    /// - **PKARR relay** base URL: `"http://localhost:15411"`
    /// - **WASM builds** additionally remember the hostname when resolving `_pubky.<pk>` targets.
    ///
    /// # Examples
    /// ```
    /// use pubky::PubkyHttpClient;
    ///
    /// let client = PubkyHttpClient::builder()
    ///     .testnet()
    ///     .build()
    ///     .expect("testnet client");
    /// ```
    pub fn testnet(&mut self) -> &mut Self {
        self.testnet_with_host("localhost")
    }

    /// Configure this builder to talk to a **Pubky testnet** reachable at a custom host.
    ///
    /// Use this when your testnet stack isn’t on `localhost` (e.g. running in Docker,
    /// a remote VM, or LAN machine).
    ///
    /// Concretely:
    /// - DHT bootstrap peer: `"<host>:6881"` (native only)
    /// - PKARR relay base:   `"http://<host>:15411"`
    /// - WASM remembers `<host>` to adjust URL rewriting for the browser environment.
    ///
    /// # Examples
    /// ```
    /// use pubky::PubkyHttpClient;
    ///
    /// let client = PubkyHttpClient::builder()
    ///     .testnet_with_host("192.168.1.50") // or "host.docker.internal"
    ///     .build()
    ///     .expect("testnet client");
    /// ```
    ///
    /// # Notes
    /// - These ports come from `pubky_common::constants::testnet_ports::{ BOOTSTRAP, PKARR_RELAY }`.
    /// - Ensure your testnet exposes them from that host (and they’re reachable from where this code runs).
    ///
    /// # Panics
    /// If the testnet cannot because the given host leads to an invalid relay URL.
    #[cfg_attr(
        target_arch = "wasm32",
        allow(
            clippy::semicolon_outside_block,
            clippy::unnecessary_operation,
            clippy::semicolon_if_nothing_returned,
            reason = "WASM-only block preserves conditional assignment formatting"
        )
    )]
    pub fn testnet_with_host(&mut self, host: &str) -> &mut Self {
        cross_log!(info, "Configuring testnet builders for host {host}");
        #[cfg(not(target_arch = "wasm32"))]
        self.pkarr
            .bootstrap(&[format!(
                "{}:{}",
                host,
                pubky_common::constants::testnet_ports::BOOTSTRAP
            )])
            .dht_report_policy(pkarr::dht::ReportPolicy::testnet());

        self.pkarr
            .relays(&[format!(
                "http://{}:{}",
                host,
                pubky_common::constants::testnet_ports::PKARR_RELAY
            )])
            .expect("relays urls infallible");

        #[cfg(target_arch = "wasm32")]
        {
            self.testnet_host = Some(host.to_string());
        }

        self
    }

    /// Allows mutating the internal [`pkarr::ClientBuilder`] with a callback function.
    ///
    /// Use this to influence PKARR resolution inputs (relays, bootstrap nodes,
    /// timeouts, etc.) *before* building the client. There are no per-request
    /// resolution knobs; configuration is done up front.
    ///
    /// # Example
    /// ```
    /// # use pubky::{PubkyHttpClient, PubkyHttpClientBuilder};
    /// let client = PubkyHttpClient::builder()
    ///     .pkarr(|p| p
    ///         .relays(&["https://pkarr.example.net/"]).expect("infallible")
    ///         .bootstrap(&["dht.node.example:6881"])
    ///     )
    ///     .build()?;
    /// # Ok::<_, pubky::BuildError>(())
    /// ```
    pub fn pkarr<F>(&mut self, f: F) -> &mut Self
    where
        F: FnOnce(&mut pkarr::ClientBuilder) -> &mut pkarr::ClientBuilder,
    {
        f(&mut self.pkarr);

        self
    }

    /// Append an extra user-agent segment after the default `pubky.org@<version>`.
    /// Enables app-level telemetry
    /// Example: `.user_agent_extra("myapp/1.2.3")`
    pub fn user_agent_extra<S: Into<String>>(&mut self, extra: S) -> &mut Self {
        self.user_agent_extra = Some(extra.into());
        self
    }

    /// Limit the raw response bytes captured for HTTP error diagnostics. Defaults to 4096.
    ///
    /// Set `0` to skip error-body reads and use the status reason as the message.
    /// Longer bodies receive a truncation marker. This applies to all checked SDK
    /// requests, including credential refresh. Successful-body handling is unchanged.
    ///
    /// Lossy UTF-8 decoding can produce up to three times the captured byte count,
    /// plus the truncation marker. This limit does not cap the final message size
    /// or total memory use; transport buffers and allocations add overhead.
    /// A stalled body at or below a positive limit still needs a request timeout.
    ///
    /// # Example
    /// ```
    /// # use pubky::PubkyHttpClient;
    /// let client = PubkyHttpClient::builder()
    ///     .max_error_body_bytes(1024)
    ///     .build()?;
    /// # Ok::<_, pubky::BuildError>(())
    /// ```
    pub fn max_error_body_bytes(&mut self, limit: usize) -> &mut Self {
        self.max_error_body_bytes = Some(limit);
        self
    }

    /// Build a [`PubkyHttpClient`].
    ///
    /// # Errors
    /// - [`crate::errors::BuildError::Pkarr`] if building the PKARR client fails.
    /// - [`crate::errors::BuildError::Http`] if constructing the HTTP client fails.
    ///
    /// # Examples
    /// ```
    /// # use pubky::PubkyHttpClient;
    /// let client = PubkyHttpClient::builder().build()?;
    /// # Ok::<_, pubky::BuildError>(())
    /// ```
    pub fn build(&self) -> Result<PubkyHttpClient, BuildError> {
        let pkarr = self.pkarr.build()?;

        // Compose user agent with optional extra part.
        let user_agent = self
            .user_agent_extra
            .as_deref()
            .map(str::trim)
            .filter(|extra| !extra.is_empty())
            .map_or_else(
                || Cow::Borrowed(DEFAULT_USER_AGENT),
                |extra| Cow::Owned(format!("{DEFAULT_USER_AGENT} {extra}")),
            );

        #[cfg(not(target_arch = "wasm32"))]
        cross_log!(
            info,
            "Building PubkyHttpClient (request_timeout: {:?}, read_timeout: {:?}, user_agent: {}, pool_max_idle_per_host: {:?})",
            self.native_http.request_timeout,
            self.native_http.read_timeout,
            user_agent,
            self.native_http.pool_max_idle_per_host
        );
        #[cfg(target_arch = "wasm32")]
        cross_log!(
            info,
            "Building PubkyHttpClient (user_agent: {})",
            user_agent
        );

        #[cfg(not(target_arch = "wasm32"))]
        let mut http_builder =
            reqwest::ClientBuilder::from(pkarr.clone()).user_agent(user_agent.as_ref());

        #[cfg(target_arch = "wasm32")]
        let http_builder = reqwest::Client::builder().user_agent(user_agent.as_ref());

        #[cfg(not(target_arch = "wasm32"))]
        let mut icann_http_builder = reqwest::Client::builder()
            .user_agent(user_agent.as_ref())
            .tls_backend_preconfigured(icann_tls_config_without_revocation_check(
                &self.native_http.extra_trust_anchors,
            ));

        // TODO: change this after Reqwest publish a release with timeout in wasm
        #[cfg(not(target_arch = "wasm32"))]
        if let Some(timeout) = self.native_http.request_timeout {
            http_builder = http_builder.timeout(timeout);
            icann_http_builder = icann_http_builder.timeout(timeout);
        }

        #[cfg(not(target_arch = "wasm32"))]
        if let Some(timeout) = self.native_http.read_timeout {
            http_builder = http_builder.read_timeout(timeout);
            icann_http_builder = icann_http_builder.read_timeout(timeout);
        }

        #[cfg(not(target_arch = "wasm32"))]
        if let Some(max) = self.native_http.pool_max_idle_per_host {
            http_builder = http_builder.pool_max_idle_per_host(max);
            icann_http_builder = icann_http_builder.pool_max_idle_per_host(max);
        }

        #[cfg(not(target_arch = "wasm32"))]
        let features = HomeserverFeatures::new(self.native_http.request_timeout);
        #[cfg(target_arch = "wasm32")]
        let features = HomeserverFeatures::default();

        Ok(PubkyHttpClient {
            pkarr,
            http: http_builder.build()?,
            features,
            max_error_body_bytes: self
                .max_error_body_bytes
                .unwrap_or(DEFAULT_MAX_ERROR_BODY_BYTES),

            #[cfg(not(target_arch = "wasm32"))]
            icann_http: icann_http_builder.build()?,

            #[cfg(not(target_arch = "wasm32"))]
            transport: super::http_targets::native::TransportResolver::new(),

            #[cfg(target_arch = "wasm32")]
            testnet_host: self.testnet_host.clone(),
        })
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl PubkyHttpClientBuilder {
    /// Add trusted CA certificates from a PEM bundle for ICANN HTTPS requests.
    ///
    /// These augment the built-in Mozilla roots. They do not affect `PubkyTLS`
    /// connections or the separate pkarr relay client. This can be used with
    /// a bundle read from `SSL_CERT_FILE`.
    ///
    /// ```no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use pubky::PubkyHttpClient;
    /// let pem = std::fs::read(std::env::var("SSL_CERT_FILE")?)?;
    /// let mut builder = PubkyHttpClient::builder();
    /// builder.add_root_certificates_pem(&pem)?;
    /// let client = builder.build()?;
    /// # Ok(()) }
    /// ```
    ///
    /// # Errors
    /// Returns an error if the bundle has no certificates, contains malformed
    /// PEM, or contains a certificate that cannot be used as a trust anchor.
    pub fn add_root_certificates_pem(&mut self, pem: &[u8]) -> Result<&mut Self, BuildError> {
        use rustls::pki_types::pem::PemObject;

        let mut roots = rustls::RootCertStore::empty();
        for certificate in rustls::pki_types::CertificateDer::pem_slice_iter(pem) {
            roots.add(certificate?)?;
        }
        if roots.is_empty() {
            return Err(BuildError::EmptyRootCertificates);
        }

        self.native_http.extra_trust_anchors.extend(roots.roots);
        Ok(self)
    }

    /// Set a total deadline for each HTTP request.
    ///
    /// The deadline starts when the request begins connecting and lasts until
    /// the response body finishes.
    pub fn request_timeout(&mut self, timeout: Duration) -> &mut Self {
        self.native_http.request_timeout = Some(timeout);
        self
    }

    /// Set the maximum duration of each HTTP read operation.
    ///
    /// The duration resets after every successful read. This detects stalled
    /// response bodies without imposing a total deadline on an active stream.
    pub fn read_timeout(&mut self, timeout: Duration) -> &mut Self {
        self.native_http.read_timeout = Some(timeout);
        self
    }

    /// Cap idle keep-alive connections per host. Set `0` to disable pooling.
    pub fn pool_max_idle_per_host(&mut self, max: usize) -> &mut Self {
        self.native_http.pool_max_idle_per_host = Some(max);
        self
    }
}

#[cfg(target_arch = "wasm32")]
impl PubkyHttpClientBuilder {
    /// Set a total deadline for each HTTP request.
    ///
    /// # Deprecated
    /// This setter has never had any effect on WASM: reqwest uses the browser
    /// `fetch` backend and `build()` does not apply a global HTTP timeout.
    /// Use [`.pkarr()`](Self::pkarr) to configure Pkarr relay request timeouts instead.
    #[deprecated(
        note = "HTTP request timeout is not supported on WASM and has never had any effect; use `.pkarr(|p| p.relay_request_timeout(..))` for Pkarr relay timeouts"
    )]
    pub fn request_timeout(&mut self, _timeout: Duration) -> &mut Self {
        self
    }

    /// Set the maximum duration of each HTTP read operation.
    ///
    /// # Deprecated
    /// This setter has no effect on WASM: reqwest's browser `fetch` backend
    /// does not support configuring a timeout for each read operation.
    #[deprecated(note = "HTTP read timeout is not supported on WASM")]
    pub fn read_timeout(&mut self, _timeout: Duration) -> &mut Self {
        self
    }
}

/// TLS config for the ICANN HTTP client: Mozilla and caller-supplied roots,
/// with certificate revocation checking disabled.
///
/// Revocation is disabled because reqwest's default verifier (rustls-platform-verifier)
/// hard-fails revocation on Android, where Let's Encrypt's sharded-CRL hierarchy makes it
/// falsely reject valid certificates ("invalid peer certificate: Revoked"). Only the ICANN
/// client uses this; the homeserver raw-public-key client keeps its pkarr-derived TLS.
#[cfg(not(target_arch = "wasm32"))]
fn icann_tls_config_without_revocation_check(
    extra_roots: &[rustls::pki_types::TrustAnchor<'static>],
) -> rustls::ClientConfig {
    let mut root_store = rustls::RootCertStore::empty();
    root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
    root_store.extend(extra_roots.iter().cloned());
    let mut tls_config = rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(
        rustls::crypto::aws_lc_rs::default_provider(),
    ))
    .with_safe_default_protocol_versions()
    .expect("aws-lc-rs provides safe default protocol versions")
    .with_root_certificates(root_store)
    .with_no_client_auth();
    tls_config.alpn_protocols = vec![b"http/1.1".to_vec()];
    tls_config
}

/// Transport client for Pubky homeserver APIs and generic HTTP, with PKARR-aware
/// URL handling.
///
/// `PubkyHttpClient` is the low-level engine the higher-level actors
/// (`PubkySession`, `PubkyStorage`, `Pkdns`, `PubkyGrantAuthFlow`) are built on. It owns:
/// - A pkarr DHT client (for resolving pkdns endpoints and publishing records).
/// - One or more reqwest HTTP clients (platform-specific).
///
/// ### What it does
/// - Detects pkarr public-key hosts and resolves them to concrete endpoints.
/// - [`PubkyHttpClient::request_async`] resolves Pubky transport and storage compatibility
///   on native Rust and WASM.
///
/// ### What it *doesn’t* do
/// - It is **not** session/identity aware. No cookies, no per-user scoping.
///   For authenticated per-user flows use [`crate::PubkySession`].
///
/// ### When to use
/// - You want direct control over the `PubkyHttpClient` (power users, libs).
/// - You’re wiring custom flows/tests and don’t need the high-level ergonomics.
///
/// ### Construction
/// Use [`PubkyHttpClient::builder()`] to tweak timeouts, relays, or
/// user-agent; or pick sensible defaults via [`PubkyHttpClient::new()`]. A
/// [`PubkyHttpClient::testnet()`] helper configures a local test network.
///
/// ### Platform notes
/// - **Native (rust, not WASM target):**
///   - ICANN domains use standard X.509 TLS via the `icann_http` client.
///   - Pubky/PKDNS hosts (public-key hostnames or `_pubky.<pk>` domains) use **`PubkyTLS`**
///     (TLS with RFC 7250 Raw Public Keys), verifying the connection against the
///     target public key—no CA chain involved.
/// - **WASM:**
///   - All requests use the browser’s standard X.509 TLS stack.
///   - For Pubky/PKDNS hosts, [`PubkyHttpClient::request_async`] resolves the endpoint
///     via PKARR, rewrites the URL (including testnet/localhost mapping), and may add a
///     `pubky-host` header to convey the intended public-key host.
///
/// ### Examples
/// Basic construction. Works out of the box for mainline DHT pkarr endpoints.
/// ```
/// # use pubky::PubkyHttpClient;
/// # #[cfg(doctest)]
/// # return Ok::<_, pubky::BuildError>(());
/// let client = PubkyHttpClient::new()?;
/// # Ok::<_, pubky::BuildError>(())
/// ```
///
/// Fetching a standard ICANN URL or any URL with `request`:
/// ```no_run
/// # use pubky::{PubkyHttpClient, Result};
/// # use reqwest::Method;
/// # use url::Url;
/// # async fn run() -> Result<()> {
/// # #[cfg(doctest)]
/// # return Ok(());
/// let client = PubkyHttpClient::new()?;
/// let url = Url::parse("https://example.com")?;
/// let resp = client.request(Method::GET, &url)
///     .send().await?;
/// assert!(resp.status().is_success());
/// # Ok(()) }
/// ```
///
/// Note: `request(..)` is available only on native targets. `request_async(..)` is
/// available on native Rust and WASM. JavaScript callers use `client.fetch(..)` from
/// `bindings/js`.
///
/// Fetching a Pubky resource via its transport URL, including legacy homeserver support:
/// ```no_run
/// # use pubky::{PubkyHttpClient, Result};
/// # use reqwest::Method;
/// # use url::Url;
/// # async fn run() -> Result<()> {
/// # #[cfg(doctest)]
/// # return Ok(());
/// let client = PubkyHttpClient::new()?;
/// // Pubky App profile of user Pubky https://pubky.app/profile/ihaqcthsdbk751sxctk849bdr7yz7a934qen5gmpcbwcur49i97y
/// let user = "ihaqcthsdbk751sxctk849bdr7yz7a934qen5gmpcbwcur49i97y";
/// let url = Url::parse(&format!(
///     "https://_pubky.{user}/storage/{user}/pub/pubky.app/profile.json"
/// ))?;
/// let resp = client.request_async(Method::GET, url).await?.send().await?;
/// let info = resp.text().await?;
/// # Ok(()) }
/// ```
///
/// > Tip: For authenticated reads/writes, prefer `session.storage().get(...)`, which
/// > automatically scopes paths and attaches the right session credential.
#[derive(Clone, Debug)]
pub struct PubkyHttpClient {
    pub(crate) http: reqwest::Client,
    pub(crate) pkarr: pkarr::Client,
    pub(crate) features: HomeserverFeatures,
    pub(crate) max_error_body_bytes: usize,

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) icann_http: reqwest::Client,

    /// Resolves and caches per-host transport decisions (`PubkyTLS` vs ICANN fallback).
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) transport: super::http_targets::native::TransportResolver,

    /// The hostname to use for testnet URL transformations (WASM only).
    #[cfg(target_arch = "wasm32")]
    pub(crate) testnet_host: Option<String>,
}

/// Prepared browser-fetch metadata used by the JavaScript bindings.
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreparedFetch {
    /// The `pubky-host` header to attach, if any.
    #[doc(hidden)]
    pub pubky_host_header: Option<String>,

    /// Whether the original request targeted a Pubky authority.
    #[doc(hidden)]
    pub is_pubky_target: bool,
}

impl PubkyHttpClient {
    /// Creates a client configured for public mainline DHT and pkarr relays.
    ///
    /// # Errors
    /// - Returns [`BuildError`] if the underlying HTTP clients cannot be constructed or configured.
    pub fn new() -> Result<Self, BuildError> {
        cross_log!(
            info,
            "Constructing PubkyHttpClient with default configuration"
        );
        Self::builder().build()
    }

    /// Returns a builder to edit settings before creating [`PubkyHttpClient`].
    /// Prefer this when you need to control PKARR/DHT inputs (relays, bootstrap);
    /// resolution itself remains automatic during requests.
    pub fn builder() -> PubkyHttpClientBuilder {
        PubkyHttpClientBuilder::default()
    }

    /// Creates a [`PubkyHttpClient`] preconfigured to talk to a **locally running Pubky testnet**.
    ///
    /// # What this configures
    /// On **non wasm** targets (`not(target_arch = "wasm32")`):
    /// - **DHT bootstrap** to the local testnet node at: `"localhost:6881"`
    /// - **PKARR relay** base URL: `"http://localhost:15411"`
    ///
    /// On **WASM** targets:
    /// - Browser environments can’t dial UDP DHT; the builder is adjusted to use the
    ///   testnet HTTP endpoints suitable for the browser (no UDP bootstrap). PKARR HTTP
    ///   relay still points at `http://localhost:15411` unless you override it.
    ///
    /// # Requirements
    /// You must have `pubky-testnet` binary running locally (it provides a homeserver, a DHT bootstrap,
    /// and a PKARR relay on the ports above). For example:
    /// ```sh
    /// # From the pubky repo:
    /// cargo run -p pubky-testnet
    /// ```
    ///
    /// # Examples
    /// ```
    /// use pubky::PubkyHttpClient;
    ///
    /// let client = PubkyHttpClient::testnet()?;
    /// // Now all https://_pubky.<pubkey>/... requests resolve via the local testnet
    /// // DHT/PKARR, and hit the local homeserver.
    /// # Ok::<_, pubky::BuildError>(())
    /// ```
    ///
    /// # See also
    /// - [`PubkyHttpClientBuilder::testnet`] to tweak additional settings first.
    /// - [`PubkyHttpClientBuilder::testnet_with_host`] to target a non-`localhost` host.
    ///
    /// # Errors
    /// - Returns [`BuildError`] if the underlying HTTP clients cannot be constructed or configured for the testnet settings.
    pub fn testnet() -> Result<Self, BuildError> {
        cross_log!(
            info,
            "Constructing PubkyHttpClient configured for local testnet"
        );
        let mut builder = Self::builder();
        builder.testnet();
        builder.build()
    }

    // === Getters ===

    /// Returns a reference to the internal Pkarr Client.
    #[must_use]
    pub const fn pkarr(&self) -> &pkarr::Client {
        &self.pkarr
    }
}

#[cfg(test)]
mod test {
    use httpmock::MockServer;
    use reqwest::{Method, StatusCode};
    #[cfg(not(target_arch = "wasm32"))]
    use tokio::{
        io::{AsyncReadExt, AsyncWriteExt},
        net::TcpListener,
    };

    use super::*;

    #[cfg(not(target_arch = "wasm32"))]
    const TEST_CA: &[u8] = include_bytes!("test_certs/ca.pem");

    #[cfg(not(target_arch = "wasm32"))]
    async fn stalling_http_server() -> String {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();

        tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await.unwrap();
            // A single read may return only part of the request or hit EOF,
            // so accumulate until the header block is complete. The test only
            // sends a bodyless GET, so the terminator ends the request.
            let mut request = Vec::new();
            let mut buffer = [0; 1024];
            loop {
                let read = stream.read(&mut buffer).await.unwrap();
                if read == 0 {
                    break;
                }
                request.extend_from_slice(&buffer[..read]);
                if request.ends_with(b"\r\n\r\n") {
                    break;
                }
            }
            stream
                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 1\r\nConnection: close\r\n\r\n")
                .await
                .unwrap();
            tokio::time::sleep(Duration::from_secs(1)).await;
        });

        format!("http://{address}")
    }

    #[tokio::test]
    async fn test_fetch() {
        let server = MockServer::start();
        let mock = server.mock(|when, then| {
            when.method("GET").path("/health");
            then.status(200).body("ok");
        });

        let client = PubkyHttpClient::new().unwrap();
        let response = client
            .request(Method::GET, &server.url("/health"))
            .send()
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        mock.assert();
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn native_timeouts_are_opt_in() {
        let config = NativeHttpConfig::default();

        assert_eq!(config.request_timeout, None);
        assert_eq!(config.read_timeout, None);
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn native_timeout_setters_store_values() {
        let request_timeout = Duration::from_secs(30);
        let read_timeout = Duration::from_secs(10);
        let mut builder = PubkyHttpClient::builder();

        builder
            .request_timeout(request_timeout)
            .read_timeout(read_timeout);

        assert_eq!(builder.native_http.request_timeout, Some(request_timeout));
        assert_eq!(builder.native_http.read_timeout, Some(read_timeout));
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn invalid_root_certificate_bundle_does_not_change_builder() {
        let mut builder = PubkyHttpClient::builder();
        assert!(matches!(
            builder.add_root_certificates_pem(b"no certificates"),
            Err(BuildError::EmptyRootCertificates)
        ));
        assert!(builder.native_http.extra_trust_anchors.is_empty());
        assert!(matches!(
            builder.add_root_certificates_pem(
                b"-----BEGIN CERTIFICATE-----\ninvalid!\n-----END CERTIFICATE-----\n"
            ),
            Err(BuildError::RootCertificatePem(_))
        ));
        assert!(builder.native_http.extra_trust_anchors.is_empty());
        assert!(matches!(
            builder.add_root_certificates_pem(
                b"-----BEGIN CERTIFICATE-----\nAA==\n-----END CERTIFICATE-----\n"
            ),
            Err(BuildError::RootCertificate(_))
        ));
        assert!(builder.native_http.extra_trust_anchors.is_empty());
        builder.add_root_certificates_pem(TEST_CA).unwrap();
        assert_eq!(builder.native_http.extra_trust_anchors.len(), 1);
    }

    #[cfg(not(target_arch = "wasm32"))]
    async fn https_server_with_test_certificate() -> url::Url {
        use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject};
        use tokio_rustls::TlsAcceptor;

        let server_cert =
            CertificateDer::from_pem_slice(include_bytes!("test_certs/server.pem")).unwrap();
        let server_key =
            PrivateKeyDer::from_pem_slice(include_bytes!("test_certs/server.key")).unwrap();
        let server_config = rustls::ServerConfig::builder_with_provider(std::sync::Arc::new(
            rustls::crypto::aws_lc_rs::default_provider(),
        ))
        .with_safe_default_protocol_versions()
        .unwrap()
        .with_no_client_auth()
        .with_single_cert(vec![server_cert], server_key)
        .unwrap();
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();

        tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            let mut stream = TlsAcceptor::from(std::sync::Arc::new(server_config))
                .accept(stream)
                .await
                .unwrap();
            let mut request = Vec::new();
            let mut buffer = [0; 1024];
            while !request.windows(4).any(|window| window == b"\r\n\r\n") {
                let read = stream.read(&mut buffer).await.unwrap();
                assert!(read > 0, "request ended before its headers");
                request.extend_from_slice(&buffer[..read]);
            }
            stream
                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
                .await
                .unwrap();
        });

        url::Url::parse(&format!("https://localhost:{}/", address.port())).unwrap()
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[tokio::test]
    async fn extra_root_certificate_trusts_icann_https_server() {
        let url = https_server_with_test_certificate().await;
        let mut builder = PubkyHttpClient::builder();
        builder.add_root_certificates_pem(TEST_CA).unwrap();
        let client = builder.build().unwrap();
        let response = client
            .request_async(Method::GET, url)
            .await
            .unwrap()
            .send()
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.text().await.unwrap(), "ok");
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[tokio::test]
    async fn read_timeout_applies_to_all_native_http_clients() {
        let client = PubkyHttpClient::builder()
            .read_timeout(Duration::from_millis(50))
            .build()
            .unwrap();

        for http in [&client.http, &client.icann_http] {
            let response = http.get(stalling_http_server().await).send().await.unwrap();
            let error = tokio::time::timeout(Duration::from_secs(1), response.bytes())
                .await
                .expect("read should finish with reqwest's timeout")
                .expect_err("stalled response body should time out");

            assert!(error.is_timeout());
        }
    }
}