1use std::{collections::HashMap, sync::Arc, time::Duration};
2
3use futures::lock::Mutex;
4use reqwest::Client;
5use serde::{Deserialize, Serialize};
6
7#[cfg(not(target_family = "wasm"))]
8use tokio::spawn;
9#[cfg(target_family = "wasm")]
10use wasm_bindgen_futures::spawn_local as spawn;
11
12use posemesh_utils::now_unix_secs;
13#[cfg(target_family = "wasm")]
14use posemesh_utils::sleep;
15#[cfg(not(target_family = "wasm"))]
16use tokio::time::sleep;
17
18use crate::auth::{AuthClient, TokenCache, get_cached_or_fresh_token, parse_jwt};
19pub const ALL_DOMAINS_ORG: &str = "all";
20pub const OWN_DOMAINS_ORG: &str = "own";
21
22#[derive(Debug, Deserialize, Clone, Serialize)]
23pub struct DomainServer {
24 pub id: String,
25 pub organization_id: String,
26 pub name: String,
27 pub url: String,
28}
29
30#[derive(Debug, Deserialize, Clone)]
31pub struct DomainWithToken {
32 #[serde(flatten)]
33 pub domain: DomainWithServer,
34 #[serde(skip)]
35 pub expires_at: u64,
36 access_token: String,
37}
38impl TokenCache for DomainWithToken {
39 fn get_access_token(&self) -> String {
40 self.access_token.clone()
41 }
42
43 fn get_expires_at(&self) -> u64 {
44 self.expires_at
45 }
46}
47
48#[derive(Debug, Deserialize, Clone, Serialize)]
49pub struct DomainWithServer {
50 pub id: String,
51 pub name: String,
52 pub organization_id: String,
53 pub domain_server_id: String,
54 pub redirect_url: Option<String>,
55 pub domain_server: DomainServer,
56}
57
58#[derive(Debug, Clone)]
59pub struct DiscoveryService {
60 dds_url: String,
61 client: Client,
62 cache: Arc<Mutex<HashMap<String, DomainWithToken>>>,
63 api_client: AuthClient,
64 oidc_access_token: Option<String>,
65}
66
67#[derive(Debug, Deserialize)]
68pub struct ListDomainsResponse {
69 pub domains: Vec<DomainWithServer>,
70}
71
72impl DiscoveryService {
73 pub fn new(api_url: &str, dds_url: &str, client_id: &str) -> Self {
74 let api_client = AuthClient::new(api_url, client_id);
75
76 Self {
77 dds_url: dds_url.to_string(),
78 client: Client::new(),
79 cache: Arc::new(Mutex::new(HashMap::new())),
80 api_client,
81 oidc_access_token: None,
82 }
83 }
84
85 pub async fn list_domains(
87 &self,
88 org: &str,
89 ) -> Result<Vec<DomainWithServer>, Box<dyn std::error::Error + Send + Sync>> {
90 let access_token = self
91 .api_client
92 .get_dds_access_token(self.oidc_access_token.as_deref())
93 .await?;
94 let response = self
95 .client
96 .get(&format!(
97 "{}/api/v1/domains?org={}&with=domain_server",
98 self.dds_url, org
99 ))
100 .bearer_auth(access_token)
101 .header("Content-Type", "application/json")
102 .header("posemesh-client-id", self.api_client.client_id.clone())
103 .send()
104 .await?;
105
106 if response.status().is_success() {
107 let domain_servers: ListDomainsResponse = response.json().await?;
108 Ok(domain_servers.domains)
109 } else {
110 Err(format!("Failed to list domains. Status: {}", response.status()).into())
111 }
112 }
113
114 pub async fn sign_in_with_auki_account(
115 &mut self,
116 email: &str,
117 password: &str,
118 remember_password: bool,
119 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
120 self.cache.lock().await.clear();
121 self.oidc_access_token = None;
122 let _ = self.api_client.user_login(email, password).await?;
123 if remember_password {
124 let mut api_client = self.api_client.clone();
125 let email = email.to_string();
126 let password = password.to_string();
127 spawn(async move {
128 loop {
129 let expires_at = api_client
130 .get_expires_at()
131 .await
132 .inspect_err(|e| tracing::error!("Failed to get expires at: {}", e));
133 if let Ok(expires_at) = expires_at {
134 let expiration = {
135 let now = now_unix_secs();
136 let duration = expires_at - now;
137 if duration > 600 {
138 Some(Duration::from_secs(duration))
139 } else {
140 None
141 }
142 };
143
144 if let Some(expiration) = expiration {
145 tracing::info!("Refreshing token in {} seconds", expiration.as_secs());
146 sleep(expiration).await;
147 }
148
149 let _ = api_client
150 .user_login(&email, &password)
151 .await
152 .inspect_err(|e| tracing::error!("Failed to login: {}", e));
153 }
154 }
155 });
156 }
157 Ok(())
158 }
159
160 pub async fn sign_in_as_auki_app(
161 &mut self,
162 app_key: &str,
163 app_secret: &str,
164 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
165 self.cache.lock().await.clear();
166 self.oidc_access_token = None;
167 let _ = self
168 .api_client
169 .sign_in_with_app_credentials(app_key, app_secret)
170 .await?;
171 Ok(())
172 }
173
174 pub fn with_oidc_access_token(&self, oidc_access_token: &str) -> Self {
175 if let Some(cached_oidc_access_token) = self.oidc_access_token.as_deref() {
176 if cached_oidc_access_token == oidc_access_token {
177 return self.clone();
178 }
179 }
180 Self {
181 dds_url: self.dds_url.clone(),
182 client: self.client.clone(),
183 cache: Arc::new(Mutex::new(HashMap::new())),
184 api_client: AuthClient::new(&self.api_client.api_url, &self.api_client.client_id),
185 oidc_access_token: Some(oidc_access_token.to_string()),
186 }
187 }
188
189 pub async fn auth_domain(
190 &self,
191 domain_id: &str,
192 ) -> Result<DomainWithToken, Box<dyn std::error::Error + Send + Sync>> {
193 let access_token = self
194 .api_client
195 .get_dds_access_token(self.oidc_access_token.as_deref())
196 .await?;
197 let cache = if let Some(cached_domain) = self.cache.lock().await.get(domain_id) {
199 cached_domain.clone()
200 } else {
201 DomainWithToken {
202 domain: DomainWithServer {
203 id: domain_id.to_string(),
204 name: "".to_string(),
205 organization_id: "".to_string(),
206 domain_server_id: "".to_string(),
207 redirect_url: None,
208 domain_server: DomainServer {
209 id: "".to_string(),
210 organization_id: "".to_string(),
211 name: "".to_string(),
212 url: "".to_string(),
213 },
214 },
215 expires_at: 0,
216 access_token: "".to_string(),
217 }
218 };
219
220 let cached = get_cached_or_fresh_token(&cache, || {
221 let client = self.client.clone();
222 let dds_url = self.dds_url.clone();
223 let client_id = self.api_client.client_id.clone();
224 async move {
225 let response = client
226 .post(&format!("{}/api/v1/domains/{}/auth", dds_url, domain_id))
227 .bearer_auth(access_token)
228 .header("Content-Type", "application/json")
229 .header("posemesh-client-id", client_id)
230 .send()
231 .await?;
232
233 if response.status().is_success() {
234 let mut domain_with_token: DomainWithToken = response.json().await?;
235 domain_with_token.expires_at =
236 parse_jwt(&domain_with_token.get_access_token())?.exp;
237 Ok(domain_with_token)
238 } else {
239 let status = response.status();
240 let text = response
241 .text()
242 .await
243 .unwrap_or_else(|_| "Unknown error".to_string());
244 Err(format!("Failed to auth domain. Status: {} - {}", status, text).into())
245 }
246 }
247 })
248 .await?;
249
250 let mut cache = self.cache.lock().await;
252 cache.insert(domain_id.to_string(), cached.clone());
253 Ok(cached)
254 }
255}