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 pub url: String,
415}
416
417pub fn publish_wrapped(payload: &serde_json::Value) -> Result<PublishedCard, String> {
421 let url = format!("{}/api/wrapped", api_url());
422
423 let resp = ureq::post(&url)
424 .header("Content-Type", "application/json")
425 .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
426 .map_err(|e| format!("Publish failed: {e}"))?;
427
428 let resp_body = resp
429 .into_body()
430 .read_to_string()
431 .map_err(|e| format!("Failed to read response: {e}"))?;
432
433 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
434}
435
436pub fn unpublish_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
438 let url = format!("{}/api/wrapped/{id}", api_url());
439
440 ureq::delete(&url)
441 .header("X-Edit-Token", edit_token)
442 .call()
443 .map_err(|e| format!("Unpublish failed: {e}"))?;
444 Ok(())
445}
446
447pub fn claim_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
451 let bearer = auth_bearer_token()?;
452 let url = format!("{}/api/wrapped/{id}/claim", api_url());
453
454 ureq::post(&url)
455 .header("Authorization", &format!("Bearer {bearer}"))
456 .header("X-Edit-Token", edit_token)
457 .send_empty()
458 .map_err(|e| format!("Claim failed: {e}"))?;
459 Ok(())
460}
461
462#[derive(serde::Deserialize)]
464pub struct LinkCode {
465 pub code: String,
466 pub expires_in_secs: i64,
467}
468
469pub fn link_wrapped_start(id: &str, edit_token: &str) -> Result<LinkCode, String> {
472 let url = format!("{}/api/wrapped/{id}/link/start", api_url());
473
474 let resp = ureq::post(&url)
475 .header("X-Edit-Token", edit_token)
476 .send_empty()
477 .map_err(|e| format!("Link start failed: {e}"))?;
478 let body = resp
479 .into_body()
480 .read_to_string()
481 .map_err(|e| format!("Failed to read response: {e}"))?;
482 serde_json::from_str(&body).map_err(|e| format!("Invalid response: {e}"))
483}
484
485pub fn link_wrapped_complete(id: &str, edit_token: &str, code: &str) -> Result<(), String> {
489 let url = format!("{}/api/wrapped/{id}/link/complete", api_url());
490 let body = serde_json::json!({ "code": code });
491
492 ureq::post(&url)
493 .header("X-Edit-Token", edit_token)
494 .header("Content-Type", "application/json")
495 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
496 .map_err(|e| match e {
497 ureq::Error::StatusCode(404) => {
498 "code invalid or expired — mint a fresh one with lean-ctx gain --link".to_string()
499 }
500 other => format!("Link failed: {other}"),
501 })?;
502 Ok(())
503}
504
505pub fn push_knowledge(entries: &[serde_json::Value]) -> Result<String, String> {
510 let bearer = auth_bearer_token()?;
511 let key = knowledge_vault_key()?;
512 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
513 let url = format!("{}/api/sync/knowledge", api_url());
514
515 let resp = ureq::post(&url)
516 .header("Authorization", &format!("Bearer {bearer}"))
517 .header("Content-Type", "application/octet-stream")
518 .header("X-Entry-Count", &entries.len().to_string())
519 .header("X-Device-Label", &device_label())
520 .send(blob.as_slice())
521 .map_err(|e| format!("Push failed: {e}"))?;
522
523 let resp_body = resp
524 .into_body()
525 .read_to_string()
526 .map_err(|e| format!("Failed to read response: {e}"))?;
527
528 let json: serde_json::Value =
529 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
530
531 Ok(format!(
532 "{} entries synced (end-to-end encrypted)",
533 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
534 ))
535}
536
537fn knowledge_vault_key() -> Result<[u8; 32], String> {
540 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
541 if api_key.trim().is_empty() {
542 return Err("Not logged in. Run: lean-ctx login".into());
543 }
544 Ok(crate::core::knowledge_vault::derive_vault_key(&api_key))
545}
546
547pub fn pull_cloud_models() -> Result<serde_json::Value, String> {
548 let bearer = auth_bearer_token()?;
549 let url = format!("{}/api/cloud/models", api_url());
550
551 let resp = ureq::get(&url)
552 .header("Authorization", &format!("Bearer {bearer}"))
553 .call()
554 .map_err(|e| {
555 let msg = e.to_string();
556 if msg.contains("403") {
557 "This feature is not available for your account.".to_string()
558 } else {
559 format!("Connection failed. Check your internet connection. ({e})")
560 }
561 })?;
562
563 let resp_body = resp
564 .into_body()
565 .read_to_string()
566 .map_err(|e| format!("Failed to read response: {e}"))?;
567
568 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
569}
570
571pub fn save_cloud_models(data: &serde_json::Value) -> std::io::Result<()> {
572 let dir = config_dir();
573 std::fs::create_dir_all(&dir)?;
574 let json = serde_json::to_string_pretty(data).map_err(std::io::Error::other)?;
575 std::fs::write(dir.join("cloud_models.json"), json)
576}
577
578pub fn load_cloud_models() -> Option<serde_json::Value> {
579 let path = config_dir().join("cloud_models.json");
580 let data = std::fs::read_to_string(path).ok()?;
581 serde_json::from_str(&data).ok()
582}
583
584pub fn fetch_leaderboard() -> Result<serde_json::Value, String> {
592 let url = format!("{}/api/leaderboard", api_url());
593 let resp = ureq::get(&url)
594 .config()
595 .timeout_global(Some(std::time::Duration::from_secs(10)))
596 .build()
597 .call()
598 .map_err(|e| format!("Could not reach the leaderboard service: {e}"))?;
599 let body = resp
600 .into_body()
601 .read_to_string()
602 .map_err(|e| format!("Failed to read leaderboard response: {e}"))?;
603 serde_json::from_str(&body).map_err(|e| format!("Invalid leaderboard JSON: {e}"))
604}
605
606pub fn is_cloud_user() -> bool {
607 let path = config_dir().join("plan.txt");
608 std::fs::read_to_string(path).is_ok_and(|p| matches!(p.trim(), "cloud" | "pro"))
609}
610
611pub const PLAN_GRACE_DAYS: i64 = 14;
615
616fn plan_cache_path() -> PathBuf {
617 config_dir().join("plan.json")
618}
619
620#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
623pub struct PlanCache {
624 pub plan: String,
625 pub verified_at: i64,
627}
628
629pub fn save_plan(plan: &str) -> std::io::Result<()> {
630 let dir = config_dir();
631 std::fs::create_dir_all(&dir)?;
632 std::fs::write(dir.join("plan.txt"), plan)?;
634 let cache = PlanCache {
636 plan: plan.to_string(),
637 verified_at: now_unix(),
638 };
639 let json = serde_json::to_string_pretty(&cache).map_err(std::io::Error::other)?;
640 std::fs::write(plan_cache_path(), json)
641}
642
643pub fn cached_plan() -> Option<PlanCache> {
647 if let Ok(data) = std::fs::read_to_string(plan_cache_path())
648 && let Ok(cache) = serde_json::from_str::<PlanCache>(&data)
649 {
650 return Some(cache);
651 }
652 let legacy = std::fs::read_to_string(config_dir().join("plan.txt")).ok()?;
653 Some(PlanCache {
654 plan: legacy.trim().to_string(),
655 verified_at: 0,
656 })
657}
658
659#[derive(Debug, Clone, Copy, PartialEq, Eq)]
662pub enum PlanSource {
663 Live,
665 Cached,
667 Expired,
669 None,
671}
672
673#[derive(Debug, Clone)]
677pub struct EffectivePlan {
678 pub plan: crate::core::billing::Plan,
679 pub source: PlanSource,
680 pub verified_at: Option<i64>,
681 pub grace_days: i64,
682}
683
684#[must_use]
687pub fn plan_within_grace(verified_at: i64, now: i64, grace_days: i64) -> (bool, i64) {
688 let age_days = (now - verified_at).max(0) / 86_400;
689 (age_days <= grace_days, age_days)
690}
691
692#[must_use]
701pub fn resolve_effective_plan_cached() -> EffectivePlan {
702 let grace_days = PLAN_GRACE_DAYS;
703 let Some(cache) = cached_plan() else {
704 return EffectivePlan {
705 plan: crate::core::billing::Plan::Free,
706 source: PlanSource::None,
707 verified_at: None,
708 grace_days,
709 };
710 };
711 let (fresh, _age) = plan_within_grace(cache.verified_at, now_unix(), grace_days);
712 if fresh {
713 EffectivePlan {
714 plan: crate::core::billing::Plan::parse(&cache.plan),
715 source: PlanSource::Cached,
716 verified_at: Some(cache.verified_at),
717 grace_days,
718 }
719 } else {
720 EffectivePlan {
723 plan: crate::core::billing::Plan::Free,
724 source: PlanSource::Expired,
725 verified_at: Some(cache.verified_at),
726 grace_days,
727 }
728 }
729}
730
731#[must_use]
735pub fn refresh_effective_plan() -> EffectivePlan {
736 if is_logged_in()
737 && let Ok(plan_str) = fetch_plan()
738 {
739 let _ = save_plan(&plan_str);
740 return EffectivePlan {
741 plan: crate::core::billing::Plan::parse(&plan_str),
742 source: PlanSource::Live,
743 verified_at: Some(now_unix()),
744 grace_days: PLAN_GRACE_DAYS,
745 };
746 }
747 resolve_effective_plan_cached()
748}
749
750pub fn fetch_plan() -> Result<String, String> {
751 let bearer = auth_bearer_token()?;
752 let url = format!("{}/api/auth/me", api_url());
753
754 let resp = ureq::get(&url)
755 .header("Authorization", &format!("Bearer {bearer}"))
756 .call()
757 .map_err(|e| format!("Failed to check plan: {e}"))?;
758
759 let resp_body = resp
760 .into_body()
761 .read_to_string()
762 .map_err(|e| format!("Failed to read response: {e}"))?;
763
764 let json: serde_json::Value =
765 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
766
767 Ok(json["plan"].as_str().unwrap_or("free").to_string())
768}
769
770pub fn start_checkout(plan: &str, interval: &str) -> Result<String, String> {
775 let bearer = auth_bearer_token()?;
776 let url = format!("{}/api/account/checkout", api_url());
777 let body = serde_json::json!({ "plan": plan, "interval": interval });
778
779 let resp = ureq::post(&url)
780 .header("Authorization", &format!("Bearer {bearer}"))
781 .header("Content-Type", "application/json")
782 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
783 .map_err(|e| format!("Checkout request failed: {e}"))?;
784
785 let resp_body = resp
786 .into_body()
787 .read_to_string()
788 .map_err(|e| format!("Failed to read response: {e}"))?;
789
790 let json: serde_json::Value =
791 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
792
793 json["url"]
794 .as_str()
795 .map(str::to_string)
796 .ok_or_else(|| "Billing did not return a checkout URL.".to_string())
797}
798
799pub fn push_commands(entries: &[serde_json::Value]) -> Result<String, String> {
800 let bearer = auth_bearer_token()?;
801 let url = format!("{}/api/sync/commands", api_url());
802 let body = serde_json::json!({ "commands": entries });
803 let resp = ureq::post(&url)
804 .header("Authorization", &format!("Bearer {bearer}"))
805 .header("Content-Type", "application/json")
806 .header("X-Device-Label", &device_label())
807 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
808 .map_err(|e| format!("Push failed: {e}"))?;
809 let resp_body = resp
810 .into_body()
811 .read_to_string()
812 .map_err(|e| format!("Failed to read response: {e}"))?;
813 let json: serde_json::Value =
814 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
815 Ok(format!(
816 "{} commands synced",
817 json["synced"].as_i64().unwrap_or(0)
818 ))
819}
820
821pub fn push_cep(entries: &[serde_json::Value]) -> Result<String, String> {
822 let bearer = auth_bearer_token()?;
823 let url = format!("{}/api/sync/cep", api_url());
824 let body = serde_json::json!({ "scores": entries });
825 let resp = ureq::post(&url)
826 .header("Authorization", &format!("Bearer {bearer}"))
827 .header("Content-Type", "application/json")
828 .header("X-Device-Label", &device_label())
829 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
830 .map_err(|e| format!("Push failed: {e}"))?;
831 let resp_body = resp
832 .into_body()
833 .read_to_string()
834 .map_err(|e| format!("Failed to read response: {e}"))?;
835 let json: serde_json::Value =
836 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
837 Ok(format!(
838 "{} sessions synced",
839 json["synced"].as_i64().unwrap_or(0)
840 ))
841}
842
843pub fn push_gain(entries: &[serde_json::Value]) -> Result<String, String> {
844 let bearer = auth_bearer_token()?;
845 let url = format!("{}/api/sync/gain", api_url());
846 let body = serde_json::json!({ "scores": entries });
847 let resp = ureq::post(&url)
848 .header("Authorization", &format!("Bearer {bearer}"))
849 .header("Content-Type", "application/json")
850 .header("X-Device-Label", &device_label())
851 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
852 .map_err(|e| format!("Push failed: {e}"))?;
853 let resp_body = resp
854 .into_body()
855 .read_to_string()
856 .map_err(|e| format!("Failed to read response: {e}"))?;
857 let json: serde_json::Value =
858 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
859 Ok(format!(
860 "{} gain scores synced",
861 json["synced"].as_i64().unwrap_or(0)
862 ))
863}
864
865pub fn push_gotchas(entries: &[serde_json::Value]) -> Result<String, String> {
870 let bearer = auth_bearer_token()?;
871 let key = gotcha_vault_key()?;
872 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
873 let url = format!("{}/api/sync/gotchas", api_url());
874
875 let resp = ureq::post(&url)
876 .header("Authorization", &format!("Bearer {bearer}"))
877 .header("Content-Type", "application/octet-stream")
878 .header("X-Entry-Count", &entries.len().to_string())
879 .header("X-Device-Label", &device_label())
880 .send(blob.as_slice())
881 .map_err(|e| format!("Push failed: {e}"))?;
882 let resp_body = resp
883 .into_body()
884 .read_to_string()
885 .map_err(|e| format!("Failed to read response: {e}"))?;
886 let json: serde_json::Value =
887 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
888 Ok(format!(
889 "{} gotchas synced (end-to-end encrypted)",
890 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
891 ))
892}
893
894fn gotcha_vault_key() -> Result<[u8; 32], String> {
897 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
898 if api_key.trim().is_empty() {
899 return Err("Not logged in. Run: lean-ctx login".into());
900 }
901 Ok(crate::core::knowledge_vault::derive_gotcha_vault_key(
902 &api_key,
903 ))
904}
905
906pub fn push_buddy(data: &serde_json::Value) -> Result<String, String> {
907 let bearer = auth_bearer_token()?;
908 let url = format!("{}/api/sync/buddy", api_url());
909 let resp = ureq::post(&url)
910 .header("Authorization", &format!("Bearer {bearer}"))
911 .header("Content-Type", "application/json")
912 .header("X-Device-Label", &device_label())
913 .send(&serde_json::to_vec(data).map_err(|e| format!("JSON error: {e}"))?)
914 .map_err(|e| format!("Push failed: {e}"))?;
915 let resp_body = resp
916 .into_body()
917 .read_to_string()
918 .map_err(|e| format!("Failed to read response: {e}"))?;
919 let _json: serde_json::Value =
920 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
921 Ok("Buddy synced".to_string())
922}
923
924pub fn push_feedback(entries: &[serde_json::Value]) -> Result<String, String> {
925 let bearer = auth_bearer_token()?;
926 let url = format!("{}/api/sync/feedback", api_url());
927 let resp = ureq::post(&url)
928 .header("Authorization", &format!("Bearer {bearer}"))
929 .header("Content-Type", "application/json")
930 .header("X-Device-Label", &device_label())
931 .send(&serde_json::to_vec(entries).map_err(|e| format!("JSON error: {e}"))?)
932 .map_err(|e| format!("Push failed: {e}"))?;
933 let resp_body = resp
934 .into_body()
935 .read_to_string()
936 .map_err(|e| format!("Failed to read response: {e}"))?;
937 let json: serde_json::Value =
938 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
939 Ok(format!(
940 "{} thresholds synced",
941 json["synced"].as_i64().unwrap_or(0)
942 ))
943}
944
945pub fn account_email() -> Option<String> {
947 load_credentials().map(|c| c.email)
948}
949
950pub fn fetch_account_cloud() -> Result<serde_json::Value, String> {
954 let bearer = auth_bearer_token()?;
955 let url = format!("{}/api/account/cloud", api_url());
956
957 let resp = ureq::get(&url)
958 .header("Authorization", &format!("Bearer {bearer}"))
959 .call()
960 .map_err(|e| format!("Status fetch failed: {e}"))?;
961
962 let resp_body = resp
963 .into_body()
964 .read_to_string()
965 .map_err(|e| format!("Failed to read response: {e}"))?;
966
967 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))
968}
969
970pub fn pull_knowledge() -> Result<Vec<serde_json::Value>, String> {
973 let bearer = auth_bearer_token()?;
974 let url = format!("{}/api/sync/knowledge", api_url());
975
976 match ureq::get(&url)
978 .header("Authorization", &format!("Bearer {bearer}"))
979 .header("Accept", "application/octet-stream")
980 .call()
981 {
982 Ok(resp) => {
983 let is_blob = resp
984 .headers()
985 .get("content-type")
986 .and_then(|v| v.to_str().ok())
987 .is_some_and(|v| v.starts_with("application/octet-stream"));
988 if is_blob {
989 let mut blob = Vec::new();
990 use std::io::Read;
991 resp.into_body()
992 .into_reader()
993 .read_to_end(&mut blob)
994 .map_err(|e| format!("Failed to read vault: {e}"))?;
995 let key = knowledge_vault_key()?;
996 return crate::core::knowledge_vault::open(&blob, &key).map_err(|e| e.to_string());
997 }
998 let body = resp
1001 .into_body()
1002 .read_to_string()
1003 .map_err(|e| format!("Failed to read response: {e}"))?;
1004 return serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"));
1005 }
1006 Err(ureq::Error::StatusCode(404)) => {}
1008 Err(e) => return Err(format!("Pull failed: {e}")),
1009 }
1010
1011 let resp = ureq::get(&url)
1012 .header("Authorization", &format!("Bearer {bearer}"))
1013 .call()
1014 .map_err(|e| format!("Pull failed: {e}"))?;
1015
1016 let resp_body = resp
1017 .into_body()
1018 .read_to_string()
1019 .map_err(|e| format!("Failed to read response: {e}"))?;
1020
1021 let entries: Vec<serde_json::Value> =
1022 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1023
1024 Ok(entries)
1025}
1026
1027fn index_bundle_key() -> Result<[u8; 32], String> {
1035 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
1036 if api_key.trim().is_empty() {
1037 return Err("Not logged in. Run: lean-ctx login".into());
1038 }
1039 Ok(crate::core::index_bundle::derive_key(&api_key))
1040}
1041
1042pub fn push_index_bundle(project_root: &std::path::Path) -> Result<(String, u64), String> {
1045 let (container, manifest) =
1046 crate::core::index_bundle::pack(project_root).map_err(|e| e.to_string())?;
1047 let blob = crate::core::index_bundle::encrypt(&container, &index_bundle_key()?)
1048 .map_err(|e| e.to_string())?;
1049
1050 let bearer = auth_bearer_token()?;
1051 let url = format!("{}/api/sync/index/{}", api_url(), manifest.project_hash);
1052 let resp = ureq::put(&url)
1053 .header("Authorization", &format!("Bearer {bearer}"))
1054 .header("Content-Type", "application/octet-stream")
1055 .header("X-Device-Label", &device_label())
1056 .send(blob.as_slice())
1057 .map_err(|e| match e {
1058 ureq::Error::StatusCode(402) => {
1059 "Hosted index requires lean-ctx Pro. Run: lean-ctx upgrade".to_string()
1060 }
1061 ureq::Error::StatusCode(413) => {
1062 "Quota exceeded — the push was blocked (nothing is billed). \
1063 Free space with `lean-ctx sync index status` / delete, then retry."
1064 .to_string()
1065 }
1066 other => format!("Push failed: {other}"),
1067 })?;
1068
1069 let body = resp
1070 .into_body()
1071 .read_to_string()
1072 .map_err(|e| format!("Failed to read response: {e}"))?;
1073 let _ack: serde_json::Value =
1074 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
1075 Ok((manifest.project_hash, blob.len() as u64))
1076}
1077
1078pub fn pull_index_bundle(
1081 project_root: &std::path::Path,
1082) -> Result<crate::core::index_bundle::BundleManifest, String> {
1083 let project_hash = crate::core::index_namespace::namespace_hash(project_root);
1084 let bearer = auth_bearer_token()?;
1085 let url = format!("{}/api/sync/index/{project_hash}", api_url());
1086
1087 let resp = ureq::get(&url)
1088 .header("Authorization", &format!("Bearer {bearer}"))
1089 .call()
1090 .map_err(|e| match e {
1091 ureq::Error::StatusCode(404) => format!(
1092 "No hosted index for this project yet ({project_hash}). \
1093 Push one from a device with a built index: lean-ctx sync index push"
1094 ),
1095 ureq::Error::StatusCode(402) => {
1096 "Hosted index requires lean-ctx Pro. Run: lean-ctx upgrade".to_string()
1097 }
1098 other => format!("Pull failed: {other}"),
1099 })?;
1100
1101 let mut blob = Vec::new();
1102 use std::io::Read;
1103 resp.into_body()
1104 .into_reader()
1105 .read_to_end(&mut blob)
1106 .map_err(|e| format!("Failed to read bundle: {e}"))?;
1107
1108 let container = crate::core::index_bundle::decrypt(&blob, &index_bundle_key()?)
1109 .map_err(|e| e.to_string())?;
1110 crate::core::index_bundle::unpack(project_root, &container).map_err(|e| e.to_string())
1111}
1112
1113pub fn index_bundle_status() -> Result<serde_json::Value, String> {
1115 let bearer = auth_bearer_token()?;
1116 let url = format!("{}/api/sync/index", api_url());
1117 let resp = ureq::get(&url)
1118 .header("Authorization", &format!("Bearer {bearer}"))
1119 .call()
1120 .map_err(|e| format!("Status fetch failed: {e}"))?;
1121 let body = resp
1122 .into_body()
1123 .read_to_string()
1124 .map_err(|e| format!("Failed to read response: {e}"))?;
1125 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))
1126}
1127
1128#[cfg(test)]
1129mod tests {
1130 use super::*;
1131 use crate::core::billing::Plan;
1132 #[cfg(unix)]
1136 use crate::core::data_dir::test_env_lock;
1137
1138 #[test]
1139 fn grace_window_boundaries_are_inclusive_and_skew_safe() {
1140 let now = 1_000_000_000;
1141 let day = 86_400;
1142 assert_eq!(plan_within_grace(now, now, 14), (true, 0));
1143 assert_eq!(plan_within_grace(now - 14 * day, now, 14), (true, 14));
1145 assert_eq!(plan_within_grace(now - 15 * day, now, 14), (false, 15));
1147 assert_eq!(plan_within_grace(now + day, now, 14), (true, 0));
1149 }
1150
1151 #[test]
1152 fn plan_cache_roundtrips_through_json() {
1153 let c = PlanCache {
1154 plan: "pro".into(),
1155 verified_at: 42,
1156 };
1157 let back: PlanCache = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
1158 assert_eq!(back.plan, "pro");
1159 assert_eq!(back.verified_at, 42);
1160 }
1161
1162 #[test]
1163 fn cached_resolve_grants_within_grace_then_expires_to_free() {
1164 let _iso = crate::core::data_dir::isolated_data_dir();
1167
1168 save_plan("pro").unwrap();
1170 let eff = resolve_effective_plan_cached();
1171 assert_eq!(eff.plan, Plan::Pro);
1172 assert_eq!(eff.source, PlanSource::Cached);
1173
1174 let stale = PlanCache {
1176 plan: "pro".into(),
1177 verified_at: now_unix() - (PLAN_GRACE_DAYS + 1) * 86_400,
1178 };
1179 std::fs::write(plan_cache_path(), serde_json::to_string(&stale).unwrap()).unwrap();
1180 let eff = resolve_effective_plan_cached();
1181 assert_eq!(eff.plan, Plan::Free);
1182 assert_eq!(eff.source, PlanSource::Expired);
1183 }
1184
1185 #[test]
1186 fn no_cache_resolves_to_free_none() {
1187 let _iso = crate::core::data_dir::isolated_data_dir();
1188 let eff = resolve_effective_plan_cached();
1189 assert_eq!(eff.plan, Plan::Free);
1190 assert_eq!(eff.source, PlanSource::None);
1191 }
1192
1193 #[cfg(unix)]
1195 #[test]
1196 fn credentials_are_written_owner_only_and_atomic() {
1197 use std::os::unix::fs::PermissionsExt;
1198 let _env = test_env_lock();
1199 let tmp = tempfile::tempdir().unwrap();
1200 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1201
1202 save_credentials("sk-test-key", "user-1", "a@b.c").unwrap();
1203
1204 let path = credentials_path();
1205 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1206 assert_eq!(mode & 0o777, 0o600, "credentials.json must be 0o600");
1207
1208 let dir_mode = std::fs::metadata(config_dir())
1209 .unwrap()
1210 .permissions()
1211 .mode();
1212 assert_eq!(
1213 dir_mode & 0o077,
1214 0,
1215 "cloud dir must not be group/world accessible"
1216 );
1217
1218 let leftovers: Vec<_> = std::fs::read_dir(config_dir())
1220 .unwrap()
1221 .filter_map(Result::ok)
1222 .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
1223 .collect();
1224 assert!(leftovers.is_empty(), "atomic write must not leak tmp files");
1225
1226 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1227 }
1228
1229 #[cfg(unix)]
1231 #[test]
1232 fn loose_credential_permissions_are_tightened_on_load() {
1233 use std::os::unix::fs::PermissionsExt;
1234 let _env = test_env_lock();
1235 let tmp = tempfile::tempdir().unwrap();
1236 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1237
1238 std::fs::create_dir_all(config_dir()).unwrap();
1239 let path = credentials_path();
1240 std::fs::write(&path, "{}").unwrap();
1241 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
1242
1243 let _ = load_credentials();
1244
1245 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1246 assert_eq!(
1247 mode & 0o777,
1248 0o600,
1249 "legacy file must be tightened to 0o600"
1250 );
1251
1252 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1253 }
1254
1255 #[test]
1256 fn legacy_plan_txt_is_migrated_but_treated_as_stale() {
1257 let _iso = crate::core::data_dir::isolated_data_dir();
1258 std::fs::create_dir_all(config_dir()).unwrap();
1260 std::fs::write(config_dir().join("plan.txt"), "team").unwrap();
1261 let cache = cached_plan().unwrap();
1262 assert_eq!(cache.plan, "team");
1263 assert_eq!(cache.verified_at, 0);
1264 assert_eq!(resolve_effective_plan_cached().source, PlanSource::Expired);
1265 }
1266}