1use std::path::PathBuf;
2
3fn config_dir() -> PathBuf {
4 crate::core::paths::data_dir()
7 .unwrap_or_else(|_| PathBuf::from("."))
8 .join("cloud")
9}
10
11fn credentials_path() -> PathBuf {
12 config_dir().join("credentials.json")
13}
14
15pub fn api_url() -> String {
16 std::env::var("LEAN_CTX_API_URL").unwrap_or_else(|_| "https://api.leanctx.com".to_string())
17}
18
19#[derive(serde::Serialize, serde::Deserialize)]
20struct Credentials {
21 api_key: String,
22 user_id: String,
23 email: String,
24 #[serde(default)]
25 oauth_client_id: Option<String>,
26 #[serde(default)]
27 oauth_client_secret: Option<String>,
28 #[serde(default)]
29 oauth_access_token: Option<String>,
30 #[serde(default)]
31 oauth_expires_at_unix: Option<i64>,
32}
33
34fn load_credentials() -> Option<Credentials> {
35 let path = credentials_path();
36 tighten_secret_permissions(&path);
39 let data = std::fs::read_to_string(&path).ok()?;
40 serde_json::from_str(&data).ok()
41}
42
43fn write_credentials(creds: &Credentials) -> std::io::Result<()> {
44 let dir = config_dir();
45 std::fs::create_dir_all(&dir)?;
46 restrict_dir_permissions(&dir);
47 let json = serde_json::to_string_pretty(creds).map_err(std::io::Error::other)?;
48 write_secret_file(&credentials_path(), json.as_bytes())
49}
50
51fn write_secret_file(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
55 use std::io::Write;
56
57 let parent = path
58 .parent()
59 .ok_or_else(|| std::io::Error::other("credentials path has no parent directory"))?;
60 let name = path
61 .file_name()
62 .ok_or_else(|| std::io::Error::other("credentials path has no file name"))?
63 .to_string_lossy();
64 let tmp = parent.join(format!(".{name}.tmp.{}", std::process::id()));
65
66 let mut opts = std::fs::OpenOptions::new();
67 opts.write(true).create_new(true);
68 #[cfg(unix)]
69 {
70 use std::os::unix::fs::OpenOptionsExt;
71 opts.mode(0o600);
72 }
73
74 let result = (|| {
75 let mut f = opts.open(&tmp)?;
76 f.write_all(bytes)?;
77 f.sync_all()?;
78 drop(f);
79 #[cfg(windows)]
80 {
81 if path.exists() {
82 std::fs::remove_file(path)?;
83 }
84 }
85 std::fs::rename(&tmp, path)
86 })();
87
88 if result.is_err() {
89 let _ = std::fs::remove_file(&tmp);
90 }
91 result
92}
93
94#[cfg(unix)]
95fn restrict_dir_permissions(dir: &std::path::Path) {
96 use std::os::unix::fs::PermissionsExt;
97 let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
98}
99
100#[cfg(not(unix))]
101fn restrict_dir_permissions(_dir: &std::path::Path) {}
102
103#[cfg(unix)]
104fn tighten_secret_permissions(path: &std::path::Path) {
105 use std::os::unix::fs::PermissionsExt;
106 if let Ok(meta) = std::fs::metadata(path)
107 && meta.permissions().mode() & 0o077 != 0
108 {
109 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
110 }
111}
112
113#[cfg(not(unix))]
114fn tighten_secret_permissions(_path: &std::path::Path) {}
115
116pub fn save_credentials(api_key: &str, user_id: &str, email: &str) -> std::io::Result<()> {
117 let mut creds = load_credentials().unwrap_or(Credentials {
118 api_key: api_key.to_string(),
119 user_id: user_id.to_string(),
120 email: email.to_string(),
121 oauth_client_id: None,
122 oauth_client_secret: None,
123 oauth_access_token: None,
124 oauth_expires_at_unix: None,
125 });
126 creds.api_key = api_key.to_string();
127 creds.user_id = user_id.to_string();
128 creds.email = email.to_string();
129 creds.oauth_access_token = None;
131 creds.oauth_expires_at_unix = None;
132 write_credentials(&creds)
133}
134
135pub fn load_api_key() -> Option<String> {
136 load_credentials().map(|c| c.api_key)
137}
138
139pub fn is_logged_in() -> bool {
140 load_credentials().is_some()
141}
142
143fn now_unix() -> i64 {
144 use std::time::{SystemTime, UNIX_EPOCH};
145 SystemTime::now()
146 .duration_since(UNIX_EPOCH)
147 .unwrap_or_default()
148 .as_secs() as i64
149}
150
151fn device_label() -> String {
159 gethostname::gethostname().to_string_lossy().into_owned()
160}
161
162fn auth_bearer_token() -> Result<String, String> {
163 let mut creds = load_credentials().ok_or("Not logged in. Run: lean-ctx login")?;
164
165 if let (Some(client_id), Some(client_secret)) = (
166 creds.oauth_client_id.clone(),
167 creds.oauth_client_secret.clone(),
168 ) {
169 let now = now_unix();
170 if let (Some(token), Some(exp)) = (
171 creds.oauth_access_token.clone(),
172 creds.oauth_expires_at_unix,
173 ) && exp > now + 10
174 {
175 return Ok(token);
176 }
177
178 let url = format!("{}/oauth/token", api_url());
179 let resp = ureq::post(&url)
180 .header("Content-Type", "application/x-www-form-urlencoded")
181 .send_form([
182 ("grant_type", "client_credentials"),
183 ("client_id", client_id.as_str()),
184 ("client_secret", client_secret.as_str()),
185 ])
186 .map_err(|e| format!("OAuth token request failed: {e}"))?;
187
188 let resp_body = resp
189 .into_body()
190 .read_to_string()
191 .map_err(|e| format!("Failed to read OAuth response: {e}"))?;
192
193 let json: serde_json::Value =
194 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
195
196 let token = json["access_token"]
197 .as_str()
198 .ok_or("Missing access_token in response")?
199 .to_string();
200 let expires_in = json["expires_in"].as_i64().unwrap_or(3600);
201 let exp = now + expires_in.saturating_sub(30);
202
203 creds.oauth_access_token = Some(token.clone());
204 creds.oauth_expires_at_unix = Some(exp);
205 let _ = write_credentials(&creds);
206
207 return Ok(token);
208 }
209
210 Ok(creds.api_key)
211}
212
213pub fn oauth_register_client(client_name: Option<&str>) -> Result<String, String> {
214 let mut creds = load_credentials().ok_or("Not logged in. Run: lean-ctx login")?;
215 if creds.oauth_client_id.is_some() && creds.oauth_client_secret.is_some() {
216 return Ok("OAuth client already registered.".to_string());
217 }
218
219 let url = format!("{}/oauth/register", api_url());
220 let body = if let Some(name) = client_name {
221 serde_json::json!({ "client_name": name })
222 } else {
223 serde_json::json!({})
224 };
225
226 let resp = ureq::post(&url)
227 .header("Authorization", &format!("Bearer {}", creds.api_key))
228 .header("Content-Type", "application/json")
229 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
230 .map_err(|e| format!("OAuth register failed: {e}"))?;
231
232 let resp_body = resp
233 .into_body()
234 .read_to_string()
235 .map_err(|e| format!("Failed to read response: {e}"))?;
236
237 let json: serde_json::Value =
238 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
239
240 creds.oauth_client_id = Some(
241 json["client_id"]
242 .as_str()
243 .ok_or("Missing client_id in response")?
244 .to_string(),
245 );
246 creds.oauth_client_secret = Some(
247 json["client_secret"]
248 .as_str()
249 .ok_or("Missing client_secret in response")?
250 .to_string(),
251 );
252 creds.oauth_access_token = None;
253 creds.oauth_expires_at_unix = None;
254 write_credentials(&creds).map_err(|e| format!("Failed to persist OAuth credentials: {e}"))?;
255
256 Ok("OAuth client registered. Cloud requests will use short-lived access tokens.".to_string())
257}
258
259pub struct RegisterResult {
260 pub api_key: String,
261 pub user_id: String,
262 pub email_verified: bool,
263 pub verification_sent: bool,
264}
265
266pub fn register(email: &str, password: Option<&str>) -> Result<RegisterResult, String> {
267 let url = format!("{}/api/auth/register", api_url());
268 let mut body = serde_json::json!({ "email": email, "device_label": device_label() });
271 if let Some(pw) = password {
272 body["password"] = serde_json::Value::String(pw.to_string());
273 }
274
275 let resp = ureq::post(&url)
276 .header("Content-Type", "application/json")
277 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
278 .map_err(|e| format!("Request failed: {e}"))?;
279
280 let resp_body = resp
281 .into_body()
282 .read_to_string()
283 .map_err(|e| format!("Failed to read response: {e}"))?;
284
285 let json: serde_json::Value =
286 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
287
288 Ok(RegisterResult {
289 api_key: json["api_key"]
290 .as_str()
291 .ok_or("Missing api_key in response")?
292 .to_string(),
293 user_id: json["user_id"]
294 .as_str()
295 .ok_or("Missing user_id in response")?
296 .to_string(),
297 email_verified: json["email_verified"].as_bool().unwrap_or(false),
298 verification_sent: json["verification_sent"].as_bool().unwrap_or(false),
299 })
300}
301
302pub fn forgot_password(email: &str) -> Result<String, String> {
303 let url = format!("{}/api/auth/forgot-password", api_url());
304 let body = serde_json::json!({ "email": email });
305
306 let resp = ureq::post(&url)
307 .header("Content-Type", "application/json")
308 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
309 .map_err(|e| format!("Request failed: {e}"))?;
310
311 let resp_body = resp
312 .into_body()
313 .read_to_string()
314 .map_err(|e| format!("Failed to read response: {e}"))?;
315
316 let json: serde_json::Value =
317 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
318
319 Ok(json["message"]
320 .as_str()
321 .unwrap_or("If an account exists, a reset email has been sent.")
322 .to_string())
323}
324
325pub fn login(email: &str, password: &str) -> Result<RegisterResult, String> {
326 let url = format!("{}/api/auth/login", api_url());
327 let body = serde_json::json!({
328 "email": email,
329 "password": password,
330 "device_label": device_label(),
331 });
332
333 let resp = ureq::post(&url)
334 .header("Content-Type", "application/json")
335 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
336 .map_err(|e| {
337 let msg = e.to_string();
338 if msg.contains("401") {
339 "Invalid email or password".to_string()
340 } else {
341 format!("Request failed: {e}")
342 }
343 })?;
344
345 let resp_body = resp
346 .into_body()
347 .read_to_string()
348 .map_err(|e| format!("Failed to read response: {e}"))?;
349
350 let json: serde_json::Value =
351 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
352
353 Ok(RegisterResult {
354 api_key: json["api_key"]
355 .as_str()
356 .ok_or("Missing api_key in response")?
357 .to_string(),
358 user_id: json["user_id"]
359 .as_str()
360 .ok_or("Missing user_id in response")?
361 .to_string(),
362 email_verified: json["email_verified"].as_bool().unwrap_or(false),
363 verification_sent: false,
364 })
365}
366
367pub fn sync_stats(stats: &[serde_json::Value]) -> Result<String, String> {
368 let bearer = auth_bearer_token()?;
369 let url = format!("{}/api/stats", api_url());
370
371 let body = serde_json::json!({ "stats": stats });
372
373 let resp = ureq::post(&url)
374 .header("Authorization", &format!("Bearer {bearer}"))
375 .header("Content-Type", "application/json")
376 .header("X-Device-Label", &device_label())
377 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
378 .map_err(|e| format!("Sync failed: {e}"))?;
379
380 let resp_body = resp
381 .into_body()
382 .read_to_string()
383 .map_err(|e| format!("Failed to read response: {e}"))?;
384
385 let json: serde_json::Value =
386 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
387
388 Ok(json["message"].as_str().unwrap_or("Synced").to_string())
389}
390
391pub fn contribute(entries: &[serde_json::Value]) -> Result<String, String> {
392 let url = format!("{}/api/contribute", api_url());
393
394 let body = serde_json::json!({ "entries": entries });
395
396 let resp = ureq::post(&url)
397 .header("Content-Type", "application/json")
398 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
399 .map_err(|e| format!("Contribute failed: {e}"))?;
400
401 let resp_body = resp
402 .into_body()
403 .read_to_string()
404 .map_err(|e| format!("Failed to read response: {e}"))?;
405
406 let json: serde_json::Value =
407 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
408
409 Ok(json["message"]
410 .as_str()
411 .unwrap_or("Contributed")
412 .to_string())
413}
414
415pub fn heartbeat(payload: &serde_json::Value) -> Result<String, String> {
418 let url = format!("{}/api/telemetry/heartbeat", api_url());
419
420 let resp = ureq::post(&url)
421 .header("Content-Type", "application/json")
422 .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
423 .map_err(|e| format!("Heartbeat failed: {e}"))?;
424
425 let resp_body = resp
426 .into_body()
427 .read_to_string()
428 .map_err(|e| format!("Failed to read response: {e}"))?;
429
430 let json: serde_json::Value =
431 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
432
433 Ok(json["message"].as_str().unwrap_or("OK").to_string())
434}
435
436pub fn submit_product_feedback(payload: &serde_json::Value) -> Result<String, String> {
448 let url = format!("{}/api/feedback/product", api_url());
449
450 let resp = ureq::post(&url)
451 .header("Content-Type", "application/json")
452 .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
453 .map_err(|e| format!("Could not send feedback: {e}"))?;
454
455 let body = resp
456 .into_body()
457 .read_to_string()
458 .map_err(|e| format!("Failed to read response: {e}"))?;
459
460 let json: serde_json::Value =
461 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
462
463 Ok(json["message"].as_str().unwrap_or("Thanks").to_string())
464}
465
466#[derive(serde::Deserialize)]
470pub struct PublishedCard {
471 pub id: String,
472 #[serde(default)]
473 pub edit_token: Option<String>,
474 #[serde(default)]
475 pub edit_token_challenge: Option<String>,
476 #[serde(default)]
477 pub challenge_expires_in_secs: Option<i64>,
478 pub url: String,
479 #[serde(skip)]
480 pub account_claimed: bool,
481}
482
483pub fn publish_wrapped(payload: &serde_json::Value) -> Result<PublishedCard, String> {
488 let url = format!("{}/api/wrapped", api_url());
489
490 let mut req = ureq::post(&url).header("Content-Type", "application/json");
491 if let Ok(token) = auth_bearer_token() {
492 req = req.header("Authorization", &format!("Bearer {token}"));
493 }
494 let resp = req
495 .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
496 .map_err(|e| format!("Publish failed: {e}"))?;
497
498 let resp_body = resp
499 .into_body()
500 .read_to_string()
501 .map_err(|e| format!("Failed to read response: {e}"))?;
502
503 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
504}
505
506#[derive(serde::Deserialize)]
507struct RecoveredEditToken {
508 edit_token: String,
509}
510
511pub fn recover_wrapped_edit_token(
514 id: &str,
515 nonce: &str,
516 public_key: &str,
517 signature: &str,
518) -> Result<String, String> {
519 let url = format!("{}/api/wrapped/{id}/edit-token/recover", api_url());
520 let body = serde_json::json!({
521 "nonce": nonce,
522 "public_key": public_key,
523 "signature": signature,
524 });
525 let resp = ureq::post(&url)
526 .header("Content-Type", "application/json")
527 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
528 .map_err(|e| format!("Edit-token recovery failed: {e}"))?;
529 let response = resp
530 .into_body()
531 .read_to_string()
532 .map_err(|e| format!("Failed to read response: {e}"))?;
533 let recovered: RecoveredEditToken =
534 serde_json::from_str(&response).map_err(|e| format!("Invalid recovery response: {e}"))?;
535 if recovered.edit_token.is_empty() {
536 return Err("Invalid recovery response: empty edit token".to_string());
537 }
538 Ok(recovered.edit_token)
539}
540
541pub fn unpublish_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
548 let url = format!("{}/api/wrapped/{id}", api_url());
549
550 match ureq::delete(&url).header("X-Edit-Token", edit_token).call() {
551 Ok(_) | Err(ureq::Error::StatusCode(404 | 410)) => Ok(()),
553 Err(e) => Err(format!("Unpublish failed: {e}")),
554 }
555}
556
557pub fn claim_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
561 let bearer = auth_bearer_token()?;
562 let url = format!("{}/api/wrapped/{id}/claim", api_url());
563
564 ureq::post(&url)
565 .header("Authorization", &format!("Bearer {bearer}"))
566 .header("X-Edit-Token", edit_token)
567 .send_empty()
568 .map_err(|e| format!("Claim failed: {e}"))?;
569 Ok(())
570}
571
572#[derive(serde::Deserialize)]
574pub struct LinkCode {
575 pub code: String,
576 pub expires_in_secs: i64,
577}
578
579pub fn link_wrapped_start(id: &str, edit_token: &str) -> Result<LinkCode, String> {
582 let url = format!("{}/api/wrapped/{id}/link/start", api_url());
583
584 let resp = ureq::post(&url)
585 .header("X-Edit-Token", edit_token)
586 .send_empty()
587 .map_err(|e| format!("Link start failed: {e}"))?;
588 let body = resp
589 .into_body()
590 .read_to_string()
591 .map_err(|e| format!("Failed to read response: {e}"))?;
592 serde_json::from_str(&body).map_err(|e| format!("Invalid response: {e}"))
593}
594
595pub fn link_wrapped_complete(id: &str, edit_token: &str, code: &str) -> Result<(), String> {
599 let url = format!("{}/api/wrapped/{id}/link/complete", api_url());
600 let body = serde_json::json!({ "code": code });
601
602 ureq::post(&url)
603 .header("X-Edit-Token", edit_token)
604 .header("Content-Type", "application/json")
605 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
606 .map_err(|e| match e {
607 ureq::Error::StatusCode(404) => {
608 "code invalid or expired — mint a fresh one with lean-ctx gain --link".to_string()
609 }
610 other => format!("Link failed: {other}"),
611 })?;
612 Ok(())
613}
614
615pub fn push_knowledge(entries: &[serde_json::Value]) -> Result<String, String> {
620 let bearer = auth_bearer_token()?;
621 let key = knowledge_vault_key()?;
622 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
623 let url = format!("{}/api/sync/knowledge", api_url());
624
625 let resp = ureq::post(&url)
626 .header("Authorization", &format!("Bearer {bearer}"))
627 .header("Content-Type", "application/octet-stream")
628 .header("X-Entry-Count", &entries.len().to_string())
629 .header("X-Device-Label", &device_label())
630 .send(blob.as_slice())
631 .map_err(|e| format!("Push failed: {e}"))?;
632
633 let resp_body = resp
634 .into_body()
635 .read_to_string()
636 .map_err(|e| format!("Failed to read response: {e}"))?;
637
638 let json: serde_json::Value =
639 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
640
641 Ok(format!(
642 "{} entries synced (end-to-end encrypted)",
643 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
644 ))
645}
646
647fn knowledge_vault_key() -> Result<[u8; 32], String> {
650 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
651 if api_key.trim().is_empty() {
652 return Err("Not logged in. Run: lean-ctx login".into());
653 }
654 Ok(crate::core::knowledge_vault::derive_vault_key(&api_key))
655}
656
657pub fn pull_cloud_models() -> Result<serde_json::Value, String> {
658 let bearer = auth_bearer_token()?;
659 let url = format!("{}/api/cloud/models", api_url());
660
661 let resp = ureq::get(&url)
662 .header("Authorization", &format!("Bearer {bearer}"))
663 .call()
664 .map_err(|e| {
665 let msg = e.to_string();
666 if msg.contains("403") {
667 "This feature is not available for your account.".to_string()
668 } else {
669 format!("Connection failed. Check your internet connection. ({e})")
670 }
671 })?;
672
673 let resp_body = resp
674 .into_body()
675 .read_to_string()
676 .map_err(|e| format!("Failed to read response: {e}"))?;
677
678 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
679}
680
681pub fn save_cloud_models(data: &serde_json::Value) -> std::io::Result<()> {
682 let dir = config_dir();
683 std::fs::create_dir_all(&dir)?;
684 let json = serde_json::to_string_pretty(data).map_err(std::io::Error::other)?;
685 std::fs::write(dir.join("cloud_models.json"), json)
686}
687
688pub fn load_cloud_models() -> Option<serde_json::Value> {
689 let path = config_dir().join("cloud_models.json");
690 let data = std::fs::read_to_string(path).ok()?;
691 serde_json::from_str(&data).ok()
692}
693
694pub fn fetch_leaderboard() -> Result<serde_json::Value, String> {
702 let url = format!("{}/api/leaderboard", api_url());
703 let resp = ureq::get(&url)
704 .config()
705 .timeout_global(Some(std::time::Duration::from_secs(10)))
706 .build()
707 .call()
708 .map_err(|e| format!("Could not reach the leaderboard service: {e}"))?;
709 let body = resp
710 .into_body()
711 .read_to_string()
712 .map_err(|e| format!("Failed to read leaderboard response: {e}"))?;
713 serde_json::from_str(&body).map_err(|e| format!("Invalid leaderboard JSON: {e}"))
714}
715
716pub fn is_cloud_user() -> bool {
717 let path = config_dir().join("plan.txt");
718 std::fs::read_to_string(path).is_ok_and(|p| matches!(p.trim(), "cloud" | "pro"))
719}
720
721pub const PLAN_GRACE_DAYS: i64 = 14;
725
726fn plan_cache_path() -> PathBuf {
727 config_dir().join("plan.json")
728}
729
730#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
733pub struct PlanCache {
734 pub plan: String,
735 pub verified_at: i64,
737}
738
739pub fn save_plan(plan: &str) -> std::io::Result<()> {
740 let dir = config_dir();
741 std::fs::create_dir_all(&dir)?;
742 std::fs::write(dir.join("plan.txt"), plan)?;
744 let cache = PlanCache {
746 plan: plan.to_string(),
747 verified_at: now_unix(),
748 };
749 let json = serde_json::to_string_pretty(&cache).map_err(std::io::Error::other)?;
750 std::fs::write(plan_cache_path(), json)
751}
752
753pub fn cached_plan() -> Option<PlanCache> {
757 if let Ok(data) = std::fs::read_to_string(plan_cache_path())
758 && let Ok(cache) = serde_json::from_str::<PlanCache>(&data)
759 {
760 return Some(cache);
761 }
762 let legacy = std::fs::read_to_string(config_dir().join("plan.txt")).ok()?;
763 Some(PlanCache {
764 plan: legacy.trim().to_string(),
765 verified_at: 0,
766 })
767}
768
769#[derive(Debug, Clone, Copy, PartialEq, Eq)]
772pub enum PlanSource {
773 Live,
775 Cached,
777 Expired,
779 None,
781}
782
783#[derive(Debug, Clone)]
787pub struct EffectivePlan {
788 pub plan: crate::core::billing::Plan,
789 pub source: PlanSource,
790 pub verified_at: Option<i64>,
791 pub grace_days: i64,
792}
793
794#[must_use]
797pub fn plan_within_grace(verified_at: i64, now: i64, grace_days: i64) -> (bool, i64) {
798 let age_days = (now - verified_at).max(0) / 86_400;
799 (age_days <= grace_days, age_days)
800}
801
802#[must_use]
811pub fn resolve_effective_plan_cached() -> EffectivePlan {
812 let grace_days = PLAN_GRACE_DAYS;
813 let Some(cache) = cached_plan() else {
814 return EffectivePlan {
815 plan: crate::core::billing::Plan::Free,
816 source: PlanSource::None,
817 verified_at: None,
818 grace_days,
819 };
820 };
821 let (fresh, _age) = plan_within_grace(cache.verified_at, now_unix(), grace_days);
822 if fresh {
823 EffectivePlan {
824 plan: crate::core::billing::Plan::parse(&cache.plan),
825 source: PlanSource::Cached,
826 verified_at: Some(cache.verified_at),
827 grace_days,
828 }
829 } else {
830 EffectivePlan {
833 plan: crate::core::billing::Plan::Free,
834 source: PlanSource::Expired,
835 verified_at: Some(cache.verified_at),
836 grace_days,
837 }
838 }
839}
840
841#[must_use]
845pub fn refresh_effective_plan() -> EffectivePlan {
846 if is_logged_in()
847 && let Ok(plan_str) = fetch_plan()
848 {
849 let _ = save_plan(&plan_str);
850 return EffectivePlan {
851 plan: crate::core::billing::Plan::parse(&plan_str),
852 source: PlanSource::Live,
853 verified_at: Some(now_unix()),
854 grace_days: PLAN_GRACE_DAYS,
855 };
856 }
857 resolve_effective_plan_cached()
858}
859
860pub fn fetch_plan() -> Result<String, String> {
861 let bearer = auth_bearer_token()?;
862 let url = format!("{}/api/auth/me", api_url());
863
864 let resp = ureq::get(&url)
865 .header("Authorization", &format!("Bearer {bearer}"))
866 .call()
867 .map_err(|e| format!("Failed to check plan: {e}"))?;
868
869 let resp_body = resp
870 .into_body()
871 .read_to_string()
872 .map_err(|e| format!("Failed to read response: {e}"))?;
873
874 let json: serde_json::Value =
875 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
876
877 Ok(json["plan"].as_str().unwrap_or("free").to_string())
878}
879
880pub fn start_checkout(plan: &str, interval: &str) -> Result<String, String> {
885 let bearer = auth_bearer_token()?;
886 let url = format!("{}/api/account/checkout", api_url());
887 let body = serde_json::json!({ "plan": plan, "interval": interval });
888
889 let resp = ureq::post(&url)
890 .header("Authorization", &format!("Bearer {bearer}"))
891 .header("Content-Type", "application/json")
892 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
893 .map_err(|e| format!("Checkout request failed: {e}"))?;
894
895 let resp_body = resp
896 .into_body()
897 .read_to_string()
898 .map_err(|e| format!("Failed to read response: {e}"))?;
899
900 let json: serde_json::Value =
901 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
902
903 json["url"]
904 .as_str()
905 .map(str::to_string)
906 .ok_or_else(|| "Billing did not return a checkout URL.".to_string())
907}
908
909pub fn push_commands(entries: &[serde_json::Value]) -> Result<String, String> {
910 let bearer = auth_bearer_token()?;
911 let url = format!("{}/api/sync/commands", api_url());
912 let body = serde_json::json!({ "commands": entries });
913 let resp = ureq::post(&url)
914 .header("Authorization", &format!("Bearer {bearer}"))
915 .header("Content-Type", "application/json")
916 .header("X-Device-Label", &device_label())
917 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
918 .map_err(|e| format!("Push failed: {e}"))?;
919 let resp_body = resp
920 .into_body()
921 .read_to_string()
922 .map_err(|e| format!("Failed to read response: {e}"))?;
923 let json: serde_json::Value =
924 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
925 Ok(format!(
926 "{} commands synced",
927 json["synced"].as_i64().unwrap_or(0)
928 ))
929}
930
931pub fn push_cep(entries: &[serde_json::Value]) -> Result<String, String> {
932 let bearer = auth_bearer_token()?;
933 let url = format!("{}/api/sync/cep", api_url());
934 let body = serde_json::json!({ "scores": entries });
935 let resp = ureq::post(&url)
936 .header("Authorization", &format!("Bearer {bearer}"))
937 .header("Content-Type", "application/json")
938 .header("X-Device-Label", &device_label())
939 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
940 .map_err(|e| format!("Push failed: {e}"))?;
941 let resp_body = resp
942 .into_body()
943 .read_to_string()
944 .map_err(|e| format!("Failed to read response: {e}"))?;
945 let json: serde_json::Value =
946 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
947 Ok(format!(
948 "{} sessions synced",
949 json["synced"].as_i64().unwrap_or(0)
950 ))
951}
952
953pub fn push_gain(entries: &[serde_json::Value]) -> Result<String, String> {
954 let bearer = auth_bearer_token()?;
955 let url = format!("{}/api/sync/gain", api_url());
956 let body = serde_json::json!({ "scores": entries });
957 let resp = ureq::post(&url)
958 .header("Authorization", &format!("Bearer {bearer}"))
959 .header("Content-Type", "application/json")
960 .header("X-Device-Label", &device_label())
961 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
962 .map_err(|e| format!("Push failed: {e}"))?;
963 let resp_body = resp
964 .into_body()
965 .read_to_string()
966 .map_err(|e| format!("Failed to read response: {e}"))?;
967 let json: serde_json::Value =
968 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
969 Ok(format!(
970 "{} gain scores synced",
971 json["synced"].as_i64().unwrap_or(0)
972 ))
973}
974
975pub fn push_gotchas(entries: &[serde_json::Value]) -> Result<String, String> {
980 let bearer = auth_bearer_token()?;
981 let key = gotcha_vault_key()?;
982 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
983 let url = format!("{}/api/sync/gotchas", api_url());
984
985 let resp = ureq::post(&url)
986 .header("Authorization", &format!("Bearer {bearer}"))
987 .header("Content-Type", "application/octet-stream")
988 .header("X-Entry-Count", &entries.len().to_string())
989 .header("X-Device-Label", &device_label())
990 .send(blob.as_slice())
991 .map_err(|e| format!("Push failed: {e}"))?;
992 let resp_body = resp
993 .into_body()
994 .read_to_string()
995 .map_err(|e| format!("Failed to read response: {e}"))?;
996 let json: serde_json::Value =
997 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
998 Ok(format!(
999 "{} gotchas synced (end-to-end encrypted)",
1000 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
1001 ))
1002}
1003
1004fn gotcha_vault_key() -> Result<[u8; 32], String> {
1007 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
1008 if api_key.trim().is_empty() {
1009 return Err("Not logged in. Run: lean-ctx login".into());
1010 }
1011 Ok(crate::core::knowledge_vault::derive_gotcha_vault_key(
1012 &api_key,
1013 ))
1014}
1015
1016pub fn push_buddy(data: &serde_json::Value) -> Result<String, String> {
1017 let bearer = auth_bearer_token()?;
1018 let url = format!("{}/api/sync/buddy", api_url());
1019 let resp = ureq::post(&url)
1020 .header("Authorization", &format!("Bearer {bearer}"))
1021 .header("Content-Type", "application/json")
1022 .header("X-Device-Label", &device_label())
1023 .send(&serde_json::to_vec(data).map_err(|e| format!("JSON error: {e}"))?)
1024 .map_err(|e| format!("Push failed: {e}"))?;
1025 let resp_body = resp
1026 .into_body()
1027 .read_to_string()
1028 .map_err(|e| format!("Failed to read response: {e}"))?;
1029 let _json: serde_json::Value =
1030 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1031 Ok("Buddy synced".to_string())
1032}
1033
1034pub fn push_feedback(entries: &[serde_json::Value]) -> Result<String, String> {
1035 let bearer = auth_bearer_token()?;
1036 let url = format!("{}/api/sync/feedback", api_url());
1037 let resp = ureq::post(&url)
1038 .header("Authorization", &format!("Bearer {bearer}"))
1039 .header("Content-Type", "application/json")
1040 .header("X-Device-Label", &device_label())
1041 .send(&serde_json::to_vec(entries).map_err(|e| format!("JSON error: {e}"))?)
1042 .map_err(|e| format!("Push failed: {e}"))?;
1043 let resp_body = resp
1044 .into_body()
1045 .read_to_string()
1046 .map_err(|e| format!("Failed to read response: {e}"))?;
1047 let json: serde_json::Value =
1048 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1049 Ok(format!(
1050 "{} thresholds synced",
1051 json["synced"].as_i64().unwrap_or(0)
1052 ))
1053}
1054
1055pub fn account_email() -> Option<String> {
1057 load_credentials().map(|c| c.email)
1058}
1059
1060pub fn fetch_account_cloud() -> Result<serde_json::Value, String> {
1064 let bearer = auth_bearer_token()?;
1065 let url = format!("{}/api/account/cloud", api_url());
1066
1067 let resp = ureq::get(&url)
1068 .header("Authorization", &format!("Bearer {bearer}"))
1069 .call()
1070 .map_err(|e| format!("Status fetch failed: {e}"))?;
1071
1072 let resp_body = resp
1073 .into_body()
1074 .read_to_string()
1075 .map_err(|e| format!("Failed to read response: {e}"))?;
1076
1077 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))
1078}
1079
1080pub fn pull_knowledge() -> Result<Vec<serde_json::Value>, String> {
1083 let bearer = auth_bearer_token()?;
1084 let url = format!("{}/api/sync/knowledge", api_url());
1085
1086 match ureq::get(&url)
1088 .header("Authorization", &format!("Bearer {bearer}"))
1089 .header("Accept", "application/octet-stream")
1090 .call()
1091 {
1092 Ok(resp) => {
1093 let is_blob = resp
1094 .headers()
1095 .get("content-type")
1096 .and_then(|v| v.to_str().ok())
1097 .is_some_and(|v| v.starts_with("application/octet-stream"));
1098 if is_blob {
1099 let mut blob = Vec::new();
1100 use std::io::Read;
1101 resp.into_body()
1102 .into_reader()
1103 .read_to_end(&mut blob)
1104 .map_err(|e| format!("Failed to read vault: {e}"))?;
1105 let key = knowledge_vault_key()?;
1106 return crate::core::knowledge_vault::open(&blob, &key).map_err(|e| e.to_string());
1107 }
1108 let body = resp
1111 .into_body()
1112 .read_to_string()
1113 .map_err(|e| format!("Failed to read response: {e}"))?;
1114 return serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"));
1115 }
1116 Err(ureq::Error::StatusCode(404)) => {}
1118 Err(e) => return Err(format!("Pull failed: {e}")),
1119 }
1120
1121 let resp = ureq::get(&url)
1122 .header("Authorization", &format!("Bearer {bearer}"))
1123 .call()
1124 .map_err(|e| format!("Pull failed: {e}"))?;
1125
1126 let resp_body = resp
1127 .into_body()
1128 .read_to_string()
1129 .map_err(|e| format!("Failed to read response: {e}"))?;
1130
1131 let entries: Vec<serde_json::Value> =
1132 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1133
1134 Ok(entries)
1135}
1136
1137fn index_bundle_key() -> Result<[u8; 32], String> {
1145 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
1146 if api_key.trim().is_empty() {
1147 return Err("Not logged in. Run: lean-ctx login".into());
1148 }
1149 Ok(crate::core::index_bundle::derive_key(&api_key))
1150}
1151
1152pub fn push_index_bundle(project_root: &std::path::Path) -> Result<(String, u64), String> {
1155 let (container, manifest) =
1156 crate::core::index_bundle::pack(project_root).map_err(|e| e.to_string())?;
1157 let blob = crate::core::index_bundle::encrypt(&container, &index_bundle_key()?)
1158 .map_err(|e| e.to_string())?;
1159
1160 let bearer = auth_bearer_token()?;
1161 let url = format!("{}/api/sync/index/{}", api_url(), manifest.project_hash);
1162 let resp = ureq::put(&url)
1163 .header("Authorization", &format!("Bearer {bearer}"))
1164 .header("Content-Type", "application/octet-stream")
1165 .header("X-Device-Label", &device_label())
1166 .send(blob.as_slice())
1167 .map_err(|e| match e {
1168 ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1169 Run: lean-ctx cloud upgrade --plan pro"
1170 .to_string(),
1171 ureq::Error::StatusCode(413) => {
1172 "Quota exceeded — the push was blocked (nothing is billed). \
1173 Free space with `lean-ctx sync index status` / delete, then retry."
1174 .to_string()
1175 }
1176 other => format!("Push failed: {other}"),
1177 })?;
1178
1179 let body = resp
1180 .into_body()
1181 .read_to_string()
1182 .map_err(|e| format!("Failed to read response: {e}"))?;
1183 let _ack: serde_json::Value =
1184 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
1185 Ok((manifest.project_hash, blob.len() as u64))
1186}
1187
1188pub fn pull_index_bundle(
1191 project_root: &std::path::Path,
1192) -> Result<crate::core::index_bundle::BundleManifest, String> {
1193 let project_hash = crate::core::index_namespace::namespace_hash(project_root);
1194 let bearer = auth_bearer_token()?;
1195 let url = format!("{}/api/sync/index/{project_hash}", api_url());
1196
1197 let resp = ureq::get(&url)
1198 .header("Authorization", &format!("Bearer {bearer}"))
1199 .call()
1200 .map_err(|e| match e {
1201 ureq::Error::StatusCode(404) => format!(
1202 "No hosted index for this project yet ({project_hash}). \
1203 Push one from a device with a built index: lean-ctx sync index push"
1204 ),
1205 ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1206 Run: lean-ctx cloud upgrade --plan pro"
1207 .to_string(),
1208 other => format!("Pull failed: {other}"),
1209 })?;
1210
1211 let mut blob = Vec::new();
1212 use std::io::Read;
1213 resp.into_body()
1214 .into_reader()
1215 .read_to_end(&mut blob)
1216 .map_err(|e| format!("Failed to read bundle: {e}"))?;
1217
1218 let container = crate::core::index_bundle::decrypt(&blob, &index_bundle_key()?)
1219 .map_err(|e| e.to_string())?;
1220 crate::core::index_bundle::unpack(project_root, &container).map_err(|e| e.to_string())
1221}
1222
1223pub fn index_bundle_status() -> Result<serde_json::Value, String> {
1225 let bearer = auth_bearer_token()?;
1226 let url = format!("{}/api/sync/index", api_url());
1227 let resp = ureq::get(&url)
1228 .header("Authorization", &format!("Bearer {bearer}"))
1229 .call()
1230 .map_err(|e| format!("Status fetch failed: {e}"))?;
1231 let body = resp
1232 .into_body()
1233 .read_to_string()
1234 .map_err(|e| format!("Failed to read response: {e}"))?;
1235 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))
1236}
1237
1238#[cfg(test)]
1239mod tests {
1240 use super::*;
1241 use crate::core::billing::Plan;
1242 #[cfg(unix)]
1246 use crate::core::data_dir::test_env_lock;
1247
1248 #[test]
1249 fn existing_card_publish_response_carries_recovery_challenge() {
1250 let card: PublishedCard = serde_json::from_value(serde_json::json!({
1251 "id": "card-1",
1252 "url": "https://leanctx.com/w/card-1",
1253 "edit_token_challenge": "nonce-1",
1254 "challenge_expires_in_secs": 300
1255 }))
1256 .unwrap();
1257 assert!(card.edit_token.is_none());
1258 assert_eq!(card.edit_token_challenge.as_deref(), Some("nonce-1"));
1259 assert_eq!(card.challenge_expires_in_secs, Some(300));
1260 assert!(!card.account_claimed);
1261 }
1262
1263 #[test]
1264 fn grace_window_boundaries_are_inclusive_and_skew_safe() {
1265 let now = 1_000_000_000;
1266 let day = 86_400;
1267 assert_eq!(plan_within_grace(now, now, 14), (true, 0));
1268 assert_eq!(plan_within_grace(now - 14 * day, now, 14), (true, 14));
1270 assert_eq!(plan_within_grace(now - 15 * day, now, 14), (false, 15));
1272 assert_eq!(plan_within_grace(now + day, now, 14), (true, 0));
1274 }
1275
1276 #[test]
1277 fn plan_cache_roundtrips_through_json() {
1278 let c = PlanCache {
1279 plan: "pro".into(),
1280 verified_at: 42,
1281 };
1282 let back: PlanCache = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
1283 assert_eq!(back.plan, "pro");
1284 assert_eq!(back.verified_at, 42);
1285 }
1286
1287 #[test]
1288 fn cached_resolve_grants_within_grace_then_expires_to_free() {
1289 let _iso = crate::core::data_dir::isolated_data_dir();
1292
1293 save_plan("pro").unwrap();
1295 let eff = resolve_effective_plan_cached();
1296 assert_eq!(eff.plan, Plan::Pro);
1297 assert_eq!(eff.source, PlanSource::Cached);
1298
1299 let stale = PlanCache {
1301 plan: "pro".into(),
1302 verified_at: now_unix() - (PLAN_GRACE_DAYS + 1) * 86_400,
1303 };
1304 std::fs::write(plan_cache_path(), serde_json::to_string(&stale).unwrap()).unwrap();
1305 let eff = resolve_effective_plan_cached();
1306 assert_eq!(eff.plan, Plan::Free);
1307 assert_eq!(eff.source, PlanSource::Expired);
1308 }
1309
1310 #[test]
1311 fn no_cache_resolves_to_free_none() {
1312 let _iso = crate::core::data_dir::isolated_data_dir();
1313 let eff = resolve_effective_plan_cached();
1314 assert_eq!(eff.plan, Plan::Free);
1315 assert_eq!(eff.source, PlanSource::None);
1316 }
1317
1318 #[cfg(unix)]
1320 #[test]
1321 fn credentials_are_written_owner_only_and_atomic() {
1322 use std::os::unix::fs::PermissionsExt;
1323 let _env = test_env_lock();
1324 let tmp = tempfile::tempdir().unwrap();
1325 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1326
1327 save_credentials("sk-test-key", "user-1", "a@b.c").unwrap();
1328
1329 let path = credentials_path();
1330 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1331 assert_eq!(mode & 0o777, 0o600, "credentials.json must be 0o600");
1332
1333 let dir_mode = std::fs::metadata(config_dir())
1334 .unwrap()
1335 .permissions()
1336 .mode();
1337 assert_eq!(
1338 dir_mode & 0o077,
1339 0,
1340 "cloud dir must not be group/world accessible"
1341 );
1342
1343 let leftovers: Vec<_> = std::fs::read_dir(config_dir())
1345 .unwrap()
1346 .filter_map(Result::ok)
1347 .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
1348 .collect();
1349 assert!(leftovers.is_empty(), "atomic write must not leak tmp files");
1350
1351 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1352 }
1353
1354 #[cfg(unix)]
1356 #[test]
1357 fn loose_credential_permissions_are_tightened_on_load() {
1358 use std::os::unix::fs::PermissionsExt;
1359 let _env = test_env_lock();
1360 let tmp = tempfile::tempdir().unwrap();
1361 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1362
1363 std::fs::create_dir_all(config_dir()).unwrap();
1364 let path = credentials_path();
1365 std::fs::write(&path, "{}").unwrap();
1366 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
1367
1368 let _ = load_credentials();
1369
1370 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1371 assert_eq!(
1372 mode & 0o777,
1373 0o600,
1374 "legacy file must be tightened to 0o600"
1375 );
1376
1377 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1378 }
1379
1380 #[test]
1381 fn legacy_plan_txt_is_migrated_but_treated_as_stale() {
1382 let _iso = crate::core::data_dir::isolated_data_dir();
1383 std::fs::create_dir_all(config_dir()).unwrap();
1385 std::fs::write(config_dir().join("plan.txt"), "team").unwrap();
1386 let cache = cached_plan().unwrap();
1387 assert_eq!(cache.plan, "team");
1388 assert_eq!(cache.verified_at, 0);
1389 assert_eq!(resolve_effective_plan_cached().source, PlanSource::Expired);
1390 }
1391}