posemesh-domain-http 1.5.3

HTTP client library for interacting with AukiLabs domain data services, supporting both native and WebAssembly targets.
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
use std::{collections::HashMap, sync::Arc, time::Duration};

use futures::lock::Mutex;
use reqwest::Client;
use serde::{Deserialize, Serialize};

#[cfg(not(target_family = "wasm"))]
use tokio::spawn;
#[cfg(target_family = "wasm")]
use wasm_bindgen_futures::spawn_local as spawn;

use posemesh_utils::now_unix_secs;
#[cfg(target_family = "wasm")]
use posemesh_utils::sleep;
#[cfg(not(target_family = "wasm"))]
use tokio::time::sleep;

use crate::{
    auth::{AuthClient, REFRESH_CACHE_TIME, TokenCache, get_cached_or_fresh_token, parse_jwt},
    errors::{AukiErrorResponse, DomainError},
};
pub const ALL_DOMAINS_ORG: &str = "all";
pub const OWN_DOMAINS_ORG: &str = "own";

#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct DomainServer {
    pub id: String,
    pub organization_id: String,
    pub name: String,
    pub url: String,
}

#[derive(Debug, Deserialize, Clone)]
pub struct DomainWithToken {
    #[serde(flatten)]
    pub domain: DomainWithServer,
    #[serde(skip)]
    pub expires_at: u64,
    access_token: String,
}

impl TokenCache for DomainWithToken {
    fn get_access_token(&self) -> String {
        self.access_token.clone()
    }

    fn get_expires_at(&self) -> u64 {
        self.expires_at
    }
}

#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct DomainWithServer {
    pub id: String,
    pub name: String,
    pub organization_id: String,
    pub domain_server_id: String,
    pub redirect_url: Option<String>,
    pub domain_server: DomainServer,
}

#[derive(Debug, Clone)]
pub struct DiscoveryService {
    dds_url: String,
    client: Client,
    cache: Arc<Mutex<HashMap<String, DomainWithToken>>>,
    api_client: AuthClient,
    oidc_access_token: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct ListDomainsResponse {
    pub domains: Vec<DomainWithServer>,
}

#[derive(Debug, Serialize)]
pub struct CreateDomainRequest {
    pub name: String,
    pub domain_server_id: String,
    pub redirect_url: Option<String>,
    domain_server_url: String,
}

/// Returns the gateway MAC address on native targets. On WASM/browser this always returns
/// empty string — browsers cannot access network interfaces, gateway, or MAC addresses.
fn get_mac_address() -> Result<String, DomainError> {
    #[cfg(not(target_family = "wasm"))]
    {
        match default_net::get_default_gateway() {
            Ok(gateway) => Ok(gateway.mac_addr.to_string()),
            Err(_) => Err(DomainError::InvalidRequest("No gateway found")),
        }
    }

    #[cfg(target_family = "wasm")]
    {
        // Browsers cannot access network interfaces, gateway IP, or MAC addresses.
        // Return empty string so auth still works; server may use other identifiers.
        Ok(String::new())
    }
}

impl DiscoveryService {
    pub fn new(api_url: &str, dds_url: &str, client_id: &str) -> Self {
        let api_client = AuthClient::new(api_url, client_id);

        Self {
            dds_url: dds_url.to_string(),
            client: Client::new(),
            cache: Arc::new(Mutex::new(HashMap::new())),
            api_client,
            oidc_access_token: None,
        }
    }

    /// List domains with domain server without issue token
    ///
    /// - org: (required) The organization to list domains from:
    ///   - "own": returns domains in your own organization.
    ///   - a UUID: returns domains in that specific organization.
    ///   - "all": returns domains across all organizations.
    ///     Otherwise, 'domain_server_id' is required and the domain server must belong to your org.
    ///     Not available for app tokens.
    /// - domain_server_id: (optional) UUID of the domain server to filter domains. Ignored if a portal filter is active.
    ///
    /// # Access control
    ///   - App tokens can only see domains where the app is on the domain's app allowlist
    ///     (or the domain has no app allowlist).
    ///   - User tokens can see all domains in their own org. When requesting domains outside
    ///     their org, they can only see domains where their org is on the domain's user-org
    ///     allowlist (or the domain has no user-org allowlist).
    ///
    pub async fn list_domains(
        &self,
        org: &str,
        domain_server_id: Option<&str>,
    ) -> Result<ListDomainsResponse, DomainError> {
        let access_token = self
            .api_client
            .get_dds_access_token(self.oidc_access_token.as_deref())
            .await?;
        let mut url = format!(
            "{}/api/v1/domains?org={}&with=domain_server",
            self.dds_url, org
        );
        if let Some(domain_server_id) = domain_server_id {
            url.push_str(&format!("&domain_server_id={}", domain_server_id));
        }
        let response = self
            .client
            .get(&url)
            .bearer_auth(access_token)
            .header("Content-Type", "application/json")
            .header("posemesh-client-id", self.api_client.client_id.clone())
            .header("posemesh-sdk-version", crate::VERSION)
            .header(
                "posemesh-gateway-mac",
                get_mac_address().unwrap_or_default(),
            )
            .send()
            .await?;

        if response.status().is_success() {
            let domain_servers: ListDomainsResponse = response.json().await?;
            Ok(domain_servers)
        } else {
            let status = response.status();
            let text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            Err(AukiErrorResponse {
                status,
                error: format!("Failed to list domains. {}", text),
            }
            .into())
        }
    }

