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
406pub fn heartbeat(payload: &serde_json::Value) -> Result<String, String> {
409 let url = format!("{}/api/telemetry/heartbeat", api_url());
410
411 let resp = ureq::post(&url)
412 .header("Content-Type", "application/json")
413 .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
414 .map_err(|e| format!("Heartbeat failed: {e}"))?;
415
416 let resp_body = resp
417 .into_body()
418 .read_to_string()
419 .map_err(|e| format!("Failed to read response: {e}"))?;
420
421 let json: serde_json::Value =
422 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
423
424 Ok(json["message"].as_str().unwrap_or("OK").to_string())
425}
426
427pub fn submit_product_feedback(payload: &serde_json::Value) -> Result<String, String> {
439 let url = format!("{}/api/feedback/product", api_url());
440
441 let resp = ureq::post(&url)
442 .header("Content-Type", "application/json")
443 .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
444 .map_err(|e| format!("Could not send feedback: {e}"))?;
445
446 let body = resp
447 .into_body()
448 .read_to_string()
449 .map_err(|e| format!("Failed to read response: {e}"))?;
450
451 let json: serde_json::Value =
452 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
453
454 Ok(json["message"].as_str().unwrap_or("Thanks").to_string())
455}
456
457#[derive(serde::Deserialize)]
461pub struct PublishedCard {
462 pub id: String,
463 #[serde(default)]
464 pub edit_token: Option<String>,
465 #[serde(default)]
466 pub edit_token_challenge: Option<String>,
467 #[serde(default)]
468 pub challenge_expires_in_secs: Option<i64>,
469 pub url: String,
470 #[serde(skip)]
471 pub account_claimed: bool,
472}
473
474pub fn publish_wrapped(payload: &serde_json::Value) -> Result<PublishedCard, String> {
479 let url = format!("{}/api/wrapped", api_url());
480
481 let mut req = ureq::post(&url).header("Content-Type", "application/json");
482 if let Ok(token) = auth_bearer_token() {
483 req = req.header("Authorization", &format!("Bearer {token}"));
484 }
485 let resp = req
486 .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
487 .map_err(|e| format!("Publish failed: {e}"))?;
488
489 let resp_body = resp
490 .into_body()
491 .read_to_string()
492 .map_err(|e| format!("Failed to read response: {e}"))?;
493
494 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
495}
496
497#[derive(serde::Deserialize)]
498struct RecoveredEditToken {
499 edit_token: String,
500}
501
502pub fn recover_wrapped_edit_token(
505 id: &str,
506 nonce: &str,
507 public_key: &str,
508 signature: &str,
509) -> Result<String, String> {
510 let url = format!("{}/api/wrapped/{id}/edit-token/recover", api_url());
511 let body = serde_json::json!({
512 "nonce": nonce,
513 "public_key": public_key,
514 "signature": signature,
515 });
516 let resp = ureq::post(&url)
517 .header("Content-Type", "application/json")
518 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
519 .map_err(|e| format!("Edit-token recovery failed: {e}"))?;
520 let response = resp
521 .into_body()
522 .read_to_string()
523 .map_err(|e| format!("Failed to read response: {e}"))?;
524 let recovered: RecoveredEditToken =
525 serde_json::from_str(&response).map_err(|e| format!("Invalid recovery response: {e}"))?;
526 if recovered.edit_token.is_empty() {
527 return Err("Invalid recovery response: empty edit token".to_string());
528 }
529 Ok(recovered.edit_token)
530}
531
532pub fn unpublish_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
534 let url = format!("{}/api/wrapped/{id}", api_url());
535
536 ureq::delete(&url)
537 .header("X-Edit-Token", edit_token)
538 .call()
539 .map_err(|e| format!("Unpublish failed: {e}"))?;
540 Ok(())
541}
542
543pub fn claim_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
547 let bearer = auth_bearer_token()?;
548 let url = format!("{}/api/wrapped/{id}/claim", api_url());
549
550 ureq::post(&url)
551 .header("Authorization", &format!("Bearer {bearer}"))
552 .header("X-Edit-Token", edit_token)
553 .send_empty()
554 .map_err(|e| format!("Claim failed: {e}"))?;
555 Ok(())
556}
557
558#[derive(serde::Deserialize)]
560pub struct LinkCode {
561 pub code: String,
562 pub expires_in_secs: i64,
563}
564
565pub fn link_wrapped_start(id: &str, edit_token: &str) -> Result<LinkCode, String> {
568 let url = format!("{}/api/wrapped/{id}/link/start", api_url());
569
570 let resp = ureq::post(&url)
571 .header("X-Edit-Token", edit_token)
572 .send_empty()
573 .map_err(|e| format!("Link start failed: {e}"))?;
574 let body = resp
575 .into_body()
576 .read_to_string()
577 .map_err(|e| format!("Failed to read response: {e}"))?;
578 serde_json::from_str(&body).map_err(|e| format!("Invalid response: {e}"))
579}
580
581pub fn link_wrapped_complete(id: &str, edit_token: &str, code: &str) -> Result<(), String> {
585 let url = format!("{}/api/wrapped/{id}/link/complete", api_url());
586 let body = serde_json::json!({ "code": code });
587
588 ureq::post(&url)
589 .header("X-Edit-Token", edit_token)
590 .header("Content-Type", "application/json")
591 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
592 .map_err(|e| match e {
593 ureq::Error::StatusCode(404) => {
594 "code invalid or expired — mint a fresh one with lean-ctx gain --link".to_string()
595 }
596 other => format!("Link failed: {other}"),
597 })?;
598 Ok(())
599}
600
601pub fn push_knowledge(entries: &[serde_json::Value]) -> Result<String, String> {
606 let bearer = auth_bearer_token()?;
607 let key = knowledge_vault_key()?;
608 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
609 let url = format!("{}/api/sync/knowledge", api_url());
610
611 let resp = ureq::post(&url)
612 .header("Authorization", &format!("Bearer {bearer}"))
613 .header("Content-Type", "application/octet-stream")
614 .header("X-Entry-Count", &entries.len().to_string())
615 .header("X-Device-Label", &device_label())
616 .send(blob.as_slice())
617 .map_err(|e| format!("Push failed: {e}"))?;
618
619 let resp_body = resp
620 .into_body()
621 .read_to_string()
622 .map_err(|e| format!("Failed to read response: {e}"))?;
623
624 let json: serde_json::Value =
625 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
626
627 Ok(format!(
628 "{} entries synced (end-to-end encrypted)",
629 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
630 ))
631}
632
633fn knowledge_vault_key() -> Result<[u8; 32], String> {
636 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
637 if api_key.trim().is_empty() {
638 return Err("Not logged in. Run: lean-ctx login".into());
639 }
640 Ok(crate::core::knowledge_vault::derive_vault_key(&api_key))
641}
642
643pub fn pull_cloud_models() -> Result<serde_json::Value, String> {
644 let bearer = auth_bearer_token()?;
645 let url = format!("{}/api/cloud/models", api_url());
646
647 let resp = ureq::get(&url)
648 .header("Authorization", &format!("Bearer {bearer}"))
649 .call()
650 .map_err(|e| {
651 let msg = e.to_string();
652 if msg.contains("403") {
653 "This feature is not available for your account.".to_string()
654 } else {
655 format!("Connection failed. Check your internet connection. ({e})")
656 }
657 })?;
658
659 let resp_body = resp
660 .into_body()
661 .read_to_string()
662 .map_err(|e| format!("Failed to read response: {e}"))?;
663
664 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
665}
666
667pub fn save_cloud_models(data: &serde_json::Value) -> std::io::Result<()> {
668 let dir = config_dir();
669 std::fs::create_dir_all(&dir)?;
670 let json = serde_json::to_string_pretty(data).map_err(std::io::Error::other)?;
671 std::fs::write(dir.join("cloud_models.json"), json)
672}
673
674pub fn load_cloud_models() -> Option<serde_json::Value> {
675 let path = config_dir().join("cloud_models.json");
676 let data = std::fs::read_to_string(path).ok()?;
677 serde_json::from_str(&data).ok()
678}
679
680pub fn fetch_leaderboard() -> Result<serde_json::Value, String> {
688 let url = format!("{}/api/leaderboard", api_url());
689 let resp = ureq::get(&url)
690 .config()
691 .timeout_global(Some(std::time::Duration::from_secs(10)))
692 .build()
693 .call()
694 .map_err(|e| format!("Could not reach the leaderboard service: {e}"))?;
695 let body = resp
696 .into_body()
697 .read_to_string()
698 .map_err(|e| format!("Failed to read leaderboard response: {e}"))?;
699 serde_json::from_str(&body).map_err(|e| format!("Invalid leaderboard JSON: {e}"))
700}
701
702pub fn is_cloud_user() -> bool {
703 let path = config_dir().join("plan.txt");
704 std::fs::read_to_string(path).is_ok_and(|p| matches!(p.trim(), "cloud" | "pro"))
705}
706
707pub const PLAN_GRACE_DAYS: i64 = 14;
711
712fn plan_cache_path() -> PathBuf {
713 config_dir().join("plan.json")
714}
715
716#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
719pub struct PlanCache {
720 pub plan: String,
721 pub verified_at: i64,
723}
724
725pub fn save_plan(plan: &str) -> std::io::Result<()> {
726 let dir = config_dir();
727 std::fs::create_dir_all(&dir)?;
728 std::fs::write(dir.join("plan.txt"), plan)?;
730 let cache = PlanCache {
732 plan: plan.to_string(),
733 verified_at: now_unix(),
734 };
735 let json = serde_json::to_string_pretty(&cache).map_err(std::io::Error::other)?;
736 std::fs::write(plan_cache_path(), json)
737}
738
739pub fn cached_plan() -> Option<PlanCache> {
743 if let Ok(data) = std::fs::read_to_string(plan_cache_path())
744 && let Ok(cache) = serde_json::from_str::<PlanCache>(&data)
745 {
746 return Some(cache);
747 }
748 let legacy = std::fs::read_to_string(config_dir().join("plan.txt")).ok()?;
749 Some(PlanCache {
750 plan: legacy.trim().to_string(),
751 verified_at: 0,
752 })
753}
754
755#[derive(Debug, Clone, Copy, PartialEq, Eq)]
758pub enum PlanSource {
759 Live,
761 Cached,
763 Expired,
765 None,
767}
768
769#[derive(Debug, Clone)]
773pub struct EffectivePlan {
774 pub plan: crate::core::billing::Plan,
775 pub source: PlanSource,
776 pub verified_at: Option<i64>,
777 pub grace_days: i64,
778}
779
780#[must_use]
783pub fn plan_within_grace(verified_at: i64, now: i64, grace_days: i64) -> (bool, i64) {
784 let age_days = (now - verified_at).max(0) / 86_400;
785 (age_days <= grace_days, age_days)
786}
787
788#[must_use]
797pub fn resolve_effective_plan_cached() -> EffectivePlan {
798 let grace_days = PLAN_GRACE_DAYS;
799 let Some(cache) = cached_plan() else {
800 return EffectivePlan {
801 plan: crate::core::billing::Plan::Free,
802 source: PlanSource::None,
803 verified_at: None,
804 grace_days,
805 };
806 };
807 let (fresh, _age) = plan_within_grace(cache.verified_at, now_unix(), grace_days);
808 if fresh {
809 EffectivePlan {
810 plan: crate::core::billing::Plan::parse(&cache.plan),
811 source: PlanSource::Cached,
812 verified_at: Some(cache.verified_at),
813 grace_days,
814 }
815 } else {
816 EffectivePlan {
819 plan: crate::core::billing::Plan::Free,
820 source: PlanSource::Expired,
821 verified_at: Some(cache.verified_at),
822 grace_days,
823 }
824 }
825}
826
827#[must_use]
831pub fn refresh_effective_plan() -> EffectivePlan {
832 if is_logged_in()
833 && let Ok(plan_str) = fetch_plan()
834 {
835 let _ = save_plan(&plan_str);
836 return EffectivePlan {
837 plan: crate::core::billing::Plan::parse(&plan_str),
838 source: PlanSource::Live,
839 verified_at: Some(now_unix()),
840 grace_days: PLAN_GRACE_DAYS,
841 };
842 }
843 resolve_effective_plan_cached()
844}
845
846pub fn fetch_plan() -> Result<String, String> {
847 let bearer = auth_bearer_token()?;
848 let url = format!("{}/api/auth/me", api_url());
849
850 let resp = ureq::get(&url)
851 .header("Authorization", &format!("Bearer {bearer}"))
852 .call()
853 .map_err(|e| format!("Failed to check plan: {e}"))?;
854
855 let resp_body = resp
856 .into_body()
857 .read_to_string()
858 .map_err(|e| format!("Failed to read response: {e}"))?;
859
860 let json: serde_json::Value =
861 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
862
863 Ok(json["plan"].as_str().unwrap_or("free").to_string())
864}
865
866pub fn start_checkout(plan: &str, interval: &str) -> Result<String, String> {
871 let bearer = auth_bearer_token()?;
872 let url = format!("{}/api/account/checkout", api_url());
873 let body = serde_json::json!({ "plan": plan, "interval": interval });
874
875 let resp = ureq::post(&url)
876 .header("Authorization", &format!("Bearer {bearer}"))
877 .header("Content-Type", "application/json")
878 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
879 .map_err(|e| format!("Checkout request failed: {e}"))?;
880
881 let resp_body = resp
882 .into_body()
883 .read_to_string()
884 .map_err(|e| format!("Failed to read response: {e}"))?;
885
886 let json: serde_json::Value =
887 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
888
889 json["url"]
890 .as_str()
891 .map(str::to_string)
892 .ok_or_else(|| "Billing did not return a checkout URL.".to_string())
893}
894
895pub fn push_commands(entries: &[serde_json::Value]) -> Result<String, String> {
896 let bearer = auth_bearer_token()?;
897 let url = format!("{}/api/sync/commands", api_url());
898 let body = serde_json::json!({ "commands": entries });
899 let resp = ureq::post(&url)
900 .header("Authorization", &format!("Bearer {bearer}"))
901 .header("Content-Type", "application/json")
902 .header("X-Device-Label", &device_label())
903 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
904 .map_err(|e| format!("Push failed: {e}"))?;
905 let resp_body = resp
906 .into_body()
907 .read_to_string()
908 .map_err(|e| format!("Failed to read response: {e}"))?;
909 let json: serde_json::Value =
910 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
911 Ok(format!(
912 "{} commands synced",
913 json["synced"].as_i64().unwrap_or(0)
914 ))
915}
916
917pub fn push_cep(entries: &[serde_json::Value]) -> Result<String, String> {
918 let bearer = auth_bearer_token()?;
919 let url = format!("{}/api/sync/cep", api_url());
920 let body = serde_json::json!({ "scores": entries });
921 let resp = ureq::post(&url)
922 .header("Authorization", &format!("Bearer {bearer}"))
923 .header("Content-Type", "application/json")
924 .header("X-Device-Label", &device_label())
925 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
926 .map_err(|e| format!("Push failed: {e}"))?;
927 let resp_body = resp
928 .into_body()
929 .read_to_string()
930 .map_err(|e| format!("Failed to read response: {e}"))?;
931 let json: serde_json::Value =
932 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
933 Ok(format!(
934 "{} sessions synced",
935 json["synced"].as_i64().unwrap_or(0)
936 ))
937}
938
939pub fn push_gain(entries: &[serde_json::Value]) -> Result<String, String> {
940 let bearer = auth_bearer_token()?;
941 let url = format!("{}/api/sync/gain", api_url());
942 let body = serde_json::json!({ "scores": entries });
943 let resp = ureq::post(&url)
944 .header("Authorization", &format!("Bearer {bearer}"))
945 .header("Content-Type", "application/json")
946 .header("X-Device-Label", &device_label())
947 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
948 .map_err(|e| format!("Push failed: {e}"))?;
949 let resp_body = resp
950 .into_body()
951 .read_to_string()
952 .map_err(|e| format!("Failed to read response: {e}"))?;
953 let json: serde_json::Value =
954 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
955 Ok(format!(
956 "{} gain scores synced",
957 json["synced"].as_i64().unwrap_or(0)
958 ))
959}
960
961pub fn push_gotchas(entries: &[serde_json::Value]) -> Result<String, String> {
966 let bearer = auth_bearer_token()?;
967 let key = gotcha_vault_key()?;
968 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
969 let url = format!("{}/api/sync/gotchas", api_url());
970
971 let resp = ureq::post(&url)
972 .header("Authorization", &format!("Bearer {bearer}"))
973 .header("Content-Type", "application/octet-stream")
974 .header("X-Entry-Count", &entries.len().to_string())
975 .header("X-Device-Label", &device_label())
976 .send(blob.as_slice())
977 .map_err(|e| format!("Push failed: {e}"))?;
978 let resp_body = resp
979 .into_body()
980 .read_to_string()
981 .map_err(|e| format!("Failed to read response: {e}"))?;
982 let json: serde_json::Value =
983 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
984 Ok(format!(
985 "{} gotchas synced (end-to-end encrypted)",
986 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
987 ))
988}
989
990fn gotcha_vault_key() -> Result<[u8; 32], String> {
993 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
994 if api_key.trim().is_empty() {
995 return Err("Not logged in. Run: lean-ctx login".into());
996 }
997 Ok(crate::core::knowledge_vault::derive_gotcha_vault_key(
998 &api_key,
999 ))
1000}
1001
1002pub fn push_buddy(data: &serde_json::Value) -> Result<String, String> {
1003 let bearer = auth_bearer_token()?;
1004 let url = format!("{}/api/sync/buddy", api_url());
1005 let resp = ureq::post(&url)
1006 .header("Authorization", &format!("Bearer {bearer}"))
1007 .header("Content-Type", "application/json")
1008 .header("X-Device-Label", &device_label())
1009 .send(&serde_json::to_vec(data).map_err(|e| format!("JSON error: {e}"))?)
1010 .map_err(|e| format!("Push failed: {e}"))?;
1011 let resp_body = resp
1012 .into_body()
1013 .read_to_string()
1014 .map_err(|e| format!("Failed to read response: {e}"))?;
1015 let _json: serde_json::Value =
1016 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1017 Ok("Buddy synced".to_string())
1018}
1019
1020pub fn push_feedback(entries: &[serde_json::Value]) -> Result<String, String> {
1021 let bearer = auth_bearer_token()?;
1022 let url = format!("{}/api/sync/feedback", api_url());
1023 let resp = ureq::post(&url)
1024 .header("Authorization", &format!("Bearer {bearer}"))
1025 .header("Content-Type", "application/json")
1026 .header("X-Device-Label", &device_label())
1027 .send(&serde_json::to_vec(entries).map_err(|e| format!("JSON error: {e}"))?)
1028 .map_err(|e| format!("Push failed: {e}"))?;
1029 let resp_body = resp
1030 .into_body()
1031 .read_to_string()
1032 .map_err(|e| format!("Failed to read response: {e}"))?;
1033 let json: serde_json::Value =
1034 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1035 Ok(format!(
1036 "{} thresholds synced",
1037 json["synced"].as_i64().unwrap_or(0)
1038 ))
1039}
1040
1041pub fn account_email() -> Option<String> {
1043 load_credentials().map(|c| c.email)
1044}
1045
1046pub fn fetch_account_cloud() -> Result<serde_json::Value, String> {
1050 let bearer = auth_bearer_token()?;
1051 let url = format!("{}/api/account/cloud", api_url());
1052
1053 let resp = ureq::get(&url)
1054 .header("Authorization", &format!("Bearer {bearer}"))
1055 .call()
1056 .map_err(|e| format!("Status fetch failed: {e}"))?;
1057
1058 let resp_body = resp
1059 .into_body()
1060 .read_to_string()
1061 .map_err(|e| format!("Failed to read response: {e}"))?;
1062
1063 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))
1064}
1065
1066pub fn pull_knowledge() -> Result<Vec<serde_json::Value>, String> {
1069 let bearer = auth_bearer_token()?;
1070 let url = format!("{}/api/sync/knowledge", api_url());
1071
1072 match ureq::get(&url)
1074 .header("Authorization", &format!("Bearer {bearer}"))
1075 .header("Accept", "application/octet-stream")
1076 .call()
1077 {
1078 Ok(resp) => {
1079 let is_blob = resp
1080 .headers()
1081 .get("content-type")
1082 .and_then(|v| v.to_str().ok())
1083 .is_some_and(|v| v.starts_with("application/octet-stream"));
1084 if is_blob {
1085 let mut blob = Vec::new();
1086 use std::io::Read;
1087 resp.into_body()
1088 .into_reader()
1089 .read_to_end(&mut blob)
1090 .map_err(|e| format!("Failed to read vault: {e}"))?;
1091 let key = knowledge_vault_key()?;
1092 return crate::core::knowledge_vault::open(&blob, &key).map_err(|e| e.to_string());
1093 }
1094 let body = resp
1097 .into_body()
1098 .read_to_string()
1099 .map_err(|e| format!("Failed to read response: {e}"))?;
1100 return serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"));
1101 }
1102 Err(ureq::Error::StatusCode(404)) => {}
1104 Err(e) => return Err(format!("Pull failed: {e}")),
1105 }
1106
1107 let resp = ureq::get(&url)
1108 .header("Authorization", &format!("Bearer {bearer}"))
1109 .call()
1110 .map_err(|e| format!("Pull failed: {e}"))?;
1111
1112 let resp_body = resp
1113 .into_body()
1114 .read_to_string()
1115 .map_err(|e| format!("Failed to read response: {e}"))?;
1116
1117 let entries: Vec<serde_json::Value> =
1118 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1119
1120 Ok(entries)
1121}
1122
1123fn index_bundle_key() -> Result<[u8; 32], String> {
1131 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
1132 if api_key.trim().is_empty() {
1133 return Err("Not logged in. Run: lean-ctx login".into());
1134 }
1135 Ok(crate::core::index_bundle::derive_key(&api_key))
1136}
1137
1138pub fn push_index_bundle(project_root: &std::path::Path) -> Result<(String, u64), String> {
1141 let (container, manifest) =
1142 crate::core::index_bundle::pack(project_root).map_err(|e| e.to_string())?;
1143 let blob = crate::core::index_bundle::encrypt(&container, &index_bundle_key()?)
1144 .map_err(|e| e.to_string())?;
1145
1146 let bearer = auth_bearer_token()?;
1147 let url = format!("{}/api/sync/index/{}", api_url(), manifest.project_hash);
1148 let resp = ureq::put(&url)
1149 .header("Authorization", &format!("Bearer {bearer}"))
1150 .header("Content-Type", "application/octet-stream")
1151 .header("X-Device-Label", &device_label())
1152 .send(blob.as_slice())
1153 .map_err(|e| match e {
1154 ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1155 Run: lean-ctx cloud upgrade --plan pro"
1156 .to_string(),
1157 ureq::Error::StatusCode(413) => {
1158 "Quota exceeded — the push was blocked (nothing is billed). \
1159 Free space with `lean-ctx sync index status` / delete, then retry."
1160 .to_string()
1161 }
1162 other => format!("Push failed: {other}"),
1163 })?;
1164
1165 let body = resp
1166 .into_body()
1167 .read_to_string()
1168 .map_err(|e| format!("Failed to read response: {e}"))?;
1169 let _ack: serde_json::Value =
1170 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
1171 Ok((manifest.project_hash, blob.len() as u64))
1172}
1173
1174pub fn pull_index_bundle(
1177 project_root: &std::path::Path,
1178) -> Result<crate::core::index_bundle::BundleManifest, String> {
1179 let project_hash = crate::core::index_namespace::namespace_hash(project_root);
1180 let bearer = auth_bearer_token()?;
1181 let url = format!("{}/api/sync/index/{project_hash}", api_url());
1182
1183 let resp = ureq::get(&url)
1184 .header("Authorization", &format!("Bearer {bearer}"))
1185 .call()
1186 .map_err(|e| match e {
1187 ureq::Error::StatusCode(404) => format!(
1188 "No hosted index for this project yet ({project_hash}). \
1189 Push one from a device with a built index: lean-ctx sync index push"
1190 ),
1191 ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1192 Run: lean-ctx cloud upgrade --plan pro"
1193 .to_string(),
1194 other => format!("Pull failed: {other}"),
1195 })?;
1196
1197 let mut blob = Vec::new();
1198 use std::io::Read;
1199 resp.into_body()
1200 .into_reader()
1201 .read_to_end(&mut blob)
1202 .map_err(|e| format!("Failed to read bundle: {e}"))?;
1203
1204 let container = crate::core::index_bundle::decrypt(&blob, &index_bundle_key()?)
1205 .map_err(|e| e.to_string())?;
1206 crate::core::index_bundle::unpack(project_root, &container).map_err(|e| e.to_string())
1207}
1208
1209pub fn index_bundle_status() -> Result<serde_json::Value, String> {
1211 let bearer = auth_bearer_token()?;
1212 let url = format!("{}/api/sync/index", api_url());
1213 let resp = ureq::get(&url)
1214 .header("Authorization", &format!("Bearer {bearer}"))
1215 .call()
1216 .map_err(|e| format!("Status fetch failed: {e}"))?;
1217 let body = resp
1218 .into_body()
1219 .read_to_string()
1220 .map_err(|e| format!("Failed to read response: {e}"))?;
1221 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))
1222}
1223
1224#[cfg(test)]
1225mod tests {
1226 use super::*;
1227 use crate::core::billing::Plan;
1228 #[cfg(unix)]
1232 use crate::core::data_dir::test_env_lock;
1233
1234 #[test]
1235 fn existing_card_publish_response_carries_recovery_challenge() {
1236 let card: PublishedCard = serde_json::from_value(serde_json::json!({
1237 "id": "card-1",
1238 "url": "https://leanctx.com/w/card-1",
1239 "edit_token_challenge": "nonce-1",
1240 "challenge_expires_in_secs": 300
1241 }))
1242 .unwrap();
1243 assert!(card.edit_token.is_none());
1244 assert_eq!(card.edit_token_challenge.as_deref(), Some("nonce-1"));
1245 assert_eq!(card.challenge_expires_in_secs, Some(300));
1246 assert!(!card.account_claimed);
1247 }
1248
1249 #[test]
1250 fn grace_window_boundaries_are_inclusive_and_skew_safe() {
1251 let now = 1_000_000_000;
1252 let day = 86_400;
1253 assert_eq!(plan_within_grace(now, now, 14), (true, 0));
1254 assert_eq!(plan_within_grace(now - 14 * day, now, 14), (true, 14));
1256 assert_eq!(plan_within_grace(now - 15 * day, now, 14), (false, 15));
1258 assert_eq!(plan_within_grace(now + day, now, 14), (true, 0));
1260 }
1261
1262 #[test]
1263 fn plan_cache_roundtrips_through_json() {
1264 let c = PlanCache {
1265 plan: "pro".into(),
1266 verified_at: 42,
1267 };
1268 let back: PlanCache = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
1269 assert_eq!(back.plan, "pro");
1270 assert_eq!(back.verified_at, 42);
1271 }
1272
1273 #[test]
1274 fn cached_resolve_grants_within_grace_then_expires_to_free() {
1275 let _iso = crate::core::data_dir::isolated_data_dir();
1278
1279 save_plan("pro").unwrap();
1281 let eff = resolve_effective_plan_cached();
1282 assert_eq!(eff.plan, Plan::Pro);
1283 assert_eq!(eff.source, PlanSource::Cached);
1284
1285 let stale = PlanCache {
1287 plan: "pro".into(),
1288 verified_at: now_unix() - (PLAN_GRACE_DAYS + 1) * 86_400,
1289 };
1290 std::fs::write(plan_cache_path(), serde_json::to_string(&stale).unwrap()).unwrap();
1291 let eff = resolve_effective_plan_cached();
1292 assert_eq!(eff.plan, Plan::Free);
1293 assert_eq!(eff.source, PlanSource::Expired);
1294 }
1295
1296 #[test]
1297 fn no_cache_resolves_to_free_none() {
1298 let _iso = crate::core::data_dir::isolated_data_dir();
1299 let eff = resolve_effective_plan_cached();
1300 assert_eq!(eff.plan, Plan::Free);
1301 assert_eq!(eff.source, PlanSource::None);
1302 }
1303
1304 #[cfg(unix)]
1306 #[test]
1307 fn credentials_are_written_owner_only_and_atomic() {
1308 use std::os::unix::fs::PermissionsExt;
1309 let _env = test_env_lock();
1310 let tmp = tempfile::tempdir().unwrap();
1311 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1312
1313 save_credentials("sk-test-key", "user-1", "a@b.c").unwrap();
1314
1315 let path = credentials_path();
1316 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1317 assert_eq!(mode & 0o777, 0o600, "credentials.json must be 0o600");
1318
1319 let dir_mode = std::fs::metadata(config_dir())
1320 .unwrap()
1321 .permissions()
1322 .mode();
1323 assert_eq!(
1324 dir_mode & 0o077,
1325 0,
1326 "cloud dir must not be group/world accessible"
1327 );
1328
1329 let leftovers: Vec<_> = std::fs::read_dir(config_dir())
1331 .unwrap()
1332 .filter_map(Result::ok)
1333 .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
1334 .collect();
1335 assert!(leftovers.is_empty(), "atomic write must not leak tmp files");
1336
1337 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1338 }
1339
1340 #[cfg(unix)]
1342 #[test]
1343 fn loose_credential_permissions_are_tightened_on_load() {
1344 use std::os::unix::fs::PermissionsExt;
1345 let _env = test_env_lock();
1346 let tmp = tempfile::tempdir().unwrap();
1347 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1348
1349 std::fs::create_dir_all(config_dir()).unwrap();
1350 let path = credentials_path();
1351 std::fs::write(&path, "{}").unwrap();
1352 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
1353
1354 let _ = load_credentials();
1355
1356 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1357 assert_eq!(
1358 mode & 0o777,
1359 0o600,
1360 "legacy file must be tightened to 0o600"
1361 );
1362
1363 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1364 }
1365
1366 #[test]
1367 fn legacy_plan_txt_is_migrated_but_treated_as_stale() {
1368 let _iso = crate::core::data_dir::isolated_data_dir();
1369 std::fs::create_dir_all(config_dir()).unwrap();
1371 std::fs::write(config_dir().join("plan.txt"), "team").unwrap();
1372 let cache = cached_plan().unwrap();
1373 assert_eq!(cache.plan, "team");
1374 assert_eq!(cache.verified_at, 0);
1375 assert_eq!(resolve_effective_plan_cached().source, PlanSource::Expired);
1376 }
1377}