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

use crate::{cross_log, errors::BuildError};

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

#[derive(Debug, Clone)]
#[must_use]
/// Configures a [`PubkyHttpClient`] before construction.
///
/// Customize timeouts, user-agent, pkarr relays, and (WASM) testnet behavior.
/// Most code obtains this via [`PubkyHttpClient::builder()`], which simply returns
/// `PubkyHttpClientBuilder::default()`.
///
/// # Defaults
/// - Pkarr relays: [`crate::pkarr::DEFAULT_RELAYS`]
/// - HTTP request timeout: reqwest default (no global timeout) unless set via
///   [`Self::request_timeout`]
/// - User-agent: `pubky.org@<crate-version>` plus any [`Self::user_agent_extra`]
///
/// # Example
/// ```no_run
/// use std::time::Duration;
/// # use pubky::{PubkyHttpClient, PubkyHttpClientBuilder};
/// let client = PubkyHttpClient::builder()
///     .request_timeout(Duration::from_secs(10))
///     .user_agent_extra("myapp/1.2.3")
///     .build()?;
/// # Ok::<_, pubky::BuildError>(())
/// ```
///
/// 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,
    http_request_timeout: Option<Duration>,

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

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

impl PubkyHttpClientBuilder {
    /// 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
        )]);

        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
    }

    /// Set HTTP requests timeout.
    pub const fn request_timeout(&mut self, timeout: Duration) -> &mut Self {
        self.http_request_timeout = Some(timeout);

        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
    }

    /// 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}")),
            );

        cross_log!(
            info,
            "Building PubkyHttpClient (timeout: {:?}, user_agent: {})",
            self.http_request_timeout,
            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());

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

            icann_http_builder = icann_http_builder.timeout(timeout);
        }
        Ok(PubkyHttpClient {
            pkarr,
            http: http_builder.build()?,

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

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

/// 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`, `PubkyAuthFlow`) 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.
/// - Internally, uses a unified `cross_request(..)` that works the same on native rust and
///   WASM (WASM performs endpoint resolution & header injection; native is a thin wrapper).
///
/// ### 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, private method `cross_request(..)` 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 on native targets. On WASM, use the high-level
/// actors (e.g., `Pubky`, `SessionStorage`, `PublicStorage`) or the JS bindings’
/// `client.fetch(..)` provided in `bindings/js`.
///
/// Fetching a Pubky resource via its transport URL:
/// ```no_run
/// # use pubky::{PubkyHttpClient, Result};
/// # use reqwest::Method;
/// # 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 = format!("https://_pubky.{user}/pub/pubky.app/profile.json");
/// let resp = client.request(Method::GET, &url).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 cookie.
#[derive(Clone, Debug)]
pub struct PubkyHttpClient {
    pub(crate) http: reqwest::Client,
    pub(crate) pkarr: pkarr::Client,

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

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

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};

    use super::*;

    #[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();
    }
}