    pub async fn sign_in_with_auki_account(
        &mut self,
        email: &str,
        password: &str,
        remember_password: bool,
    ) -> Result<String, DomainError> {
        self.cache.lock().await.clear();
        self.oidc_access_token = None;
        let token = self.api_client.user_login(email, password).await?;
        if remember_password {
            let mut api_client = self.api_client.clone();
            let email = email.to_string();
            let password = password.to_string();
            spawn(async move {
                loop {
                    let expires_at = api_client
                        .get_expires_at()
                        .await
                        .inspect_err(|e| tracing::error!("Failed to get expires at: {}", e));
                    if let Ok(expires_at) = expires_at {
                        let expiration = {
                            let now = now_unix_secs();
                            let duration = expires_at - now;
                            if duration > REFRESH_CACHE_TIME {
                                Some(Duration::from_secs(duration))
                            } else {
                                None
                            }
                        };

                        if let Some(expiration) = expiration {
                            tracing::info!("Refreshing token in {} seconds", expiration.as_secs());
                            sleep(expiration).await;
                        }

                        let _ = api_client
                            .user_login(&email, &password)
                            .await
                            .inspect_err(|e| tracing::error!("Failed to relogin: {}", e));
                    }
                }
            });
        }
        Ok(token)
    }

    pub async fn sign_in_as_auki_app(
        &mut self,
        app_key: &str,
        app_secret: &str,
    ) -> Result<String, DomainError> {
        self.cache.lock().await.clear();
        self.oidc_access_token = None;
        self.api_client
            .sign_in_with_app_credentials(app_key, app_secret)
            .await
    }

    pub fn with_oidc_access_token(&self, oidc_access_token: &str) -> Self {
        if let Some(cached_oidc_access_token) = self.oidc_access_token.as_deref()
            && cached_oidc_access_token == oidc_access_token
        {
            return self.clone();
        }
        Self {
            dds_url: self.dds_url.clone(),
            client: self.client.clone(),
            cache: Arc::new(Mutex::new(HashMap::new())),
            api_client: AuthClient::new(&self.api_client.api_url, &self.api_client.client_id),
            oidc_access_token: Some(oidc_access_token.to_string()),
        }
    }

    pub async fn auth_domain(&self, domain_id: &str) -> Result<DomainWithToken, DomainError> {
        let access_token = self
            .api_client
            .get_dds_access_token(self.oidc_access_token.as_deref())
            .await?;
        // Check cache first
        let cache = if let Some(cached_domain) = self.cache.lock().await.get(domain_id) {
            cached_domain.clone()
        } else {
            DomainWithToken {
                domain: DomainWithServer {
                    id: domain_id.to_string(),
                    name: "".to_string(),
                    organization_id: "".to_string(),
                    domain_server_id: "".to_string(),
                    redirect_url: None,
                    domain_server: DomainServer {
                        id: "".to_string(),
                        organization_id: "".to_string(),
                        name: "".to_string(),
                        url: "".to_string(),
                    },
                },
                expires_at: 0,
                access_token: "".to_string(),
            }
        };

        let cached = get_cached_or_fresh_token(&cache, || {
            let client = self.client.clone();
            let dds_url = self.dds_url.clone();
            let client_id = self.api_client.client_id.clone();
            async move {
                let mac_address = get_mac_address().unwrap_or_default();
                let response = client
                    .post(format!("{}/api/v1/domains/{}/auth", dds_url, domain_id))
                    .bearer_auth(access_token)
                    .header("Content-Type", "application/json")
                    .header("posemesh-client-id", client_id)
                    .header("posemesh-sdk-version", crate::VERSION)
                    .header("posemesh-gateway-mac", mac_address)
                    .send()
                    .await?;

                if response.status().is_success() {
                    let mut domain_with_token: DomainWithToken = response.json().await?;
                    domain_with_token.expires_at =
                        parse_jwt(&domain_with_token.get_access_token())?.exp;
                    Ok(domain_with_token)
                } else {
                    let status = response.status();
                    let text = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Unknown error".to_string());
                    Err(AukiErrorResponse {
                        status,
                        error: format!("Failed to auth domain. {}", text),
                    }
                    .into())
                }
            }
        })
        .await?;

        // Cache the result
        let mut cache = self.cache.lock().await;
        cache.insert(domain_id.to_string(), cached.clone());
        Ok(cached)
    }

