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