1use std::path::PathBuf;
2
3#[allow(dead_code, unreachable_pub)]
4mod entitlement_cache;
5pub use entitlement_cache::EffectivePlan as VerifiedEffectivePlan;
6
7pub const ENTITLEMENT_DENIAL_PREFIX: &str = "Signed entitlement does not allow ";
8
9fn config_dir() -> PathBuf {
10 crate::core::paths::data_dir()
13 .unwrap_or_else(|_| PathBuf::from("."))
14 .join("cloud")
15}
16
17fn credentials_path() -> PathBuf {
18 config_dir().join("credentials.json")
19}
20
21pub fn api_url() -> String {
26 const LOOPBACK_SINK: &str = "http://127.0.0.1:9";
27 let configured =
28 std::env::var("LEAN_CTX_API_URL").unwrap_or_else(|_| "https://api.leanctx.com".to_string());
29 if cloud_endpoint_allowed(&configured, launched_by_cargo()) {
30 configured
31 } else {
32 LOOPBACK_SINK.to_string()
33 }
34}
35
36#[derive(serde::Serialize, serde::Deserialize)]
37struct Credentials {
38 api_key: String,
39 user_id: String,
40 email: String,
41 #[serde(default)]
42 oauth_client_id: Option<String>,
43 #[serde(default)]
44 oauth_client_secret: Option<String>,
45 #[serde(default)]
46 oauth_access_token: Option<String>,
47 #[serde(default)]
48 oauth_expires_at_unix: Option<i64>,
49}
50
51fn load_credentials() -> Option<Credentials> {
52 let path = credentials_path();
53 tighten_secret_permissions(&path);
56 let data = std::fs::read_to_string(&path).ok()?;
57 serde_json::from_str(&data).ok()
58}
59
60fn write_credentials(creds: &Credentials) -> std::io::Result<()> {
61 let dir = config_dir();
62 std::fs::create_dir_all(&dir)?;
63 restrict_dir_permissions(&dir);
64 let json = serde_json::to_string_pretty(creds).map_err(std::io::Error::other)?;
65 write_secret_file(&credentials_path(), json.as_bytes())
66}
67
68fn write_secret_file(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
72 use std::io::Write;
73
74 let parent = path
75 .parent()
76 .ok_or_else(|| std::io::Error::other("credentials path has no parent directory"))?;
77 let name = path
78 .file_name()
79 .ok_or_else(|| std::io::Error::other("credentials path has no file name"))?
80 .to_string_lossy();
81 let tmp = parent.join(format!(".{name}.tmp.{}", std::process::id()));
82
83 let mut opts = std::fs::OpenOptions::new();
84 opts.write(true).create_new(true);
85 #[cfg(unix)]
86 {
87 use std::os::unix::fs::OpenOptionsExt;
88 opts.mode(0o600);
89 }
90
91 let result = (|| {
92 let mut f = opts.open(&tmp)?;
93 f.write_all(bytes)?;
94 f.sync_all()?;
95 drop(f);
96 #[cfg(windows)]
97 {
98 if path.exists() {
99 std::fs::remove_file(path)?;
100 }
101 }
102 std::fs::rename(&tmp, path)
103 })();
104
105 if result.is_err() {
106 let _ = std::fs::remove_file(&tmp);
107 }
108 result
109}
110
111#[cfg(unix)]
112fn restrict_dir_permissions(dir: &std::path::Path) {
113 use std::os::unix::fs::PermissionsExt;
114 let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
115}
116
117#[cfg(not(unix))]
118fn restrict_dir_permissions(_dir: &std::path::Path) {}
119
120#[cfg(unix)]
121fn tighten_secret_permissions(path: &std::path::Path) {
122 use std::os::unix::fs::PermissionsExt;
123 if let Ok(meta) = std::fs::metadata(path)
124 && meta.permissions().mode() & 0o077 != 0
125 {
126 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
127 }
128}
129
130#[cfg(not(unix))]
131fn tighten_secret_permissions(_path: &std::path::Path) {}
132
133pub fn save_credentials(api_key: &str, user_id: &str, email: &str) -> std::io::Result<()> {
134 let mut creds = load_credentials().unwrap_or(Credentials {
135 api_key: api_key.to_string(),
136 user_id: user_id.to_string(),
137 email: email.to_string(),
138 oauth_client_id: None,
139 oauth_client_secret: None,
140 oauth_access_token: None,
141 oauth_expires_at_unix: None,
142 });
143 creds.api_key = api_key.to_string();
144 creds.user_id = user_id.to_string();
145 creds.email = email.to_string();
146 creds.oauth_access_token = None;
148 creds.oauth_expires_at_unix = None;
149 write_credentials(&creds)
150}
151
152pub fn load_api_key() -> Option<String> {
153 load_credentials().map(|c| c.api_key)
154}
155
156pub fn is_logged_in() -> bool {
157 load_credentials().is_some()
158}
159
160fn now_unix() -> i64 {
161 use std::time::{SystemTime, UNIX_EPOCH};
162 SystemTime::now()
163 .duration_since(UNIX_EPOCH)
164 .unwrap_or_default()
165 .as_secs() as i64
166}
167
168fn device_label() -> String {
173 gethostname::gethostname().to_string_lossy().into_owned()
174}
175
176fn auth_bearer_token() -> Result<String, String> {
177 let mut creds = load_credentials().ok_or("Not logged in. Run: lean-ctx login")?;
178
179 if let (Some(client_id), Some(client_secret)) = (
180 creds.oauth_client_id.clone(),
181 creds.oauth_client_secret.clone(),
182 ) {
183 let now = now_unix();
184 if let (Some(token), Some(exp)) = (
185 creds.oauth_access_token.clone(),
186 creds.oauth_expires_at_unix,
187 ) && exp > now + 10
188 {
189 return Ok(token);
190 }
191
192 let url = format!("{}/oauth/token", api_url());
193 let resp = ureq::post(&url)
194 .header("Content-Type", "application/x-www-form-urlencoded")
195 .send_form([
196 ("grant_type", "client_credentials"),
197 ("client_id", client_id.as_str()),
198 ("client_secret", client_secret.as_str()),
199 ])
200 .map_err(|e| format!("OAuth token request failed: {e}"))?;
201
202 let resp_body = resp
203 .into_body()
204 .read_to_string()
205 .map_err(|e| format!("Failed to read OAuth response: {e}"))?;
206
207 let json: serde_json::Value =
208 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
209
210 let token = json["access_token"]
211 .as_str()
212 .ok_or("Missing access_token in response")?
213 .to_string();
214 let expires_in = json["expires_in"].as_i64().unwrap_or(3600);
215 let exp = now + expires_in.saturating_sub(30);
216
217 creds.oauth_access_token = Some(token.clone());
218 creds.oauth_expires_at_unix = Some(exp);
219 let _ = write_credentials(&creds);
220
221 return Ok(token);
222 }
223
224 Ok(creds.api_key)
225}
226
227pub fn oauth_register_client(client_name: Option<&str>) -> Result<String, String> {
228 let mut creds = load_credentials().ok_or("Not logged in. Run: lean-ctx login")?;
229 if creds.oauth_client_id.is_some() && creds.oauth_client_secret.is_some() {
230 return Ok("OAuth client already registered.".to_string());
231 }
232
233 let url = format!("{}/oauth/register", api_url());
234 let body = if let Some(name) = client_name {
235 serde_json::json!({ "client_name": name })
236 } else {
237 serde_json::json!({})
238 };
239
240 let resp = ureq::post(&url)
241 .header("Authorization", &format!("Bearer {}", creds.api_key))
242 .header("Content-Type", "application/json")
243 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
244 .map_err(|e| format!("OAuth register failed: {e}"))?;
245
246 let resp_body = resp
247 .into_body()
248 .read_to_string()
249 .map_err(|e| format!("Failed to read response: {e}"))?;
250
251 let json: serde_json::Value =
252 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
253
254 creds.oauth_client_id = Some(
255 json["client_id"]
256 .as_str()
257 .ok_or("Missing client_id in response")?
258 .to_string(),
259 );
260 creds.oauth_client_secret = Some(
261 json["client_secret"]
262 .as_str()
263 .ok_or("Missing client_secret in response")?
264 .to_string(),
265 );
266 creds.oauth_access_token = None;
267 creds.oauth_expires_at_unix = None;
268 write_credentials(&creds).map_err(|e| format!("Failed to persist OAuth credentials: {e}"))?;
269
270 Ok("OAuth client registered. Cloud requests will use short-lived access tokens.".to_string())
271}
272
273pub struct RegisterResult {
274 pub api_key: String,
275 pub user_id: String,
276 pub email_verified: bool,
277 pub verification_sent: bool,
278}
279
280pub fn register(email: &str, password: Option<&str>) -> Result<RegisterResult, String> {
281 let url = format!("{}/api/auth/register", api_url());
282 let mut body = serde_json::json!({ "email": email, "device_label": device_label() });
285 if let Some(pw) = password {
286 body["password"] = serde_json::Value::String(pw.to_string());
287 }
288
289 let resp = ureq::post(&url)
290 .header("Content-Type", "application/json")
291 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
292 .map_err(|e| format!("Request failed: {e}"))?;
293
294 let resp_body = resp
295 .into_body()
296 .read_to_string()
297 .map_err(|e| format!("Failed to read response: {e}"))?;
298
299 let json: serde_json::Value =
300 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
301
302 Ok(RegisterResult {
303 api_key: json["api_key"]
304 .as_str()
305 .ok_or("Missing api_key in response")?
306 .to_string(),
307 user_id: json["user_id"]
308 .as_str()
309 .ok_or("Missing user_id in response")?
310 .to_string(),
311 email_verified: json["email_verified"].as_bool().unwrap_or(false),
312 verification_sent: json["verification_sent"].as_bool().unwrap_or(false),
313 })
314}
315
316pub fn forgot_password(email: &str) -> Result<String, String> {
317 let url = format!("{}/api/auth/forgot-password", api_url());
318 let body = serde_json::json!({ "email": email });
319
320 let resp = ureq::post(&url)
321 .header("Content-Type", "application/json")
322 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
323 .map_err(|e| format!("Request failed: {e}"))?;
324
325 let resp_body = resp
326 .into_body()
327 .read_to_string()
328 .map_err(|e| format!("Failed to read response: {e}"))?;
329
330 let json: serde_json::Value =
331 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
332
333 Ok(json["message"]
334 .as_str()
335 .unwrap_or("If an account exists, a reset email has been sent.")
336 .to_string())
337}
338
339pub fn login(email: &str, password: &str) -> Result<RegisterResult, String> {
340 let url = format!("{}/api/auth/login", api_url());
341 let body = serde_json::json!({
342 "email": email,
343 "password": password,
344 "device_label": device_label(),
345 });
346
347 let resp = ureq::post(&url)
348 .header("Content-Type", "application/json")
349 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
350 .map_err(|e| {
351 let msg = e.to_string();
352 if msg.contains("401") {
353 "Invalid email or password".to_string()
354 } else {
355 format!("Request failed: {e}")
356 }
357 })?;
358
359 let resp_body = resp
360 .into_body()
361 .read_to_string()
362 .map_err(|e| format!("Failed to read response: {e}"))?;
363
364 let json: serde_json::Value =
365 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
366
367 Ok(RegisterResult {
368 api_key: json["api_key"]
369 .as_str()
370 .ok_or("Missing api_key in response")?
371 .to_string(),
372 user_id: json["user_id"]
373 .as_str()
374 .ok_or("Missing user_id in response")?
375 .to_string(),
376 email_verified: json["email_verified"].as_bool().unwrap_or(false),
377 verification_sent: false,
378 })
379}
380
381pub fn sync_stats(stats: &[serde_json::Value]) -> Result<String, String> {
382 let bearer = auth_bearer_token()?;
383 let url = format!("{}/api/stats", api_url());
384
385 let body = serde_json::json!({ "stats": stats });
386
387 let resp = ureq::post(&url)
388 .header("Authorization", &format!("Bearer {bearer}"))
389 .header("Content-Type", "application/json")
390 .header("X-Device-Label", &device_label())
391 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
392 .map_err(|e| format!("Sync failed: {e}"))?;
393
394 let resp_body = resp
395 .into_body()
396 .read_to_string()
397 .map_err(|e| format!("Failed to read response: {e}"))?;
398
399 let json: serde_json::Value =
400 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
401
402 Ok(json["message"].as_str().unwrap_or("Synced").to_string())
403}
404
405pub fn contribute(entries: &[serde_json::Value]) -> Result<String, String> {
406 let url = format!("{}/api/contribute", api_url());
407
408 let body = serde_json::json!({ "entries": entries });
409
410 let resp = ureq::post(&url)
411 .header("Content-Type", "application/json")
412 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
413 .map_err(|e| format!("Contribute failed: {e}"))?;
414
415 let resp_body = resp
416 .into_body()
417 .read_to_string()
418 .map_err(|e| format!("Failed to read response: {e}"))?;
419
420 let json: serde_json::Value =
421 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
422
423 Ok(json["message"]
424 .as_str()
425 .unwrap_or("Contributed")
426 .to_string())
427}
428
429pub fn heartbeat(payload: &serde_json::Value) -> Result<String, String> {
432 let url = format!("{}/api/telemetry/heartbeat", api_url());
433
434 let resp = ureq::post(&url)
435 .header("Content-Type", "application/json")
436 .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
437 .map_err(|e| format!("Heartbeat failed: {e}"))?;
438
439 let resp_body = resp
440 .into_body()
441 .read_to_string()
442 .map_err(|e| format!("Failed to read response: {e}"))?;
443
444 let json: serde_json::Value =
445 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
446
447 Ok(json["message"].as_str().unwrap_or("OK").to_string())
448}
449
450pub fn submit_product_feedback(payload: &serde_json::Value) -> Result<String, String> {
462 let url = format!("{}/api/feedback/product", api_url());
463
464 let resp = ureq::post(&url)
465 .header("Content-Type", "application/json")
466 .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
467 .map_err(|e| format!("Could not send feedback: {e}"))?;
468
469 let body = resp
470 .into_body()
471 .read_to_string()
472 .map_err(|e| format!("Failed to read response: {e}"))?;
473
474 let json: serde_json::Value =
475 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
476
477 Ok(json["message"].as_str().unwrap_or("Thanks").to_string())
478}
479
480fn launched_by_cargo() -> bool {
483 std::env::var("CARGO_PKG_NAME").is_ok_and(|name| name == env!("CARGO_PKG_NAME"))
484}
485
486fn cloud_endpoint_allowed(base_url: &str, launched_by_cargo: bool) -> bool {
489 if !cfg!(test) && !launched_by_cargo {
490 return true;
491 }
492 let Some(authority) = base_url
493 .strip_prefix("http://")
494 .or_else(|| base_url.strip_prefix("https://"))
495 .and_then(|rest| rest.split(['/', '?', '#']).next())
496 else {
497 return false;
498 };
499 if authority.contains('@') {
500 return false;
501 }
502 let host = match authority.strip_prefix('[') {
503 Some(bracketed) => bracketed.split(']').next().unwrap_or_default(),
504 None => authority.split(':').next().unwrap_or_default(),
505 };
506 host.eq_ignore_ascii_case("localhost")
507 || host
508 .parse::<std::net::IpAddr>()
509 .is_ok_and(|ip| ip.is_loopback())
510}
511
512pub fn telemetry_v2_batch(
514 batch: &crate::core::telemetry_v2::TelemetryBatchV2,
515) -> Result<String, String> {
516 telemetry_v2_batch_with_timeout(batch, std::time::Duration::from_secs(10))
517}
518
519pub(crate) fn telemetry_v2_batch_with_timeout(
520 batch: &crate::core::telemetry_v2::TelemetryBatchV2,
521 timeout: std::time::Duration,
522) -> Result<String, String> {
523 let config = crate::core::config::Config::try_load_global()
525 .map_err(|_| "Telemetry configuration unavailable".to_string())?;
526 let do_not_track = crate::core::host_env::var("DO_NOT_TRACK");
527 let telemetry_override = crate::core::host_env::var("LEAN_CTX_TELEMETRY");
528 if !config
529 .telemetry
530 .send_eligible(do_not_track.as_deref(), telemetry_override.as_deref())
531 {
532 return Err("Telemetry sending is disabled".to_string());
533 }
534 if crate::core::telemetry_consent::running_in_ci() {
535 return Err("Telemetry is not sent from CI".to_string());
536 }
537 batch
538 .validate()
539 .map_err(|error| format!("Telemetry validation failed: {error:?}"))?;
540 let url = format!("{}/api/telemetry/v2/batch", api_url());
541 let response = ureq::post(&url)
542 .config()
543 .timeout_global(Some(timeout))
544 .build()
545 .header("Content-Type", "application/json")
546 .send(&serde_json::to_vec(batch).map_err(|error| format!("JSON error: {error}"))?)
547 .map_err(|error| format!("Telemetry v2 batch failed: {error}"))?;
548 let body = response
549 .into_body()
550 .read_to_string()
551 .map_err(|error| format!("Failed to read response: {error}"))?;
552 let json: serde_json::Value =
553 serde_json::from_str(&body).map_err(|error| format!("Invalid JSON: {error}"))?;
554 crate::core::telemetry_notices::remember(crate::core::telemetry_notices::from_response(&json));
555 Ok(json["message"].as_str().unwrap_or("OK").to_string())
556}
557
558pub fn delete_remote_telemetry(
560 installation_id: &str,
561 deletion_token: &str,
562) -> Result<bool, String> {
563 let installation_id = uuid::Uuid::parse_str(installation_id)
564 .map_err(|_| "Invalid installation ID".to_string())?;
565 let url = format!(
566 "{}/api/telemetry/v2/installations/{installation_id}",
567 api_url()
568 );
569 if deletion_token.len() != 64
570 || !deletion_token
571 .bytes()
572 .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
573 {
574 return Err("Invalid telemetry deletion credential".to_string());
575 }
576 let response = ureq::delete(&url)
577 .header(
578 "Authorization",
579 &format!("TelemetryDelete v1.{deletion_token}"),
580 )
581 .call()
582 .map_err(|error| format!("Remote telemetry deletion failed: {error}"))?;
583 let status = response.status().as_u16();
584 let body = response
585 .into_body()
586 .read_to_string()
587 .map_err(|error| format!("Failed to read deletion response: {error}"))?;
588 deletion_confirmed(status, &body)
589}
590
591fn deletion_confirmed(status: u16, body: &str) -> Result<bool, String> {
592 if status == 204 {
593 return Ok(false);
594 }
595 let value: serde_json::Value = serde_json::from_str(body)
596 .map_err(|error| format!("Invalid deletion response: {error}"))?;
597 Ok(value.get("deleted").and_then(serde_json::Value::as_bool) == Some(true))
598}
599
600#[derive(serde::Deserialize)]
604pub struct PublishedCard {
605 pub id: String,
606 #[serde(default)]
607 pub edit_token: Option<String>,
608 #[serde(default)]
609 pub edit_token_challenge: Option<String>,
610 #[serde(default)]
611 pub challenge_expires_in_secs: Option<i64>,
612 pub url: String,
613 #[serde(skip)]
614 pub account_claimed: bool,
615}
616
617pub fn publish_wrapped(payload: &serde_json::Value) -> Result<PublishedCard, String> {
622 let url = format!("{}/api/wrapped", api_url());
623
624 let mut req = ureq::post(&url).header("Content-Type", "application/json");
625 if let Ok(token) = auth_bearer_token() {
626 req = req.header("Authorization", &format!("Bearer {token}"));
627 }
628 let resp = req
629 .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
630 .map_err(|e| format!("Publish failed: {e}"))?;
631
632 let resp_body = resp
633 .into_body()
634 .read_to_string()
635 .map_err(|e| format!("Failed to read response: {e}"))?;
636
637 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
638}
639
640#[derive(serde::Deserialize)]
641struct RecoveredEditToken {
642 edit_token: String,
643}
644
645pub fn recover_wrapped_edit_token(
648 id: &str,
649 nonce: &str,
650 public_key: &str,
651 signature: &str,
652) -> Result<String, String> {
653 let url = format!("{}/api/wrapped/{id}/edit-token/recover", api_url());
654 let body = serde_json::json!({
655 "nonce": nonce,
656 "public_key": public_key,
657 "signature": signature,
658 });
659 let resp = ureq::post(&url)
660 .header("Content-Type", "application/json")
661 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
662 .map_err(|e| format!("Edit-token recovery failed: {e}"))?;
663 let response = resp
664 .into_body()
665 .read_to_string()
666 .map_err(|e| format!("Failed to read response: {e}"))?;
667 let recovered: RecoveredEditToken =
668 serde_json::from_str(&response).map_err(|e| format!("Invalid recovery response: {e}"))?;
669 if recovered.edit_token.is_empty() {
670 return Err("Invalid recovery response: empty edit token".to_string());
671 }
672 Ok(recovered.edit_token)
673}
674
675pub fn unpublish_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
682 let url = format!("{}/api/wrapped/{id}", api_url());
683
684 match ureq::delete(&url).header("X-Edit-Token", edit_token).call() {
685 Ok(_) | Err(ureq::Error::StatusCode(404 | 410)) => Ok(()),
687 Err(e) => Err(format!("Unpublish failed: {e}")),
688 }
689}
690
691pub fn claim_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
695 let bearer = auth_bearer_token()?;
696 let url = format!("{}/api/wrapped/{id}/claim", api_url());
697
698 ureq::post(&url)
699 .header("Authorization", &format!("Bearer {bearer}"))
700 .header("X-Edit-Token", edit_token)
701 .send_empty()
702 .map_err(|e| format!("Claim failed: {e}"))?;
703 Ok(())
704}
705
706#[derive(serde::Deserialize)]
708pub struct LinkCode {
709 pub code: String,
710 pub expires_in_secs: i64,
711}
712
713pub fn link_wrapped_start(id: &str, edit_token: &str) -> Result<LinkCode, String> {
716 let url = format!("{}/api/wrapped/{id}/link/start", api_url());
717
718 let resp = ureq::post(&url)
719 .header("X-Edit-Token", edit_token)
720 .send_empty()
721 .map_err(|e| format!("Link start failed: {e}"))?;
722 let body = resp
723 .into_body()
724 .read_to_string()
725 .map_err(|e| format!("Failed to read response: {e}"))?;
726 serde_json::from_str(&body).map_err(|e| format!("Invalid response: {e}"))
727}
728
729pub fn link_wrapped_complete(id: &str, edit_token: &str, code: &str) -> Result<(), String> {
733 let url = format!("{}/api/wrapped/{id}/link/complete", api_url());
734 let body = serde_json::json!({ "code": code });
735
736 ureq::post(&url)
737 .header("X-Edit-Token", edit_token)
738 .header("Content-Type", "application/json")
739 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
740 .map_err(|e| match e {
741 ureq::Error::StatusCode(404) => {
742 "code invalid or expired — mint a fresh one with lean-ctx gain --link".to_string()
743 }
744 other => format!("Link failed: {other}"),
745 })?;
746 Ok(())
747}
748
749pub fn push_knowledge(entries: &[serde_json::Value]) -> Result<String, String> {
754 let bearer = auth_bearer_token()?;
755 let key = knowledge_vault_key()?;
756 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
757 let url = format!("{}/api/sync/knowledge", api_url());
758
759 let resp = ureq::post(&url)
760 .header("Authorization", &format!("Bearer {bearer}"))
761 .header("Content-Type", "application/octet-stream")
762 .header("X-Entry-Count", &entries.len().to_string())
763 .header("X-Device-Label", &device_label())
764 .send(blob.as_slice())
765 .map_err(|e| format!("Push failed: {e}"))?;
766
767 let resp_body = resp
768 .into_body()
769 .read_to_string()
770 .map_err(|e| format!("Failed to read response: {e}"))?;
771
772 let json: serde_json::Value =
773 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
774
775 Ok(format!(
776 "{} entries synced (end-to-end encrypted)",
777 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
778 ))
779}
780
781fn knowledge_vault_key() -> Result<[u8; 32], String> {
784 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
785 if api_key.trim().is_empty() {
786 return Err("Not logged in. Run: lean-ctx login".into());
787 }
788 Ok(crate::core::knowledge_vault::derive_vault_key(&api_key))
789}
790
791pub fn pull_cloud_models() -> Result<serde_json::Value, String> {
792 let bearer = auth_bearer_token()?;
793 let url = format!("{}/api/cloud/models", api_url());
794
795 let resp = ureq::get(&url)
796 .header("Authorization", &format!("Bearer {bearer}"))
797 .call()
798 .map_err(|e| {
799 let msg = e.to_string();
800 if msg.contains("403") {
801 "This feature is not available for your account.".to_string()
802 } else {
803 format!("Connection failed. Check your internet connection. ({e})")
804 }
805 })?;
806
807 let resp_body = resp
808 .into_body()
809 .read_to_string()
810 .map_err(|e| format!("Failed to read response: {e}"))?;
811
812 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
813}
814
815pub fn save_cloud_models(data: &serde_json::Value) -> std::io::Result<()> {
816 let dir = config_dir();
817 std::fs::create_dir_all(&dir)?;
818 let json = serde_json::to_string_pretty(data).map_err(std::io::Error::other)?;
819 std::fs::write(dir.join("cloud_models.json"), json)
820}
821
822pub fn load_cloud_models() -> Option<serde_json::Value> {
823 let path = config_dir().join("cloud_models.json");
824 let data = std::fs::read_to_string(path).ok()?;
825 serde_json::from_str(&data).ok()
826}
827
828pub fn fetch_leaderboard() -> Result<serde_json::Value, String> {
836 let url = format!("{}/api/leaderboard", api_url());
837 let resp = ureq::get(&url)
838 .config()
839 .timeout_global(Some(std::time::Duration::from_secs(10)))
840 .build()
841 .call()
842 .map_err(|e| format!("Could not reach the leaderboard service: {e}"))?;
843 let body = resp
844 .into_body()
845 .read_to_string()
846 .map_err(|e| format!("Failed to read leaderboard response: {e}"))?;
847 serde_json::from_str(&body).map_err(|e| format!("Invalid leaderboard JSON: {e}"))
848}
849
850pub fn is_cloud_user() -> bool {
851 let path = config_dir().join("plan.txt");
852 std::fs::read_to_string(path).is_ok_and(|value| plan_value_has_cloud_access(&value))
853}
854
855fn plan_value_has_cloud_access(value: &str) -> bool {
856 value.trim().eq_ignore_ascii_case("cloud")
857 || crate::core::billing::Plan::parse_known(value)
858 .is_some_and(|plan| plan.rank() >= crate::core::billing::Plan::Pro.rank())
859}
860
861pub const PLAN_GRACE_DAYS: i64 = 14;
865
866fn plan_cache_path() -> PathBuf {
867 config_dir().join("plan.json")
868}
869
870#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
873pub struct PlanCache {
874 pub plan: String,
875 pub verified_at: i64,
877}
878
879pub fn save_plan(plan: &str) -> std::io::Result<()> {
880 let dir = config_dir();
881 std::fs::create_dir_all(&dir)?;
882 std::fs::write(dir.join("plan.txt"), plan)?;
884 let cache = PlanCache {
886 plan: plan.to_string(),
887 verified_at: now_unix(),
888 };
889 let json = serde_json::to_string_pretty(&cache).map_err(std::io::Error::other)?;
890 std::fs::write(plan_cache_path(), json)
891}
892
893pub fn cached_plan() -> Option<PlanCache> {
897 if let Ok(data) = std::fs::read_to_string(plan_cache_path())
898 && let Ok(cache) = serde_json::from_str::<PlanCache>(&data)
899 {
900 return Some(cache);
901 }
902 let legacy = std::fs::read_to_string(config_dir().join("plan.txt")).ok()?;
903 Some(PlanCache {
904 plan: legacy.trim().to_string(),
905 verified_at: 0,
906 })
907}
908
909#[derive(Debug, Clone, Copy, PartialEq, Eq)]
912pub enum PlanSource {
913 Live,
915 Cached,
917 Expired,
919 None,
921}
922
923#[derive(Debug, Clone)]
925pub struct EffectivePlan {
926 pub plan: crate::core::billing::Plan,
927 pub supporter_recognition: bool,
928 pub source: PlanSource,
929 pub verified_at: Option<i64>,
930 pub grace_days: i64,
931}
932
933#[must_use]
936pub fn plan_within_grace(verified_at: i64, now: i64, grace_days: i64) -> (bool, i64) {
937 let age_days = (now - verified_at).max(0) / 86_400;
938 (age_days <= grace_days, age_days)
939}
940
941#[must_use]
950pub fn resolve_effective_plan_cached() -> EffectivePlan {
951 let grace_days = PLAN_GRACE_DAYS;
952 let Some(cache) = cached_plan() else {
953 return EffectivePlan {
954 plan: crate::core::billing::Plan::Community,
955 supporter_recognition: false,
956 source: PlanSource::None,
957 verified_at: None,
958 grace_days,
959 };
960 };
961 let (fresh, _age) = plan_within_grace(cache.verified_at, now_unix(), grace_days);
962 if fresh {
963 let selection = crate::core::billing::Plan::parse_selection(&cache.plan);
964 EffectivePlan {
965 plan: selection.plan,
966 supporter_recognition: selection.supporter_recognition,
967 source: PlanSource::Cached,
968 verified_at: Some(cache.verified_at),
969 grace_days,
970 }
971 } else {
972 EffectivePlan {
975 plan: crate::core::billing::Plan::Community,
976 supporter_recognition: false,
977 source: PlanSource::Expired,
978 verified_at: Some(cache.verified_at),
979 grace_days,
980 }
981 }
982}
983
984#[must_use]
987pub fn signed_entitlement_allows(capability: &str) -> bool {
988 entitlement_cache::resolve_cached().allows(capability)
989}
990
991#[must_use]
993pub fn resolve_verified_plan_cached() -> VerifiedEffectivePlan {
994 entitlement_cache::resolve_cached()
995}
996
997#[must_use]
999pub fn refresh_verified_plan() -> VerifiedEffectivePlan {
1000 entitlement_cache::refresh()
1001}
1002
1003#[cfg(test)]
1004pub(crate) fn install_test_signed_entitlement_paths(
1005 trust: PathBuf,
1006 credentials: PathBuf,
1007 cache: PathBuf,
1008 anchors: Vec<(String, [u8; 32])>,
1009) -> impl Drop {
1010 entitlement_cache::install_test_paths(trust, credentials, cache, anchors)
1011}
1012
1013#[cfg(test)]
1014pub(crate) fn accept_test_signed_entitlement(account: &str, bytes: &[u8]) {
1015 entitlement_cache::accept_test_cache(account, bytes);
1016}
1017
1018#[must_use]
1022pub fn refresh_effective_plan() -> EffectivePlan {
1023 if is_logged_in()
1024 && let Ok(plan_str) = fetch_plan()
1025 {
1026 let _ = save_plan(&plan_str);
1027 let selection = crate::core::billing::Plan::parse_selection(&plan_str);
1028 return EffectivePlan {
1029 plan: selection.plan,
1030 supporter_recognition: selection.supporter_recognition,
1031 source: PlanSource::Live,
1032 verified_at: Some(now_unix()),
1033 grace_days: PLAN_GRACE_DAYS,
1034 };
1035 }
1036 resolve_effective_plan_cached()
1037}
1038
1039pub fn fetch_plan() -> Result<String, String> {
1040 let bearer = auth_bearer_token()?;
1041 let url = format!("{}/api/auth/me", api_url());
1042
1043 let resp = ureq::get(&url)
1044 .header("Authorization", &format!("Bearer {bearer}"))
1045 .call()
1046 .map_err(|e| format!("Failed to check plan: {e}"))?;
1047
1048 let resp_body = resp
1049 .into_body()
1050 .read_to_string()
1051 .map_err(|e| format!("Failed to read response: {e}"))?;
1052
1053 let json: serde_json::Value =
1054 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
1055
1056 Ok(json["plan"].as_str().unwrap_or("community").to_string())
1057}
1058
1059pub fn start_checkout(plan: &str, interval: &str) -> Result<String, String> {
1064 let bearer = auth_bearer_token()?;
1065 let url = format!("{}/api/account/checkout", api_url());
1066 let body = serde_json::json!({ "plan": plan, "interval": interval });
1067
1068 let resp = ureq::post(&url)
1069 .header("Authorization", &format!("Bearer {bearer}"))
1070 .header("Content-Type", "application/json")
1071 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
1072 .map_err(|e| format!("Checkout request failed: {e}"))?;
1073
1074 let resp_body = resp
1075 .into_body()
1076 .read_to_string()
1077 .map_err(|e| format!("Failed to read response: {e}"))?;
1078
1079 let json: serde_json::Value =
1080 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
1081
1082 parse_checkout_url(&json)
1083}
1084
1085fn parse_checkout_url(json: &serde_json::Value) -> Result<String, String> {
1086 let raw = json["url"]
1087 .as_str()
1088 .ok_or_else(|| "Billing did not return a checkout URL.".to_string())?;
1089 if raw.chars().any(char::is_control) {
1092 return Err("Billing returned an invalid checkout URL.".to_string());
1093 }
1094 let parsed = reqwest::Url::parse(raw)
1095 .map_err(|_| "Billing returned an invalid checkout URL.".to_string())?;
1096 if parsed.scheme() != "https"
1097 || parsed.host_str().is_none()
1098 || !parsed.username().is_empty()
1099 || parsed.password().is_some()
1100 {
1101 return Err("Billing returned an invalid checkout URL.".to_string());
1102 }
1103 Ok(parsed.to_string())
1104}
1105
1106pub fn push_commands(entries: &[serde_json::Value]) -> Result<String, String> {
1107 let bearer = auth_bearer_token()?;
1108 let url = format!("{}/api/sync/commands", api_url());
1109 let body = serde_json::json!({ "commands": entries });
1110 let resp = ureq::post(&url)
1111 .header("Authorization", &format!("Bearer {bearer}"))
1112 .header("Content-Type", "application/json")
1113 .header("X-Device-Label", &device_label())
1114 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
1115 .map_err(|e| format!("Push failed: {e}"))?;
1116 let resp_body = resp
1117 .into_body()
1118 .read_to_string()
1119 .map_err(|e| format!("Failed to read response: {e}"))?;
1120 let json: serde_json::Value =
1121 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1122 Ok(format!(
1123 "{} commands synced",
1124 json["synced"].as_i64().unwrap_or(0)
1125 ))
1126}
1127
1128pub fn push_cep(entries: &[serde_json::Value]) -> Result<String, String> {
1129 let bearer = auth_bearer_token()?;
1130 let url = format!("{}/api/sync/cep", api_url());
1131 let body = serde_json::json!({ "scores": entries });
1132 let resp = ureq::post(&url)
1133 .header("Authorization", &format!("Bearer {bearer}"))
1134 .header("Content-Type", "application/json")
1135 .header("X-Device-Label", &device_label())
1136 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
1137 .map_err(|e| format!("Push failed: {e}"))?;
1138 let resp_body = resp
1139 .into_body()
1140 .read_to_string()
1141 .map_err(|e| format!("Failed to read response: {e}"))?;
1142 let json: serde_json::Value =
1143 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1144 Ok(format!(
1145 "{} sessions synced",
1146 json["synced"].as_i64().unwrap_or(0)
1147 ))
1148}
1149
1150pub fn push_gain(entries: &[serde_json::Value]) -> Result<String, String> {
1151 let bearer = auth_bearer_token()?;
1152 let url = format!("{}/api/sync/gain", api_url());
1153 let body = serde_json::json!({ "scores": entries });
1154 let resp = ureq::post(&url)
1155 .header("Authorization", &format!("Bearer {bearer}"))
1156 .header("Content-Type", "application/json")
1157 .header("X-Device-Label", &device_label())
1158 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
1159 .map_err(|e| format!("Push failed: {e}"))?;
1160 let resp_body = resp
1161 .into_body()
1162 .read_to_string()
1163 .map_err(|e| format!("Failed to read response: {e}"))?;
1164 let json: serde_json::Value =
1165 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1166 Ok(format!(
1167 "{} gain scores synced",
1168 json["synced"].as_i64().unwrap_or(0)
1169 ))
1170}
1171
1172pub fn push_gotchas(entries: &[serde_json::Value]) -> Result<String, String> {
1177 let bearer = auth_bearer_token()?;
1178 let key = gotcha_vault_key()?;
1179 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
1180 let url = format!("{}/api/sync/gotchas", api_url());
1181
1182 let resp = ureq::post(&url)
1183 .header("Authorization", &format!("Bearer {bearer}"))
1184 .header("Content-Type", "application/octet-stream")
1185 .header("X-Entry-Count", &entries.len().to_string())
1186 .header("X-Device-Label", &device_label())
1187 .send(blob.as_slice())
1188 .map_err(|e| format!("Push failed: {e}"))?;
1189 let resp_body = resp
1190 .into_body()
1191 .read_to_string()
1192 .map_err(|e| format!("Failed to read response: {e}"))?;
1193 let json: serde_json::Value =
1194 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1195 Ok(format!(
1196 "{} gotchas synced (end-to-end encrypted)",
1197 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
1198 ))
1199}
1200
1201fn gotcha_vault_key() -> Result<[u8; 32], String> {
1204 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
1205 if api_key.trim().is_empty() {
1206 return Err("Not logged in. Run: lean-ctx login".into());
1207 }
1208 Ok(crate::core::knowledge_vault::derive_gotcha_vault_key(
1209 &api_key,
1210 ))
1211}
1212
1213pub fn push_buddy(data: &serde_json::Value) -> Result<String, String> {
1214 let bearer = auth_bearer_token()?;
1215 let url = format!("{}/api/sync/buddy", api_url());
1216 let resp = ureq::post(&url)
1217 .header("Authorization", &format!("Bearer {bearer}"))
1218 .header("Content-Type", "application/json")
1219 .header("X-Device-Label", &device_label())
1220 .send(&serde_json::to_vec(data).map_err(|e| format!("JSON error: {e}"))?)
1221 .map_err(|e| format!("Push failed: {e}"))?;
1222 let resp_body = resp
1223 .into_body()
1224 .read_to_string()
1225 .map_err(|e| format!("Failed to read response: {e}"))?;
1226 let _json: serde_json::Value =
1227 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1228 Ok("Buddy synced".to_string())
1229}
1230
1231pub fn push_feedback(entries: &[serde_json::Value]) -> Result<String, String> {
1232 let bearer = auth_bearer_token()?;
1233 let url = format!("{}/api/sync/feedback", api_url());
1234 let resp = ureq::post(&url)
1235 .header("Authorization", &format!("Bearer {bearer}"))
1236 .header("Content-Type", "application/json")
1237 .header("X-Device-Label", &device_label())
1238 .send(&serde_json::to_vec(entries).map_err(|e| format!("JSON error: {e}"))?)
1239 .map_err(|e| format!("Push failed: {e}"))?;
1240 let resp_body = resp
1241 .into_body()
1242 .read_to_string()
1243 .map_err(|e| format!("Failed to read response: {e}"))?;
1244 let json: serde_json::Value =
1245 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1246 Ok(format!(
1247 "{} thresholds synced",
1248 json["synced"].as_i64().unwrap_or(0)
1249 ))
1250}
1251
1252pub fn account_email() -> Option<String> {
1254 load_credentials().map(|c| c.email)
1255}
1256
1257pub fn fetch_account_cloud() -> Result<serde_json::Value, String> {
1261 let bearer = auth_bearer_token()?;
1262 let url = format!("{}/api/account/cloud", api_url());
1263
1264 let resp = ureq::get(&url)
1265 .header("Authorization", &format!("Bearer {bearer}"))
1266 .call()
1267 .map_err(|e| format!("Status fetch failed: {e}"))?;
1268
1269 let resp_body = resp
1270 .into_body()
1271 .read_to_string()
1272 .map_err(|e| format!("Failed to read response: {e}"))?;
1273
1274 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))
1275}
1276
1277pub fn pull_knowledge() -> Result<Vec<serde_json::Value>, String> {
1280 let bearer = auth_bearer_token()?;
1281 let url = format!("{}/api/sync/knowledge", api_url());
1282
1283 match ureq::get(&url)
1285 .header("Authorization", &format!("Bearer {bearer}"))
1286 .header("Accept", "application/octet-stream")
1287 .call()
1288 {
1289 Ok(resp) => {
1290 let is_blob = resp
1291 .headers()
1292 .get("content-type")
1293 .and_then(|v| v.to_str().ok())
1294 .is_some_and(|v| v.starts_with("application/octet-stream"));
1295 if is_blob {
1296 let mut blob = Vec::new();
1297 use std::io::Read;
1298 resp.into_body()
1299 .into_reader()
1300 .read_to_end(&mut blob)
1301 .map_err(|e| format!("Failed to read vault: {e}"))?;
1302 let key = knowledge_vault_key()?;
1303 return crate::core::knowledge_vault::open(&blob, &key).map_err(|e| e.to_string());
1304 }
1305 let body = resp
1308 .into_body()
1309 .read_to_string()
1310 .map_err(|e| format!("Failed to read response: {e}"))?;
1311 return serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"));
1312 }
1313 Err(ureq::Error::StatusCode(404)) => {}
1315 Err(e) => return Err(format!("Pull failed: {e}")),
1316 }
1317
1318 let resp = ureq::get(&url)
1319 .header("Authorization", &format!("Bearer {bearer}"))
1320 .call()
1321 .map_err(|e| format!("Pull failed: {e}"))?;
1322
1323 let resp_body = resp
1324 .into_body()
1325 .read_to_string()
1326 .map_err(|e| format!("Failed to read response: {e}"))?;
1327
1328 let entries: Vec<serde_json::Value> =
1329 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1330
1331 Ok(entries)
1332}
1333
1334fn index_bundle_key() -> Result<[u8; 32], String> {
1342 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
1343 if api_key.trim().is_empty() {
1344 return Err("Not logged in. Run: lean-ctx login".into());
1345 }
1346 Ok(crate::core::index_bundle::derive_key(&api_key))
1347}
1348
1349pub fn push_index_bundle(project_root: &std::path::Path) -> Result<(String, u64), String> {
1352 let (container, manifest) =
1353 crate::core::index_bundle::pack(project_root).map_err(|e| e.to_string())?;
1354 let blob = crate::core::index_bundle::encrypt(&container, &index_bundle_key()?)
1355 .map_err(|e| e.to_string())?;
1356
1357 let bearer = auth_bearer_token()?;
1358 let url = format!("{}/api/sync/index/{}", api_url(), manifest.project_hash);
1359 let resp = ureq::put(&url)
1360 .header("Authorization", &format!("Bearer {bearer}"))
1361 .header("Content-Type", "application/octet-stream")
1362 .header("X-Device-Label", &device_label())
1363 .send(blob.as_slice())
1364 .map_err(|e| match e {
1365 ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1366 Run: lean-ctx cloud upgrade --plan pro"
1367 .to_string(),
1368 ureq::Error::StatusCode(413) => {
1369 "Quota exceeded — the push was blocked (nothing is billed). \
1370 Free space with `lean-ctx sync index status` / delete, then retry."
1371 .to_string()
1372 }
1373 other => format!("Push failed: {other}"),
1374 })?;
1375
1376 let body = resp
1377 .into_body()
1378 .read_to_string()
1379 .map_err(|e| format!("Failed to read response: {e}"))?;
1380 let _ack: serde_json::Value =
1381 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
1382 Ok((manifest.project_hash, blob.len() as u64))
1383}
1384
1385pub fn pull_index_bundle(
1388 project_root: &std::path::Path,
1389) -> Result<crate::core::index_bundle::BundleManifest, String> {
1390 let project_hash = crate::core::index_namespace::namespace_hash(project_root);
1391 let bearer = auth_bearer_token()?;
1392 let url = format!("{}/api/sync/index/{project_hash}", api_url());
1393
1394 let resp = ureq::get(&url)
1395 .header("Authorization", &format!("Bearer {bearer}"))
1396 .call()
1397 .map_err(|e| match e {
1398 ureq::Error::StatusCode(404) => format!(
1399 "No hosted index for this project yet ({project_hash}). \
1400 Push one from a device with a built index: lean-ctx sync index push"
1401 ),
1402 ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1403 Run: lean-ctx cloud upgrade --plan pro"
1404 .to_string(),
1405 other => format!("Pull failed: {other}"),
1406 })?;
1407
1408 let mut blob = Vec::new();
1409 use std::io::Read;
1410 resp.into_body()
1411 .into_reader()
1412 .read_to_end(&mut blob)
1413 .map_err(|e| format!("Failed to read bundle: {e}"))?;
1414
1415 let container = crate::core::index_bundle::decrypt(&blob, &index_bundle_key()?)
1416 .map_err(|e| e.to_string())?;
1417 crate::core::index_bundle::unpack(project_root, &container).map_err(|e| e.to_string())
1418}
1419
1420pub fn index_bundle_status() -> Result<serde_json::Value, String> {
1422 let bearer = auth_bearer_token()?;
1423 let url = format!("{}/api/sync/index", api_url());
1424 let resp = ureq::get(&url)
1425 .header("Authorization", &format!("Bearer {bearer}"))
1426 .call()
1427 .map_err(|e| format!("Status fetch failed: {e}"))?;
1428 let body = resp
1429 .into_body()
1430 .read_to_string()
1431 .map_err(|e| format!("Failed to read response: {e}"))?;
1432 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))
1433}
1434
1435#[cfg(test)]
1436#[path = "cloud_client/inline_tests.rs"]
1437mod tests;