    pub async fn create_domain(
        &self,
        name: &str,
        domain_server_id: Option<String>,
        domain_server_url: Option<String>,
        redirect_url: Option<String>,
    ) -> Result<DomainWithToken, DomainError> {
        let domain_server_id = domain_server_id.unwrap_or_default();
        let domain_server_url = domain_server_url.unwrap_or_default();
        if domain_server_id.is_empty() && domain_server_url.is_empty() {
            return Err(DomainError::InvalidRequest(
                "domain_server_id or domain_server_url is required",
            ));
        }
        let access_token: String = self
            .api_client
            .get_dds_access_token(self.oidc_access_token.as_deref())
            .await?;
        let response = self
            .client
            .post(format!("{}/api/v1/domains?issue_token=true", self.dds_url))
            .bearer_auth(access_token)
            .header("Content-Type", "application/json")
            .header("posemesh-client-id", self.api_client.client_id.clone())
            .header("posemesh-sdk-version", crate::VERSION)
            .header(
                "posemesh-gateway-mac",
                get_mac_address().unwrap_or_default(),
            )
            .json(&CreateDomainRequest {
                name: name.to_string(),
                domain_server_id: domain_server_id.to_string(),
                redirect_url,
                domain_server_url: domain_server_url.to_string(),
            })
            .send()
            .await?;

        if response.status().is_success() {
            let mut domain_with_token: DomainWithToken = response.json().await?;
            domain_with_token.expires_at = parse_jwt(&domain_with_token.get_access_token())?.exp;
            // Cache the result
            let mut cache = self.cache.lock().await;
            cache.insert(
                domain_with_token.domain.id.clone(),
                domain_with_token.clone(),
            );
            Ok(domain_with_token)
        } else {
            let status = response.status();
            let text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            Err(AukiErrorResponse {
                status,
                error: format!("Failed to create domain. {}", text),
            }
            .into())
        }
    }

    /// List domains by portal, portal_id or portal_short_id is required
    /// If org is not provided, it will list domains for the current authorized organization
    /// If org is provided, it will list domains for the specified organization
    /// Set org to `all` to list domains for all organizations
    pub async fn list_domains_by_portal(
        &self,
        portal_id: Option<&str>,
        portal_short_id: Option<&str>,
        org: &str,
    ) -> Result<ListDomainsResponse, DomainError> {
        let access_token: String = self
            .api_client
            .get_dds_access_token(self.oidc_access_token.as_deref())
            .await?;
        if portal_id.is_none() && portal_short_id.is_none() {
            return Err(DomainError::InvalidRequest(
                "portal_id or portal_short_id is required",
            ));
        }
        let id = portal_id.or(portal_short_id).unwrap();
        let response = self
            .client
            .get(format!(
                "{}/api/v1/lighthouses/{}/domains?with=domain_server,lighthouse&org={}",
                self.dds_url, id, org
            ))
            .bearer_auth(access_token)
            .header("Content-Type", "application/json")
            .header("posemesh-client-id", self.api_client.client_id.clone())
            .header("posemesh-sdk-version", crate::VERSION)
            .header(
                "posemesh-gateway-mac",
                get_mac_address().unwrap_or_default(),
            )
            .send()
            .await?;
        if response.status().is_success() {
            let domains: ListDomainsResponse = response.json().await?;
            Ok(domains)
        } else {
            let status = response.status();
            let text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            Err(AukiErrorResponse {
                status,
                error: format!("Failed to list domains by portal. {}", text),
            }
            .into())
        }
    }

    pub(crate) async fn delete_domain(
        &self,
        access_token: &str,
        domain_id: &str,
    ) -> Result<(), DomainError> {
        let response = self
            .client
            .delete(format!("{}/api/v1/domains/{}", self.dds_url, domain_id))
            .bearer_auth(access_token)
            .header("Content-Type", "application/json")
            .header("posemesh-client-id", self.api_client.client_id.clone())
            .header("posemesh-sdk-version", crate::VERSION)
            .header(
                "posemesh-gateway-mac",
                get_mac_address().unwrap_or_default(),
            )
            .send()
            .await?;
        if response.status().is_success() {
            Ok(())
        } else {
            let status = response.status();
            let text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            Err(AukiErrorResponse {
                status,
                error: format!("Failed to delete domain. {}", text),
            }
            .into())
        }
    }
}