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 {
156 gethostname::gethostname().to_string_lossy().into_owned()
157}
158
159fn auth_bearer_token() -> Result<String, String> {
160 let mut creds = load_credentials().ok_or("Not logged in. Run: lean-ctx login")?;
161
162 if let (Some(client_id), Some(client_secret)) = (
163 creds.oauth_client_id.clone(),
164 creds.oauth_client_secret.clone(),
165 ) {
166 let now = now_unix();
167 if let (Some(token), Some(exp)) = (
168 creds.oauth_access_token.clone(),
169 creds.oauth_expires_at_unix,
170 ) && exp > now + 10
171 {
172 return Ok(token);
173 }
174
175 let url = format!("{}/oauth/token", api_url());
176 let resp = ureq::post(&url)
177 .header("Content-Type", "application/x-www-form-urlencoded")
178 .send_form([
179 ("grant_type", "client_credentials"),
180 ("client_id", client_id.as_str()),
181 ("client_secret", client_secret.as_str()),
182 ])
183 .map_err(|e| format!("OAuth token request failed: {e}"))?;
184
185 let resp_body = resp
186 .into_body()
187 .read_to_string()
188 .map_err(|e| format!("Failed to read OAuth response: {e}"))?;
189
190 let json: serde_json::Value =
191 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
192
193 let token = json["access_token"]
194 .as_str()
195 .ok_or("Missing access_token in response")?
196 .to_string();
197 let expires_in = json["expires_in"].as_i64().unwrap_or(3600);
198 let exp = now + expires_in.saturating_sub(30);
199
200 creds.oauth_access_token = Some(token.clone());
201 creds.oauth_expires_at_unix = Some(exp);
202 let _ = write_credentials(&creds);
203
204 return Ok(token);
205 }
206
207 Ok(creds.api_key)
208}
209
210pub fn oauth_register_client(client_name: Option<&str>) -> Result<String, String> {
211 let mut creds = load_credentials().ok_or("Not logged in. Run: lean-ctx login")?;
212 if creds.oauth_client_id.is_some() && creds.oauth_client_secret.is_some() {
213 return Ok("OAuth client already registered.".to_string());
214 }
215
216 let url = format!("{}/oauth/register", api_url());
217 let body = if let Some(name) = client_name {
218 serde_json::json!({ "client_name": name })
219 } else {
220 serde_json::json!({})
221 };
222
223 let resp = ureq::post(&url)
224 .header("Authorization", &format!("Bearer {}", creds.api_key))
225 .header("Content-Type", "application/json")
226 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
227 .map_err(|e| format!("OAuth register failed: {e}"))?;
228
229 let resp_body = resp
230 .into_body()
231 .read_to_string()
232 .map_err(|e| format!("Failed to read response: {e}"))?;
233
234 let json: serde_json::Value =
235 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
236
237 creds.oauth_client_id = Some(
238 json["client_id"]
239 .as_str()
240 .ok_or("Missing client_id in response")?
241 .to_string(),
242 );
243 creds.oauth_client_secret = Some(
244 json["client_secret"]
245 .as_str()
246 .ok_or("Missing client_secret in response")?
247 .to_string(),
248 );
249 creds.oauth_access_token = None;
250 creds.oauth_expires_at_unix = None;
251 write_credentials(&creds).map_err(|e| format!("Failed to persist OAuth credentials: {e}"))?;
252
253 Ok("OAuth client registered. Cloud requests will use short-lived access tokens.".to_string())
254}
255
256pub struct RegisterResult {
257 pub api_key: String,
258 pub user_id: String,
259 pub email_verified: bool,
260 pub verification_sent: bool,
261}
262
263pub fn register(email: &str, password: Option<&str>) -> Result<RegisterResult, String> {
264 let url = format!("{}/api/auth/register", api_url());
265 let mut body = serde_json::json!({ "email": email });
266 if let Some(pw) = password {
267 body["password"] = serde_json::Value::String(pw.to_string());
268 }
269
270 let resp = ureq::post(&url)
271 .header("Content-Type", "application/json")
272 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
273 .map_err(|e| format!("Request failed: {e}"))?;
274
275 let resp_body = resp
276 .into_body()
277 .read_to_string()
278 .map_err(|e| format!("Failed to read response: {e}"))?;
279
280 let json: serde_json::Value =
281 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
282
283 Ok(RegisterResult {
284 api_key: json["api_key"]
285 .as_str()
286 .ok_or("Missing api_key in response")?
287 .to_string(),
288 user_id: json["user_id"]
289 .as_str()
290 .ok_or("Missing user_id in response")?
291 .to_string(),
292 email_verified: json["email_verified"].as_bool().unwrap_or(false),
293 verification_sent: json["verification_sent"].as_bool().unwrap_or(false),
294 })
295}
296
297pub fn forgot_password(email: &str) -> Result<String, String> {
298 let url = format!("{}/api/auth/forgot-password", api_url());
299 let body = serde_json::json!({ "email": email });
300
301 let resp = ureq::post(&url)
302 .header("Content-Type", "application/json")
303 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
304 .map_err(|e| format!("Request failed: {e}"))?;
305
306 let resp_body = resp
307 .into_body()
308 .read_to_string()
309 .map_err(|e| format!("Failed to read response: {e}"))?;
310
311 let json: serde_json::Value =
312 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
313
314 Ok(json["message"]
315 .as_str()
316 .unwrap_or("If an account exists, a reset email has been sent.")
317 .to_string())
318}
319
320pub fn login(email: &str, password: &str) -> Result<RegisterResult, String> {
321 let url = format!("{}/api/auth/login", api_url());
322 let body = serde_json::json!({ "email": email, "password": password });
323
324 let resp = ureq::post(&url)
325 .header("Content-Type", "application/json")
326 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
327 .map_err(|e| {
328 let msg = e.to_string();
329 if msg.contains("401") {
330 "Invalid email or password".to_string()
331 } else {
332 format!("Request failed: {e}")
333 }
334 })?;
335
336 let resp_body = resp
337 .into_body()
338 .read_to_string()
339 .map_err(|e| format!("Failed to read response: {e}"))?;
340
341 let json: serde_json::Value =
342 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
343
344 Ok(RegisterResult {
345 api_key: json["api_key"]
346 .as_str()
347 .ok_or("Missing api_key in response")?
348 .to_string(),
349 user_id: json["user_id"]
350 .as_str()
351 .ok_or("Missing user_id in response")?
352 .to_string(),
353 email_verified: json["email_verified"].as_bool().unwrap_or(false),
354 verification_sent: false,
355 })
356}
357
358pub fn sync_stats(stats: &[serde_json::Value]) -> Result<String, String> {
359 let bearer = auth_bearer_token()?;
360 let url = format!("{}/api/stats", api_url());
361
362 let body = serde_json::json!({ "stats": stats });
363
364 let resp = ureq::post(&url)
365 .header("Authorization", &format!("Bearer {bearer}"))
366 .header("Content-Type", "application/json")
367 .header("X-Device-Label", &device_label())
368 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
369 .map_err(|e| format!("Sync failed: {e}"))?;
370
371 let resp_body = resp
372 .into_body()
373 .read_to_string()
374 .map_err(|e| format!("Failed to read response: {e}"))?;
375
376 let json: serde_json::Value =
377 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
378
379 Ok(json["message"].as_str().unwrap_or("Synced").to_string())
380}
381
382pub fn contribute(entries: &[serde_json::Value]) -> Result<String, String> {
383 let url = format!("{}/api/contribute", api_url());
384
385 let body = serde_json::json!({ "entries": entries });
386
387 let resp = ureq::post(&url)
388 .header("Content-Type", "application/json")
389 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
390 .map_err(|e| format!("Contribute failed: {e}"))?;
391
392 let resp_body = resp
393 .into_body()
394 .read_to_string()
395 .map_err(|e| format!("Failed to read response: {e}"))?;
396
397 let json: serde_json::Value =
398 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
399
400 Ok(json["message"]
401 .as_str()
402 .unwrap_or("Contributed")
403 .to_string())
404}
405
406#[derive(serde::Deserialize)]
410pub struct PublishedCard {
411 pub id: String,
412 #[serde(default)]
413 pub edit_token: Option<String>,
414 #[serde(default)]
415 pub edit_token_challenge: Option<String>,
416 #[serde(default)]
417 pub challenge_expires_in_secs: Option<i64>,
418 pub url: String,
419 #[serde(skip)]
420 pub account_claimed: bool,
421}
422
423pub fn publish_wrapped(payload: &serde_json::Value) -> Result<PublishedCard, String> {
427 let url = format!("{}/api/wrapped", api_url());
428
429 let resp = ureq::post(&url)
430 .header("Content-Type", "application/json")
431 .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
432 .map_err(|e| format!("Publish failed: {e}"))?;
433
434 let resp_body = resp
435 .into_body()
436 .read_to_string()
437 .map_err(|e| format!("Failed to read response: {e}"))?;
438
439 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
440}
441
442#[derive(serde::Deserialize)]
443struct RecoveredEditToken {
444 edit_token: String,
445}
446
447pub fn recover_wrapped_edit_token(
450 id: &str,
451 nonce: &str,
452 public_key: &str,
453 signature: &str,
454) -> Result<String, String> {
455 let url = format!("{}/api/wrapped/{id}/edit-token/recover", api_url());
456 let body = serde_json::json!({
457 "nonce": nonce,
458 "public_key": public_key,
459 "signature": signature,
460 });
461 let resp = ureq::post(&url)
462 .header("Content-Type", "application/json")
463 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
464 .map_err(|e| format!("Edit-token recovery failed: {e}"))?;
465 let response = resp
466 .into_body()
467 .read_to_string()
468 .map_err(|e| format!("Failed to read response: {e}"))?;
469 let recovered: RecoveredEditToken =
470 serde_json::from_str(&response).map_err(|e| format!("Invalid recovery response: {e}"))?;
471 if recovered.edit_token.is_empty() {
472 return Err("Invalid recovery response: empty edit token".to_string());
473 }
474 Ok(recovered.edit_token)
475}
476
477pub fn unpublish_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
479 let url = format!("{}/api/wrapped/{id}", api_url());
480
481 ureq::delete(&url)
482 .header("X-Edit-Token", edit_token)
483 .call()
484 .map_err(|e| format!("Unpublish failed: {e}"))?;
485 Ok(())
486}
487
488pub fn claim_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
492 let bearer = auth_bearer_token()?;
493 let url = format!("{}/api/wrapped/{id}/claim", api_url());
494
495 ureq::post(&url)
496 .header("Authorization", &format!("Bearer {bearer}"))
497 .header("X-Edit-Token", edit_token)
498 .send_empty()
499 .map_err(|e| format!("Claim failed: {e}"))?;
500 Ok(())
501}
502
503#[derive(serde::Deserialize)]
505pub struct LinkCode {
506 pub code: String,
507 pub expires_in_secs: i64,
508}
509
510pub fn link_wrapped_start(id: &str, edit_token: &str) -> Result<LinkCode, String> {
513 let url = format!("{}/api/wrapped/{id}/link/start", api_url());
514
515 let resp = ureq::post(&url)
516 .header("X-Edit-Token", edit_token)
517 .send_empty()
518 .map_err(|e| format!("Link start failed: {e}"))?;
519 let body = resp
520 .into_body()
521 .read_to_string()
522 .map_err(|e| format!("Failed to read response: {e}"))?;
523 serde_json::from_str(&body).map_err(|e| format!("Invalid response: {e}"))
524}
525
526pub fn link_wrapped_complete(id: &str, edit_token: &str, code: &str) -> Result<(), String> {
530 let url = format!("{}/api/wrapped/{id}/link/complete", api_url());
531 let body = serde_json::json!({ "code": code });
532
533 ureq::post(&url)
534 .header("X-Edit-Token", edit_token)
535 .header("Content-Type", "application/json")
536 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
537 .map_err(|e| match e {
538 ureq::Error::StatusCode(404) => {
539 "code invalid or expired — mint a fresh one with lean-ctx gain --link".to_string()
540 }
541 other => format!("Link failed: {other}"),
542 })?;
543 Ok(())
544}
545
546pub fn push_knowledge(entries: &[serde_json::Value]) -> Result<String, String> {
551 let bearer = auth_bearer_token()?;
552 let key = knowledge_vault_key()?;
553 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
554 let url = format!("{}/api/sync/knowledge", api_url());
555
556 let resp = ureq::post(&url)
557 .header("Authorization", &format!("Bearer {bearer}"))
558 .header("Content-Type", "application/octet-stream")
559 .header("X-Entry-Count", &entries.len().to_string())
560 .header("X-Device-Label", &device_label())
561 .send(blob.as_slice())
562 .map_err(|e| format!("Push failed: {e}"))?;
563
564 let resp_body = resp
565 .into_body()
566 .read_to_string()
567 .map_err(|e| format!("Failed to read response: {e}"))?;
568
569 let json: serde_json::Value =
570 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
571
572 Ok(format!(
573 "{} entries synced (end-to-end encrypted)",
574 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
575 ))
576}
577
578fn knowledge_vault_key() -> Result<[u8; 32], String> {
581 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
582 if api_key.trim().is_empty() {
583 return Err("Not logged in. Run: lean-ctx login".into());
584 }
585 Ok(crate::core::knowledge_vault::derive_vault_key(&api_key))
586}
587
588pub fn pull_cloud_models() -> Result<serde_json::Value, String> {
589 let bearer = auth_bearer_token()?;
590 let url = format!("{}/api/cloud/models", api_url());
591
592 let resp = ureq::get(&url)
593 .header("Authorization", &format!("Bearer {bearer}"))
594 .call()
595 .map_err(|e| {
596 let msg = e.to_string();
597 if msg.contains("403") {
598 "This feature is not available for your account.".to_string()
599 } else {
600 format!("Connection failed. Check your internet connection. ({e})")
601 }
602 })?;
603
604 let resp_body = resp
605 .into_body()
606 .read_to_string()
607 .map_err(|e| format!("Failed to read response: {e}"))?;
608
609 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
610}
611
612pub fn save_cloud_models(data: &serde_json::Value) -> std::io::Result<()> {
613 let dir = config_dir();
614 std::fs::create_dir_all(&dir)?;
615 let json = serde_json::to_string_pretty(data).map_err(std::io::Error::other)?;
616 std::fs::write(dir.join("cloud_models.json"), json)
617}
618
619pub fn load_cloud_models() -> Option<serde_json::Value> {
620 let path = config_dir().join("cloud_models.json");
621 let data = std::fs::read_to_string(path).ok()?;
622 serde_json::from_str(&data).ok()
623}
624
625pub fn fetch_leaderboard() -> Result<serde_json::Value, String> {
633 let url = format!("{}/api/leaderboard", api_url());
634 let resp = ureq::get(&url)
635 .config()
636 .timeout_global(Some(std::time::Duration::from_secs(10)))
637 .build()
638 .call()
639 .map_err(|e| format!("Could not reach the leaderboard service: {e}"))?;
640 let body = resp
641 .into_body()
642 .read_to_string()
643 .map_err(|e| format!("Failed to read leaderboard response: {e}"))?;
644 serde_json::from_str(&body).map_err(|e| format!("Invalid leaderboard JSON: {e}"))
645}
646
647pub fn is_cloud_user() -> bool {
648 let path = config_dir().join("plan.txt");
649 std::fs::read_to_string(path).is_ok_and(|p| matches!(p.trim(), "cloud" | "pro"))
650}
651
652pub const PLAN_GRACE_DAYS: i64 = 14;
656
657fn plan_cache_path() -> PathBuf {
658 config_dir().join("plan.json")
659}
660
661#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
664pub struct PlanCache {
665 pub plan: String,
666 pub verified_at: i64,
668}
669
670pub fn save_plan(plan: &str) -> std::io::Result<()> {
671 let dir = config_dir();
672 std::fs::create_dir_all(&dir)?;
673 std::fs::write(dir.join("plan.txt"), plan)?;
675 let cache = PlanCache {
677 plan: plan.to_string(),
678 verified_at: now_unix(),
679 };
680 let json = serde_json::to_string_pretty(&cache).map_err(std::io::Error::other)?;
681 std::fs::write(plan_cache_path(), json)
682}
683
684pub fn cached_plan() -> Option<PlanCache> {
688 if let Ok(data) = std::fs::read_to_string(plan_cache_path())
689 && let Ok(cache) = serde_json::from_str::<PlanCache>(&data)
690 {
691 return Some(cache);
692 }
693 let legacy = std::fs::read_to_string(config_dir().join("plan.txt")).ok()?;
694 Some(PlanCache {
695 plan: legacy.trim().to_string(),
696 verified_at: 0,
697 })
698}
699
700#[derive(Debug, Clone, Copy, PartialEq, Eq)]
703pub enum PlanSource {
704 Live,
706 Cached,
708 Expired,
710 None,
712}
713
714#[derive(Debug, Clone)]
718pub struct EffectivePlan {
719 pub plan: crate::core::billing::Plan,
720 pub source: PlanSource,
721 pub verified_at: Option<i64>,
722 pub grace_days: i64,
723}
724
725#[must_use]
728pub fn plan_within_grace(verified_at: i64, now: i64, grace_days: i64) -> (bool, i64) {
729 let age_days = (now - verified_at).max(0) / 86_400;
730 (age_days <= grace_days, age_days)
731}
732
733#[must_use]
742pub fn resolve_effective_plan_cached() -> EffectivePlan {
743 let grace_days = PLAN_GRACE_DAYS;
744 let Some(cache) = cached_plan() else {
745 return EffectivePlan {
746 plan: crate::core::billing::Plan::Free,
747 source: PlanSource::None,
748 verified_at: None,
749 grace_days,
750 };
751 };
752 let (fresh, _age) = plan_within_grace(cache.verified_at, now_unix(), grace_days);
753 if fresh {
754 EffectivePlan {
755 plan: crate::core::billing::Plan::parse(&cache.plan),
756 source: PlanSource::Cached,
757 verified_at: Some(cache.verified_at),
758 grace_days,
759 }
760 } else {
761 EffectivePlan {
764 plan: crate::core::billing::Plan::Free,
765 source: PlanSource::Expired,
766 verified_at: Some(cache.verified_at),
767 grace_days,
768 }
769 }
770}
771
772#[must_use]
776pub fn refresh_effective_plan() -> EffectivePlan {
777 if is_logged_in()
778 && let Ok(plan_str) = fetch_plan()
779 {
780 let _ = save_plan(&plan_str);
781 return EffectivePlan {
782 plan: crate::core::billing::Plan::parse(&plan_str),
783 source: PlanSource::Live,
784 verified_at: Some(now_unix()),
785 grace_days: PLAN_GRACE_DAYS,
786 };
787 }
788 resolve_effective_plan_cached()
789}
790
791pub fn fetch_plan() -> Result<String, String> {
792 let bearer = auth_bearer_token()?;
793 let url = format!("{}/api/auth/me", api_url());
794
795 let resp = ureq::get(&url)
796 .header("Authorization", &format!("Bearer {bearer}"))
797 .call()
798 .map_err(|e| format!("Failed to check plan: {e}"))?;
799
800 let resp_body = resp
801 .into_body()
802 .read_to_string()
803 .map_err(|e| format!("Failed to read response: {e}"))?;
804
805 let json: serde_json::Value =
806 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
807
808 Ok(json["plan"].as_str().unwrap_or("free").to_string())
809}
810
811pub fn start_checkout(plan: &str, interval: &str) -> Result<String, String> {
816 let bearer = auth_bearer_token()?;
817 let url = format!("{}/api/account/checkout", api_url());
818 let body = serde_json::json!({ "plan": plan, "interval": interval });
819
820 let resp = ureq::post(&url)
821 .header("Authorization", &format!("Bearer {bearer}"))
822 .header("Content-Type", "application/json")
823 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
824 .map_err(|e| format!("Checkout request failed: {e}"))?;
825
826 let resp_body = resp
827 .into_body()
828 .read_to_string()
829 .map_err(|e| format!("Failed to read response: {e}"))?;
830
831 let json: serde_json::Value =
832 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
833
834 json["url"]
835 .as_str()
836 .map(str::to_string)
837 .ok_or_else(|| "Billing did not return a checkout URL.".to_string())
838}
839
840pub fn push_commands(entries: &[serde_json::Value]) -> Result<String, String> {
841 let bearer = auth_bearer_token()?;
842 let url = format!("{}/api/sync/commands", api_url());
843 let body = serde_json::json!({ "commands": entries });
844 let resp = ureq::post(&url)
845 .header("Authorization", &format!("Bearer {bearer}"))
846 .header("Content-Type", "application/json")
847 .header("X-Device-Label", &device_label())
848 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
849 .map_err(|e| format!("Push failed: {e}"))?;
850 let resp_body = resp
851 .into_body()
852 .read_to_string()
853 .map_err(|e| format!("Failed to read response: {e}"))?;
854 let json: serde_json::Value =
855 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
856 Ok(format!(
857 "{} commands synced",
858 json["synced"].as_i64().unwrap_or(0)
859 ))
860}
861
862pub fn push_cep(entries: &[serde_json::Value]) -> Result<String, String> {
863 let bearer = auth_bearer_token()?;
864 let url = format!("{}/api/sync/cep", api_url());
865 let body = serde_json::json!({ "scores": entries });
866 let resp = ureq::post(&url)
867 .header("Authorization", &format!("Bearer {bearer}"))
868 .header("Content-Type", "application/json")
869 .header("X-Device-Label", &device_label())
870 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
871 .map_err(|e| format!("Push failed: {e}"))?;
872 let resp_body = resp
873 .into_body()
874 .read_to_string()
875 .map_err(|e| format!("Failed to read response: {e}"))?;
876 let json: serde_json::Value =
877 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
878 Ok(format!(
879 "{} sessions synced",
880 json["synced"].as_i64().unwrap_or(0)
881 ))
882}
883
884pub fn push_gain(entries: &[serde_json::Value]) -> Result<String, String> {
885 let bearer = auth_bearer_token()?;
886 let url = format!("{}/api/sync/gain", api_url());
887 let body = serde_json::json!({ "scores": entries });
888 let resp = ureq::post(&url)
889 .header("Authorization", &format!("Bearer {bearer}"))
890 .header("Content-Type", "application/json")
891 .header("X-Device-Label", &device_label())
892 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
893 .map_err(|e| format!("Push failed: {e}"))?;
894 let resp_body = resp
895 .into_body()
896 .read_to_string()
897 .map_err(|e| format!("Failed to read response: {e}"))?;
898 let json: serde_json::Value =
899 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
900 Ok(format!(
901 "{} gain scores synced",
902 json["synced"].as_i64().unwrap_or(0)
903 ))
904}
905
906pub fn push_gotchas(entries: &[serde_json::Value]) -> Result<String, String> {
911 let bearer = auth_bearer_token()?;
912 let key = gotcha_vault_key()?;
913 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
914 let url = format!("{}/api/sync/gotchas", api_url());
915
916 let resp = ureq::post(&url)
917 .header("Authorization", &format!("Bearer {bearer}"))
918 .header("Content-Type", "application/octet-stream")
919 .header("X-Entry-Count", &entries.len().to_string())
920 .header("X-Device-Label", &device_label())
921 .send(blob.as_slice())
922 .map_err(|e| format!("Push failed: {e}"))?;
923 let resp_body = resp
924 .into_body()
925 .read_to_string()
926 .map_err(|e| format!("Failed to read response: {e}"))?;
927 let json: serde_json::Value =
928 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
929 Ok(format!(
930 "{} gotchas synced (end-to-end encrypted)",
931 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
932 ))
933}
934
935fn gotcha_vault_key() -> Result<[u8; 32], String> {
938 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
939 if api_key.trim().is_empty() {
940 return Err("Not logged in. Run: lean-ctx login".into());
941 }
942 Ok(crate::core::knowledge_vault::derive_gotcha_vault_key(
943 &api_key,
944 ))
945}
946
947pub fn push_buddy(data: &serde_json::Value) -> Result<String, String> {
948 let bearer = auth_bearer_token()?;
949 let url = format!("{}/api/sync/buddy", api_url());
950 let resp = ureq::post(&url)
951 .header("Authorization", &format!("Bearer {bearer}"))
952 .header("Content-Type", "application/json")
953 .header("X-Device-Label", &device_label())
954 .send(&serde_json::to_vec(data).map_err(|e| format!("JSON error: {e}"))?)
955 .map_err(|e| format!("Push failed: {e}"))?;
956 let resp_body = resp
957 .into_body()
958 .read_to_string()
959 .map_err(|e| format!("Failed to read response: {e}"))?;
960 let _json: serde_json::Value =
961 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
962 Ok("Buddy synced".to_string())
963}
964
965pub fn push_feedback(entries: &[serde_json::Value]) -> Result<String, String> {
966 let bearer = auth_bearer_token()?;
967 let url = format!("{}/api/sync/feedback", api_url());
968 let resp = ureq::post(&url)
969 .header("Authorization", &format!("Bearer {bearer}"))
970 .header("Content-Type", "application/json")
971 .header("X-Device-Label", &device_label())
972 .send(&serde_json::to_vec(entries).map_err(|e| format!("JSON error: {e}"))?)
973 .map_err(|e| format!("Push failed: {e}"))?;
974 let resp_body = resp
975 .into_body()
976 .read_to_string()
977 .map_err(|e| format!("Failed to read response: {e}"))?;
978 let json: serde_json::Value =
979 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
980 Ok(format!(
981 "{} thresholds synced",
982 json["synced"].as_i64().unwrap_or(0)
983 ))
984}
985
986pub fn account_email() -> Option<String> {
988 load_credentials().map(|c| c.email)
989}
990
991pub fn fetch_account_cloud() -> Result<serde_json::Value, String> {
995 let bearer = auth_bearer_token()?;
996 let url = format!("{}/api/account/cloud", api_url());
997
998 let resp = ureq::get(&url)
999 .header("Authorization", &format!("Bearer {bearer}"))
1000 .call()
1001 .map_err(|e| format!("Status fetch failed: {e}"))?;
1002
1003 let resp_body = resp
1004 .into_body()
1005 .read_to_string()
1006 .map_err(|e| format!("Failed to read response: {e}"))?;
1007
1008 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))
1009}
1010
1011pub fn pull_knowledge() -> Result<Vec<serde_json::Value>, String> {
1014 let bearer = auth_bearer_token()?;
1015 let url = format!("{}/api/sync/knowledge", api_url());
1016
1017 match ureq::get(&url)
1019 .header("Authorization", &format!("Bearer {bearer}"))
1020 .header("Accept", "application/octet-stream")
1021 .call()
1022 {
1023 Ok(resp) => {
1024 let is_blob = resp
1025 .headers()
1026 .get("content-type")
1027 .and_then(|v| v.to_str().ok())
1028 .is_some_and(|v| v.starts_with("application/octet-stream"));
1029 if is_blob {
1030 let mut blob = Vec::new();
1031 use std::io::Read;
1032 resp.into_body()
1033 .into_reader()
1034 .read_to_end(&mut blob)
1035 .map_err(|e| format!("Failed to read vault: {e}"))?;
1036 let key = knowledge_vault_key()?;
1037 return crate::core::knowledge_vault::open(&blob, &key).map_err(|e| e.to_string());
1038 }
1039 let body = resp
1042 .into_body()
1043 .read_to_string()
1044 .map_err(|e| format!("Failed to read response: {e}"))?;
1045 return serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"));
1046 }
1047 Err(ureq::Error::StatusCode(404)) => {}
1049 Err(e) => return Err(format!("Pull failed: {e}")),
1050 }
1051
1052 let resp = ureq::get(&url)
1053 .header("Authorization", &format!("Bearer {bearer}"))
1054 .call()
1055 .map_err(|e| format!("Pull failed: {e}"))?;
1056
1057 let resp_body = resp
1058 .into_body()
1059 .read_to_string()
1060 .map_err(|e| format!("Failed to read response: {e}"))?;
1061
1062 let entries: Vec<serde_json::Value> =
1063 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1064
1065 Ok(entries)
1066}
1067
1068fn index_bundle_key() -> Result<[u8; 32], String> {
1076 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
1077 if api_key.trim().is_empty() {
1078 return Err("Not logged in. Run: lean-ctx login".into());
1079 }
1080 Ok(crate::core::index_bundle::derive_key(&api_key))
1081}
1082
1083pub fn push_index_bundle(project_root: &std::path::Path) -> Result<(String, u64), String> {
1086 let (container, manifest) =
1087 crate::core::index_bundle::pack(project_root).map_err(|e| e.to_string())?;
1088 let blob = crate::core::index_bundle::encrypt(&container, &index_bundle_key()?)
1089 .map_err(|e| e.to_string())?;
1090
1091 let bearer = auth_bearer_token()?;
1092 let url = format!("{}/api/sync/index/{}", api_url(), manifest.project_hash);
1093 let resp = ureq::put(&url)
1094 .header("Authorization", &format!("Bearer {bearer}"))
1095 .header("Content-Type", "application/octet-stream")
1096 .header("X-Device-Label", &device_label())
1097 .send(blob.as_slice())
1098 .map_err(|e| match e {
1099 ureq::Error::StatusCode(402) => {
1100 "Hosted index requires lean-ctx Pro. Run: lean-ctx upgrade".to_string()
1101 }
1102 ureq::Error::StatusCode(413) => {
1103 "Quota exceeded — the push was blocked (nothing is billed). \
1104 Free space with `lean-ctx sync index status` / delete, then retry."
1105 .to_string()
1106 }
1107 other => format!("Push failed: {other}"),
1108 })?;
1109
1110 let body = resp
1111 .into_body()
1112 .read_to_string()
1113 .map_err(|e| format!("Failed to read response: {e}"))?;
1114 let _ack: serde_json::Value =
1115 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
1116 Ok((manifest.project_hash, blob.len() as u64))
1117}
1118
1119pub fn pull_index_bundle(
1122 project_root: &std::path::Path,
1123) -> Result<crate::core::index_bundle::BundleManifest, String> {
1124 let project_hash = crate::core::index_namespace::namespace_hash(project_root);
1125 let bearer = auth_bearer_token()?;
1126 let url = format!("{}/api/sync/index/{project_hash}", api_url());
1127
1128 let resp = ureq::get(&url)
1129 .header("Authorization", &format!("Bearer {bearer}"))
1130 .call()
1131 .map_err(|e| match e {
1132 ureq::Error::StatusCode(404) => format!(
1133 "No hosted index for this project yet ({project_hash}). \
1134 Push one from a device with a built index: lean-ctx sync index push"
1135 ),
1136 ureq::Error::StatusCode(402) => {
1137 "Hosted index requires lean-ctx Pro. Run: lean-ctx upgrade".to_string()
1138 }
1139 other => format!("Pull failed: {other}"),
1140 })?;
1141
1142 let mut blob = Vec::new();
1143 use std::io::Read;
1144 resp.into_body()
1145 .into_reader()
1146 .read_to_end(&mut blob)
1147 .map_err(|e| format!("Failed to read bundle: {e}"))?;
1148
1149 let container = crate::core::index_bundle::decrypt(&blob, &index_bundle_key()?)
1150 .map_err(|e| e.to_string())?;
1151 crate::core::index_bundle::unpack(project_root, &container).map_err(|e| e.to_string())
1152}
1153
1154pub fn index_bundle_status() -> Result<serde_json::Value, String> {
1156 let bearer = auth_bearer_token()?;
1157 let url = format!("{}/api/sync/index", api_url());
1158 let resp = ureq::get(&url)
1159 .header("Authorization", &format!("Bearer {bearer}"))
1160 .call()
1161 .map_err(|e| format!("Status fetch failed: {e}"))?;
1162 let body = resp
1163 .into_body()
1164 .read_to_string()
1165 .map_err(|e| format!("Failed to read response: {e}"))?;
1166 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))
1167}
1168
1169#[cfg(test)]
1170mod tests {
1171 use super::*;
1172 use crate::core::billing::Plan;
1173 #[cfg(unix)]
1177 use crate::core::data_dir::test_env_lock;
1178
1179 #[test]
1180 fn existing_card_publish_response_carries_recovery_challenge() {
1181 let card: PublishedCard = serde_json::from_value(serde_json::json!({
1182 "id": "card-1",
1183 "url": "https://leanctx.com/w/card-1",
1184 "edit_token_challenge": "nonce-1",
1185 "challenge_expires_in_secs": 300
1186 }))
1187 .unwrap();
1188 assert!(card.edit_token.is_none());
1189 assert_eq!(card.edit_token_challenge.as_deref(), Some("nonce-1"));
1190 assert_eq!(card.challenge_expires_in_secs, Some(300));
1191 assert!(!card.account_claimed);
1192 }
1193
1194 #[test]
1195 fn grace_window_boundaries_are_inclusive_and_skew_safe() {
1196 let now = 1_000_000_000;
1197 let day = 86_400;
1198 assert_eq!(plan_within_grace(now, now, 14), (true, 0));
1199 assert_eq!(plan_within_grace(now - 14 * day, now, 14), (true, 14));
1201 assert_eq!(plan_within_grace(now - 15 * day, now, 14), (false, 15));
1203 assert_eq!(plan_within_grace(now + day, now, 14), (true, 0));
1205 }
1206
1207 #[test]
1208 fn plan_cache_roundtrips_through_json() {
1209 let c = PlanCache {
1210 plan: "pro".into(),
1211 verified_at: 42,
1212 };
1213 let back: PlanCache = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
1214 assert_eq!(back.plan, "pro");
1215 assert_eq!(back.verified_at, 42);
1216 }
1217
1218 #[test]
1219 fn cached_resolve_grants_within_grace_then_expires_to_free() {
1220 let _iso = crate::core::data_dir::isolated_data_dir();
1223
1224 save_plan("pro").unwrap();
1226 let eff = resolve_effective_plan_cached();
1227 assert_eq!(eff.plan, Plan::Pro);
1228 assert_eq!(eff.source, PlanSource::Cached);
1229
1230 let stale = PlanCache {
1232 plan: "pro".into(),
1233 verified_at: now_unix() - (PLAN_GRACE_DAYS + 1) * 86_400,
1234 };
1235 std::fs::write(plan_cache_path(), serde_json::to_string(&stale).unwrap()).unwrap();
1236 let eff = resolve_effective_plan_cached();
1237 assert_eq!(eff.plan, Plan::Free);
1238 assert_eq!(eff.source, PlanSource::Expired);
1239 }
1240
1241 #[test]
1242 fn no_cache_resolves_to_free_none() {
1243 let _iso = crate::core::data_dir::isolated_data_dir();
1244 let eff = resolve_effective_plan_cached();
1245 assert_eq!(eff.plan, Plan::Free);
1246 assert_eq!(eff.source, PlanSource::None);
1247 }
1248
1249 #[cfg(unix)]
1251 #[test]
1252 fn credentials_are_written_owner_only_and_atomic() {
1253 use std::os::unix::fs::PermissionsExt;
1254 let _env = test_env_lock();
1255 let tmp = tempfile::tempdir().unwrap();
1256 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1257
1258 save_credentials("sk-test-key", "user-1", "a@b.c").unwrap();
1259
1260 let path = credentials_path();
1261 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1262 assert_eq!(mode & 0o777, 0o600, "credentials.json must be 0o600");
1263
1264 let dir_mode = std::fs::metadata(config_dir())
1265 .unwrap()
1266 .permissions()
1267 .mode();
1268 assert_eq!(
1269 dir_mode & 0o077,
1270 0,
1271 "cloud dir must not be group/world accessible"
1272 );
1273
1274 let leftovers: Vec<_> = std::fs::read_dir(config_dir())
1276 .unwrap()
1277 .filter_map(Result::ok)
1278 .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
1279 .collect();
1280 assert!(leftovers.is_empty(), "atomic write must not leak tmp files");
1281
1282 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1283 }
1284
1285 #[cfg(unix)]
1287 #[test]
1288 fn loose_credential_permissions_are_tightened_on_load() {
1289 use std::os::unix::fs::PermissionsExt;
1290 let _env = test_env_lock();
1291 let tmp = tempfile::tempdir().unwrap();
1292 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1293
1294 std::fs::create_dir_all(config_dir()).unwrap();
1295 let path = credentials_path();
1296 std::fs::write(&path, "{}").unwrap();
1297 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
1298
1299 let _ = load_credentials();
1300
1301 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1302 assert_eq!(
1303 mode & 0o777,
1304 0o600,
1305 "legacy file must be tightened to 0o600"
1306 );
1307
1308 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1309 }
1310
1311 #[test]
1312 fn legacy_plan_txt_is_migrated_but_treated_as_stale() {
1313 let _iso = crate::core::data_dir::isolated_data_dir();
1314 std::fs::create_dir_all(config_dir()).unwrap();
1316 std::fs::write(config_dir().join("plan.txt"), "team").unwrap();
1317 let cache = cached_plan().unwrap();
1318 assert_eq!(cache.plan, "team");
1319 assert_eq!(cache.verified_at, 0);
1320 assert_eq!(resolve_effective_plan_cached().source, PlanSource::Expired);
1321 }
1322}