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
462pub fn push_knowledge(entries: &[serde_json::Value]) -> Result<String, String> {
467 let bearer = auth_bearer_token()?;
468 let key = knowledge_vault_key()?;
469 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
470 let url = format!("{}/api/sync/knowledge", api_url());
471
472 let resp = ureq::post(&url)
473 .header("Authorization", &format!("Bearer {bearer}"))
474 .header("Content-Type", "application/octet-stream")
475 .header("X-Entry-Count", &entries.len().to_string())
476 .header("X-Device-Label", &device_label())
477 .send(blob.as_slice())
478 .map_err(|e| format!("Push failed: {e}"))?;
479
480 let resp_body = resp
481 .into_body()
482 .read_to_string()
483 .map_err(|e| format!("Failed to read response: {e}"))?;
484
485 let json: serde_json::Value =
486 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
487
488 Ok(format!(
489 "{} entries synced (end-to-end encrypted)",
490 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
491 ))
492}
493
494fn knowledge_vault_key() -> Result<[u8; 32], String> {
497 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
498 if api_key.trim().is_empty() {
499 return Err("Not logged in. Run: lean-ctx login".into());
500 }
501 Ok(crate::core::knowledge_vault::derive_vault_key(&api_key))
502}
503
504pub fn pull_cloud_models() -> Result<serde_json::Value, String> {
505 let bearer = auth_bearer_token()?;
506 let url = format!("{}/api/cloud/models", api_url());
507
508 let resp = ureq::get(&url)
509 .header("Authorization", &format!("Bearer {bearer}"))
510 .call()
511 .map_err(|e| {
512 let msg = e.to_string();
513 if msg.contains("403") {
514 "This feature is not available for your account.".to_string()
515 } else {
516 format!("Connection failed. Check your internet connection. ({e})")
517 }
518 })?;
519
520 let resp_body = resp
521 .into_body()
522 .read_to_string()
523 .map_err(|e| format!("Failed to read response: {e}"))?;
524
525 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
526}
527
528pub fn save_cloud_models(data: &serde_json::Value) -> std::io::Result<()> {
529 let dir = config_dir();
530 std::fs::create_dir_all(&dir)?;
531 let json = serde_json::to_string_pretty(data).map_err(std::io::Error::other)?;
532 std::fs::write(dir.join("cloud_models.json"), json)
533}
534
535pub fn load_cloud_models() -> Option<serde_json::Value> {
536 let path = config_dir().join("cloud_models.json");
537 let data = std::fs::read_to_string(path).ok()?;
538 serde_json::from_str(&data).ok()
539}
540
541pub fn fetch_leaderboard() -> Result<serde_json::Value, String> {
549 let url = format!("{}/api/leaderboard", api_url());
550 let resp = ureq::get(&url)
551 .config()
552 .timeout_global(Some(std::time::Duration::from_secs(10)))
553 .build()
554 .call()
555 .map_err(|e| format!("Could not reach the leaderboard service: {e}"))?;
556 let body = resp
557 .into_body()
558 .read_to_string()
559 .map_err(|e| format!("Failed to read leaderboard response: {e}"))?;
560 serde_json::from_str(&body).map_err(|e| format!("Invalid leaderboard JSON: {e}"))
561}
562
563pub fn is_cloud_user() -> bool {
564 let path = config_dir().join("plan.txt");
565 std::fs::read_to_string(path).is_ok_and(|p| matches!(p.trim(), "cloud" | "pro"))
566}
567
568pub const PLAN_GRACE_DAYS: i64 = 14;
572
573fn plan_cache_path() -> PathBuf {
574 config_dir().join("plan.json")
575}
576
577#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
580pub struct PlanCache {
581 pub plan: String,
582 pub verified_at: i64,
584}
585
586pub fn save_plan(plan: &str) -> std::io::Result<()> {
587 let dir = config_dir();
588 std::fs::create_dir_all(&dir)?;
589 std::fs::write(dir.join("plan.txt"), plan)?;
591 let cache = PlanCache {
593 plan: plan.to_string(),
594 verified_at: now_unix(),
595 };
596 let json = serde_json::to_string_pretty(&cache).map_err(std::io::Error::other)?;
597 std::fs::write(plan_cache_path(), json)
598}
599
600pub fn cached_plan() -> Option<PlanCache> {
604 if let Ok(data) = std::fs::read_to_string(plan_cache_path())
605 && let Ok(cache) = serde_json::from_str::<PlanCache>(&data)
606 {
607 return Some(cache);
608 }
609 let legacy = std::fs::read_to_string(config_dir().join("plan.txt")).ok()?;
610 Some(PlanCache {
611 plan: legacy.trim().to_string(),
612 verified_at: 0,
613 })
614}
615
616#[derive(Debug, Clone, Copy, PartialEq, Eq)]
619pub enum PlanSource {
620 Live,
622 Cached,
624 Expired,
626 None,
628}
629
630#[derive(Debug, Clone)]
634pub struct EffectivePlan {
635 pub plan: crate::core::billing::Plan,
636 pub source: PlanSource,
637 pub verified_at: Option<i64>,
638 pub grace_days: i64,
639}
640
641#[must_use]
644pub fn plan_within_grace(verified_at: i64, now: i64, grace_days: i64) -> (bool, i64) {
645 let age_days = (now - verified_at).max(0) / 86_400;
646 (age_days <= grace_days, age_days)
647}
648
649#[must_use]
658pub fn resolve_effective_plan_cached() -> EffectivePlan {
659 let grace_days = PLAN_GRACE_DAYS;
660 let Some(cache) = cached_plan() else {
661 return EffectivePlan {
662 plan: crate::core::billing::Plan::Free,
663 source: PlanSource::None,
664 verified_at: None,
665 grace_days,
666 };
667 };
668 let (fresh, _age) = plan_within_grace(cache.verified_at, now_unix(), grace_days);
669 if fresh {
670 EffectivePlan {
671 plan: crate::core::billing::Plan::parse(&cache.plan),
672 source: PlanSource::Cached,
673 verified_at: Some(cache.verified_at),
674 grace_days,
675 }
676 } else {
677 EffectivePlan {
680 plan: crate::core::billing::Plan::Free,
681 source: PlanSource::Expired,
682 verified_at: Some(cache.verified_at),
683 grace_days,
684 }
685 }
686}
687
688#[must_use]
692pub fn refresh_effective_plan() -> EffectivePlan {
693 if is_logged_in()
694 && let Ok(plan_str) = fetch_plan()
695 {
696 let _ = save_plan(&plan_str);
697 return EffectivePlan {
698 plan: crate::core::billing::Plan::parse(&plan_str),
699 source: PlanSource::Live,
700 verified_at: Some(now_unix()),
701 grace_days: PLAN_GRACE_DAYS,
702 };
703 }
704 resolve_effective_plan_cached()
705}
706
707pub fn fetch_plan() -> Result<String, String> {
708 let bearer = auth_bearer_token()?;
709 let url = format!("{}/api/auth/me", api_url());
710
711 let resp = ureq::get(&url)
712 .header("Authorization", &format!("Bearer {bearer}"))
713 .call()
714 .map_err(|e| format!("Failed to check plan: {e}"))?;
715
716 let resp_body = resp
717 .into_body()
718 .read_to_string()
719 .map_err(|e| format!("Failed to read response: {e}"))?;
720
721 let json: serde_json::Value =
722 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
723
724 Ok(json["plan"].as_str().unwrap_or("free").to_string())
725}
726
727pub fn start_checkout(plan: &str, interval: &str) -> Result<String, String> {
732 let bearer = auth_bearer_token()?;
733 let url = format!("{}/api/account/checkout", api_url());
734 let body = serde_json::json!({ "plan": plan, "interval": interval });
735
736 let resp = ureq::post(&url)
737 .header("Authorization", &format!("Bearer {bearer}"))
738 .header("Content-Type", "application/json")
739 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
740 .map_err(|e| format!("Checkout request failed: {e}"))?;
741
742 let resp_body = resp
743 .into_body()
744 .read_to_string()
745 .map_err(|e| format!("Failed to read response: {e}"))?;
746
747 let json: serde_json::Value =
748 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
749
750 json["url"]
751 .as_str()
752 .map(str::to_string)
753 .ok_or_else(|| "Billing did not return a checkout URL.".to_string())
754}
755
756pub fn push_commands(entries: &[serde_json::Value]) -> Result<String, String> {
757 let bearer = auth_bearer_token()?;
758 let url = format!("{}/api/sync/commands", api_url());
759 let body = serde_json::json!({ "commands": entries });
760 let resp = ureq::post(&url)
761 .header("Authorization", &format!("Bearer {bearer}"))
762 .header("Content-Type", "application/json")
763 .header("X-Device-Label", &device_label())
764 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
765 .map_err(|e| format!("Push failed: {e}"))?;
766 let resp_body = resp
767 .into_body()
768 .read_to_string()
769 .map_err(|e| format!("Failed to read response: {e}"))?;
770 let json: serde_json::Value =
771 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
772 Ok(format!(
773 "{} commands synced",
774 json["synced"].as_i64().unwrap_or(0)
775 ))
776}
777
778pub fn push_cep(entries: &[serde_json::Value]) -> Result<String, String> {
779 let bearer = auth_bearer_token()?;
780 let url = format!("{}/api/sync/cep", api_url());
781 let body = serde_json::json!({ "scores": entries });
782 let resp = ureq::post(&url)
783 .header("Authorization", &format!("Bearer {bearer}"))
784 .header("Content-Type", "application/json")
785 .header("X-Device-Label", &device_label())
786 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
787 .map_err(|e| format!("Push failed: {e}"))?;
788 let resp_body = resp
789 .into_body()
790 .read_to_string()
791 .map_err(|e| format!("Failed to read response: {e}"))?;
792 let json: serde_json::Value =
793 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
794 Ok(format!(
795 "{} sessions synced",
796 json["synced"].as_i64().unwrap_or(0)
797 ))
798}
799
800pub fn push_gain(entries: &[serde_json::Value]) -> Result<String, String> {
801 let bearer = auth_bearer_token()?;
802 let url = format!("{}/api/sync/gain", api_url());
803 let body = serde_json::json!({ "scores": entries });
804 let resp = ureq::post(&url)
805 .header("Authorization", &format!("Bearer {bearer}"))
806 .header("Content-Type", "application/json")
807 .header("X-Device-Label", &device_label())
808 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
809 .map_err(|e| format!("Push failed: {e}"))?;
810 let resp_body = resp
811 .into_body()
812 .read_to_string()
813 .map_err(|e| format!("Failed to read response: {e}"))?;
814 let json: serde_json::Value =
815 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
816 Ok(format!(
817 "{} gain scores synced",
818 json["synced"].as_i64().unwrap_or(0)
819 ))
820}
821
822pub fn push_gotchas(entries: &[serde_json::Value]) -> Result<String, String> {
827 let bearer = auth_bearer_token()?;
828 let key = gotcha_vault_key()?;
829 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
830 let url = format!("{}/api/sync/gotchas", api_url());
831
832 let resp = ureq::post(&url)
833 .header("Authorization", &format!("Bearer {bearer}"))
834 .header("Content-Type", "application/octet-stream")
835 .header("X-Entry-Count", &entries.len().to_string())
836 .header("X-Device-Label", &device_label())
837 .send(blob.as_slice())
838 .map_err(|e| format!("Push failed: {e}"))?;
839 let resp_body = resp
840 .into_body()
841 .read_to_string()
842 .map_err(|e| format!("Failed to read response: {e}"))?;
843 let json: serde_json::Value =
844 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
845 Ok(format!(
846 "{} gotchas synced (end-to-end encrypted)",
847 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
848 ))
849}
850
851fn gotcha_vault_key() -> Result<[u8; 32], String> {
854 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
855 if api_key.trim().is_empty() {
856 return Err("Not logged in. Run: lean-ctx login".into());
857 }
858 Ok(crate::core::knowledge_vault::derive_gotcha_vault_key(
859 &api_key,
860 ))
861}
862
863pub fn push_buddy(data: &serde_json::Value) -> Result<String, String> {
864 let bearer = auth_bearer_token()?;
865 let url = format!("{}/api/sync/buddy", api_url());
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(data).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("Buddy synced".to_string())
879}
880
881pub fn push_feedback(entries: &[serde_json::Value]) -> Result<String, String> {
882 let bearer = auth_bearer_token()?;
883 let url = format!("{}/api/sync/feedback", api_url());
884 let resp = ureq::post(&url)
885 .header("Authorization", &format!("Bearer {bearer}"))
886 .header("Content-Type", "application/json")
887 .header("X-Device-Label", &device_label())
888 .send(&serde_json::to_vec(entries).map_err(|e| format!("JSON error: {e}"))?)
889 .map_err(|e| format!("Push failed: {e}"))?;
890 let resp_body = resp
891 .into_body()
892 .read_to_string()
893 .map_err(|e| format!("Failed to read response: {e}"))?;
894 let json: serde_json::Value =
895 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
896 Ok(format!(
897 "{} thresholds synced",
898 json["synced"].as_i64().unwrap_or(0)
899 ))
900}
901
902pub fn account_email() -> Option<String> {
904 load_credentials().map(|c| c.email)
905}
906
907pub fn fetch_account_cloud() -> Result<serde_json::Value, String> {
911 let bearer = auth_bearer_token()?;
912 let url = format!("{}/api/account/cloud", api_url());
913
914 let resp = ureq::get(&url)
915 .header("Authorization", &format!("Bearer {bearer}"))
916 .call()
917 .map_err(|e| format!("Status fetch failed: {e}"))?;
918
919 let resp_body = resp
920 .into_body()
921 .read_to_string()
922 .map_err(|e| format!("Failed to read response: {e}"))?;
923
924 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))
925}
926
927pub fn pull_knowledge() -> Result<Vec<serde_json::Value>, String> {
930 let bearer = auth_bearer_token()?;
931 let url = format!("{}/api/sync/knowledge", api_url());
932
933 match ureq::get(&url)
935 .header("Authorization", &format!("Bearer {bearer}"))
936 .header("Accept", "application/octet-stream")
937 .call()
938 {
939 Ok(resp) => {
940 let is_blob = resp
941 .headers()
942 .get("content-type")
943 .and_then(|v| v.to_str().ok())
944 .is_some_and(|v| v.starts_with("application/octet-stream"));
945 if is_blob {
946 let mut blob = Vec::new();
947 use std::io::Read;
948 resp.into_body()
949 .into_reader()
950 .read_to_end(&mut blob)
951 .map_err(|e| format!("Failed to read vault: {e}"))?;
952 let key = knowledge_vault_key()?;
953 return crate::core::knowledge_vault::open(&blob, &key).map_err(|e| e.to_string());
954 }
955 let body = resp
958 .into_body()
959 .read_to_string()
960 .map_err(|e| format!("Failed to read response: {e}"))?;
961 return serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"));
962 }
963 Err(ureq::Error::StatusCode(404)) => {}
965 Err(e) => return Err(format!("Pull failed: {e}")),
966 }
967
968 let resp = ureq::get(&url)
969 .header("Authorization", &format!("Bearer {bearer}"))
970 .call()
971 .map_err(|e| format!("Pull failed: {e}"))?;
972
973 let resp_body = resp
974 .into_body()
975 .read_to_string()
976 .map_err(|e| format!("Failed to read response: {e}"))?;
977
978 let entries: Vec<serde_json::Value> =
979 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
980
981 Ok(entries)
982}
983
984fn index_bundle_key() -> Result<[u8; 32], String> {
992 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
993 if api_key.trim().is_empty() {
994 return Err("Not logged in. Run: lean-ctx login".into());
995 }
996 Ok(crate::core::index_bundle::derive_key(&api_key))
997}
998
999pub fn push_index_bundle(project_root: &std::path::Path) -> Result<(String, u64), String> {
1002 let (container, manifest) =
1003 crate::core::index_bundle::pack(project_root).map_err(|e| e.to_string())?;
1004 let blob = crate::core::index_bundle::encrypt(&container, &index_bundle_key()?)
1005 .map_err(|e| e.to_string())?;
1006
1007 let bearer = auth_bearer_token()?;
1008 let url = format!("{}/api/sync/index/{}", api_url(), manifest.project_hash);
1009 let resp = ureq::put(&url)
1010 .header("Authorization", &format!("Bearer {bearer}"))
1011 .header("Content-Type", "application/octet-stream")
1012 .header("X-Device-Label", &device_label())
1013 .send(blob.as_slice())
1014 .map_err(|e| match e {
1015 ureq::Error::StatusCode(402) => {
1016 "Hosted index requires lean-ctx Pro. Run: lean-ctx upgrade".to_string()
1017 }
1018 ureq::Error::StatusCode(413) => {
1019 "Quota exceeded — the push was blocked (nothing is billed). \
1020 Free space with `lean-ctx sync index status` / delete, then retry."
1021 .to_string()
1022 }
1023 other => format!("Push failed: {other}"),
1024 })?;
1025
1026 let body = resp
1027 .into_body()
1028 .read_to_string()
1029 .map_err(|e| format!("Failed to read response: {e}"))?;
1030 let _ack: serde_json::Value =
1031 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
1032 Ok((manifest.project_hash, blob.len() as u64))
1033}
1034
1035pub fn pull_index_bundle(
1038 project_root: &std::path::Path,
1039) -> Result<crate::core::index_bundle::BundleManifest, String> {
1040 let project_hash = crate::core::index_namespace::namespace_hash(project_root);
1041 let bearer = auth_bearer_token()?;
1042 let url = format!("{}/api/sync/index/{project_hash}", api_url());
1043
1044 let resp = ureq::get(&url)
1045 .header("Authorization", &format!("Bearer {bearer}"))
1046 .call()
1047 .map_err(|e| match e {
1048 ureq::Error::StatusCode(404) => format!(
1049 "No hosted index for this project yet ({project_hash}). \
1050 Push one from a device with a built index: lean-ctx sync index push"
1051 ),
1052 ureq::Error::StatusCode(402) => {
1053 "Hosted index requires lean-ctx Pro. Run: lean-ctx upgrade".to_string()
1054 }
1055 other => format!("Pull failed: {other}"),
1056 })?;
1057
1058 let mut blob = Vec::new();
1059 use std::io::Read;
1060 resp.into_body()
1061 .into_reader()
1062 .read_to_end(&mut blob)
1063 .map_err(|e| format!("Failed to read bundle: {e}"))?;
1064
1065 let container = crate::core::index_bundle::decrypt(&blob, &index_bundle_key()?)
1066 .map_err(|e| e.to_string())?;
1067 crate::core::index_bundle::unpack(project_root, &container).map_err(|e| e.to_string())
1068}
1069
1070pub fn index_bundle_status() -> Result<serde_json::Value, String> {
1072 let bearer = auth_bearer_token()?;
1073 let url = format!("{}/api/sync/index", api_url());
1074 let resp = ureq::get(&url)
1075 .header("Authorization", &format!("Bearer {bearer}"))
1076 .call()
1077 .map_err(|e| format!("Status fetch failed: {e}"))?;
1078 let body = resp
1079 .into_body()
1080 .read_to_string()
1081 .map_err(|e| format!("Failed to read response: {e}"))?;
1082 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))
1083}
1084
1085#[cfg(test)]
1086mod tests {
1087 use super::*;
1088 use crate::core::billing::Plan;
1089 #[cfg(unix)]
1093 use crate::core::data_dir::test_env_lock;
1094
1095 #[test]
1096 fn grace_window_boundaries_are_inclusive_and_skew_safe() {
1097 let now = 1_000_000_000;
1098 let day = 86_400;
1099 assert_eq!(plan_within_grace(now, now, 14), (true, 0));
1100 assert_eq!(plan_within_grace(now - 14 * day, now, 14), (true, 14));
1102 assert_eq!(plan_within_grace(now - 15 * day, now, 14), (false, 15));
1104 assert_eq!(plan_within_grace(now + day, now, 14), (true, 0));
1106 }
1107
1108 #[test]
1109 fn plan_cache_roundtrips_through_json() {
1110 let c = PlanCache {
1111 plan: "pro".into(),
1112 verified_at: 42,
1113 };
1114 let back: PlanCache = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
1115 assert_eq!(back.plan, "pro");
1116 assert_eq!(back.verified_at, 42);
1117 }
1118
1119 #[test]
1120 fn cached_resolve_grants_within_grace_then_expires_to_free() {
1121 let _iso = crate::core::data_dir::isolated_data_dir();
1124
1125 save_plan("pro").unwrap();
1127 let eff = resolve_effective_plan_cached();
1128 assert_eq!(eff.plan, Plan::Pro);
1129 assert_eq!(eff.source, PlanSource::Cached);
1130
1131 let stale = PlanCache {
1133 plan: "pro".into(),
1134 verified_at: now_unix() - (PLAN_GRACE_DAYS + 1) * 86_400,
1135 };
1136 std::fs::write(plan_cache_path(), serde_json::to_string(&stale).unwrap()).unwrap();
1137 let eff = resolve_effective_plan_cached();
1138 assert_eq!(eff.plan, Plan::Free);
1139 assert_eq!(eff.source, PlanSource::Expired);
1140 }
1141
1142 #[test]
1143 fn no_cache_resolves_to_free_none() {
1144 let _iso = crate::core::data_dir::isolated_data_dir();
1145 let eff = resolve_effective_plan_cached();
1146 assert_eq!(eff.plan, Plan::Free);
1147 assert_eq!(eff.source, PlanSource::None);
1148 }
1149
1150 #[cfg(unix)]
1152 #[test]
1153 fn credentials_are_written_owner_only_and_atomic() {
1154 use std::os::unix::fs::PermissionsExt;
1155 let _env = test_env_lock();
1156 let tmp = tempfile::tempdir().unwrap();
1157 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1158
1159 save_credentials("sk-test-key", "user-1", "a@b.c").unwrap();
1160
1161 let path = credentials_path();
1162 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1163 assert_eq!(mode & 0o777, 0o600, "credentials.json must be 0o600");
1164
1165 let dir_mode = std::fs::metadata(config_dir())
1166 .unwrap()
1167 .permissions()
1168 .mode();
1169 assert_eq!(
1170 dir_mode & 0o077,
1171 0,
1172 "cloud dir must not be group/world accessible"
1173 );
1174
1175 let leftovers: Vec<_> = std::fs::read_dir(config_dir())
1177 .unwrap()
1178 .filter_map(Result::ok)
1179 .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
1180 .collect();
1181 assert!(leftovers.is_empty(), "atomic write must not leak tmp files");
1182
1183 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1184 }
1185
1186 #[cfg(unix)]
1188 #[test]
1189 fn loose_credential_permissions_are_tightened_on_load() {
1190 use std::os::unix::fs::PermissionsExt;
1191 let _env = test_env_lock();
1192 let tmp = tempfile::tempdir().unwrap();
1193 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1194
1195 std::fs::create_dir_all(config_dir()).unwrap();
1196 let path = credentials_path();
1197 std::fs::write(&path, "{}").unwrap();
1198 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
1199
1200 let _ = load_credentials();
1201
1202 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1203 assert_eq!(
1204 mode & 0o777,
1205 0o600,
1206 "legacy file must be tightened to 0o600"
1207 );
1208
1209 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1210 }
1211
1212 #[test]
1213 fn legacy_plan_txt_is_migrated_but_treated_as_stale() {
1214 let _iso = crate::core::data_dir::isolated_data_dir();
1215 std::fs::create_dir_all(config_dir()).unwrap();
1217 std::fs::write(config_dir().join("plan.txt"), "team").unwrap();
1218 let cache = cached_plan().unwrap();
1219 assert_eq!(cache.plan, "team");
1220 assert_eq!(cache.verified_at, 0);
1221 assert_eq!(resolve_effective_plan_cached().source, PlanSource::Expired);
1222 }
1223}