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> {
539 let url = format!("{}/api/wrapped/{id}", api_url());
540
541 match ureq::delete(&url).header("X-Edit-Token", edit_token).call() {
542 Ok(_) | Err(ureq::Error::StatusCode(404 | 410)) => Ok(()),
544 Err(e) => Err(format!("Unpublish failed: {e}")),
545 }
546}
547
548pub fn claim_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
552 let bearer = auth_bearer_token()?;
553 let url = format!("{}/api/wrapped/{id}/claim", api_url());
554
555 ureq::post(&url)
556 .header("Authorization", &format!("Bearer {bearer}"))
557 .header("X-Edit-Token", edit_token)
558 .send_empty()
559 .map_err(|e| format!("Claim failed: {e}"))?;
560 Ok(())
561}
562
563#[derive(serde::Deserialize)]
565pub struct LinkCode {
566 pub code: String,
567 pub expires_in_secs: i64,
568}
569
570pub fn link_wrapped_start(id: &str, edit_token: &str) -> Result<LinkCode, String> {
573 let url = format!("{}/api/wrapped/{id}/link/start", api_url());
574
575 let resp = ureq::post(&url)
576 .header("X-Edit-Token", edit_token)
577 .send_empty()
578 .map_err(|e| format!("Link start failed: {e}"))?;
579 let body = resp
580 .into_body()
581 .read_to_string()
582 .map_err(|e| format!("Failed to read response: {e}"))?;
583 serde_json::from_str(&body).map_err(|e| format!("Invalid response: {e}"))
584}
585
586pub fn link_wrapped_complete(id: &str, edit_token: &str, code: &str) -> Result<(), String> {
590 let url = format!("{}/api/wrapped/{id}/link/complete", api_url());
591 let body = serde_json::json!({ "code": code });
592
593 ureq::post(&url)
594 .header("X-Edit-Token", edit_token)
595 .header("Content-Type", "application/json")
596 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
597 .map_err(|e| match e {
598 ureq::Error::StatusCode(404) => {
599 "code invalid or expired — mint a fresh one with lean-ctx gain --link".to_string()
600 }
601 other => format!("Link failed: {other}"),
602 })?;
603 Ok(())
604}
605
606pub fn push_knowledge(entries: &[serde_json::Value]) -> Result<String, String> {
611 let bearer = auth_bearer_token()?;
612 let key = knowledge_vault_key()?;
613 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
614 let url = format!("{}/api/sync/knowledge", api_url());
615
616 let resp = ureq::post(&url)
617 .header("Authorization", &format!("Bearer {bearer}"))
618 .header("Content-Type", "application/octet-stream")
619 .header("X-Entry-Count", &entries.len().to_string())
620 .header("X-Device-Label", &device_label())
621 .send(blob.as_slice())
622 .map_err(|e| format!("Push failed: {e}"))?;
623
624 let resp_body = resp
625 .into_body()
626 .read_to_string()
627 .map_err(|e| format!("Failed to read response: {e}"))?;
628
629 let json: serde_json::Value =
630 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
631
632 Ok(format!(
633 "{} entries synced (end-to-end encrypted)",
634 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
635 ))
636}
637
638fn knowledge_vault_key() -> Result<[u8; 32], String> {
641 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
642 if api_key.trim().is_empty() {
643 return Err("Not logged in. Run: lean-ctx login".into());
644 }
645 Ok(crate::core::knowledge_vault::derive_vault_key(&api_key))
646}
647
648pub fn pull_cloud_models() -> Result<serde_json::Value, String> {
649 let bearer = auth_bearer_token()?;
650 let url = format!("{}/api/cloud/models", api_url());
651
652 let resp = ureq::get(&url)
653 .header("Authorization", &format!("Bearer {bearer}"))
654 .call()
655 .map_err(|e| {
656 let msg = e.to_string();
657 if msg.contains("403") {
658 "This feature is not available for your account.".to_string()
659 } else {
660 format!("Connection failed. Check your internet connection. ({e})")
661 }
662 })?;
663
664 let resp_body = resp
665 .into_body()
666 .read_to_string()
667 .map_err(|e| format!("Failed to read response: {e}"))?;
668
669 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
670}
671
672pub fn save_cloud_models(data: &serde_json::Value) -> std::io::Result<()> {
673 let dir = config_dir();
674 std::fs::create_dir_all(&dir)?;
675 let json = serde_json::to_string_pretty(data).map_err(std::io::Error::other)?;
676 std::fs::write(dir.join("cloud_models.json"), json)
677}
678
679pub fn load_cloud_models() -> Option<serde_json::Value> {
680 let path = config_dir().join("cloud_models.json");
681 let data = std::fs::read_to_string(path).ok()?;
682 serde_json::from_str(&data).ok()
683}
684
685pub fn fetch_leaderboard() -> Result<serde_json::Value, String> {
693 let url = format!("{}/api/leaderboard", api_url());
694 let resp = ureq::get(&url)
695 .config()
696 .timeout_global(Some(std::time::Duration::from_secs(10)))
697 .build()
698 .call()
699 .map_err(|e| format!("Could not reach the leaderboard service: {e}"))?;
700 let body = resp
701 .into_body()
702 .read_to_string()
703 .map_err(|e| format!("Failed to read leaderboard response: {e}"))?;
704 serde_json::from_str(&body).map_err(|e| format!("Invalid leaderboard JSON: {e}"))
705}
706
707pub fn is_cloud_user() -> bool {
708 let path = config_dir().join("plan.txt");
709 std::fs::read_to_string(path).is_ok_and(|p| matches!(p.trim(), "cloud" | "pro"))
710}
711
712pub const PLAN_GRACE_DAYS: i64 = 14;
716
717fn plan_cache_path() -> PathBuf {
718 config_dir().join("plan.json")
719}
720
721#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
724pub struct PlanCache {
725 pub plan: String,
726 pub verified_at: i64,
728}
729
730pub fn save_plan(plan: &str) -> std::io::Result<()> {
731 let dir = config_dir();
732 std::fs::create_dir_all(&dir)?;
733 std::fs::write(dir.join("plan.txt"), plan)?;
735 let cache = PlanCache {
737 plan: plan.to_string(),
738 verified_at: now_unix(),
739 };
740 let json = serde_json::to_string_pretty(&cache).map_err(std::io::Error::other)?;
741 std::fs::write(plan_cache_path(), json)
742}
743
744pub fn cached_plan() -> Option<PlanCache> {
748 if let Ok(data) = std::fs::read_to_string(plan_cache_path())
749 && let Ok(cache) = serde_json::from_str::<PlanCache>(&data)
750 {
751 return Some(cache);
752 }
753 let legacy = std::fs::read_to_string(config_dir().join("plan.txt")).ok()?;
754 Some(PlanCache {
755 plan: legacy.trim().to_string(),
756 verified_at: 0,
757 })
758}
759
760#[derive(Debug, Clone, Copy, PartialEq, Eq)]
763pub enum PlanSource {
764 Live,
766 Cached,
768 Expired,
770 None,
772}
773
774#[derive(Debug, Clone)]
778pub struct EffectivePlan {
779 pub plan: crate::core::billing::Plan,
780 pub source: PlanSource,
781 pub verified_at: Option<i64>,
782 pub grace_days: i64,
783}
784
785#[must_use]
788pub fn plan_within_grace(verified_at: i64, now: i64, grace_days: i64) -> (bool, i64) {
789 let age_days = (now - verified_at).max(0) / 86_400;
790 (age_days <= grace_days, age_days)
791}
792
793#[must_use]
802pub fn resolve_effective_plan_cached() -> EffectivePlan {
803 let grace_days = PLAN_GRACE_DAYS;
804 let Some(cache) = cached_plan() else {
805 return EffectivePlan {
806 plan: crate::core::billing::Plan::Free,
807 source: PlanSource::None,
808 verified_at: None,
809 grace_days,
810 };
811 };
812 let (fresh, _age) = plan_within_grace(cache.verified_at, now_unix(), grace_days);
813 if fresh {
814 EffectivePlan {
815 plan: crate::core::billing::Plan::parse(&cache.plan),
816 source: PlanSource::Cached,
817 verified_at: Some(cache.verified_at),
818 grace_days,
819 }
820 } else {
821 EffectivePlan {
824 plan: crate::core::billing::Plan::Free,
825 source: PlanSource::Expired,
826 verified_at: Some(cache.verified_at),
827 grace_days,
828 }
829 }
830}
831
832#[must_use]
836pub fn refresh_effective_plan() -> EffectivePlan {
837 if is_logged_in()
838 && let Ok(plan_str) = fetch_plan()
839 {
840 let _ = save_plan(&plan_str);
841 return EffectivePlan {
842 plan: crate::core::billing::Plan::parse(&plan_str),
843 source: PlanSource::Live,
844 verified_at: Some(now_unix()),
845 grace_days: PLAN_GRACE_DAYS,
846 };
847 }
848 resolve_effective_plan_cached()
849}
850
851pub fn fetch_plan() -> Result<String, String> {
852 let bearer = auth_bearer_token()?;
853 let url = format!("{}/api/auth/me", api_url());
854
855 let resp = ureq::get(&url)
856 .header("Authorization", &format!("Bearer {bearer}"))
857 .call()
858 .map_err(|e| format!("Failed to check plan: {e}"))?;
859
860 let resp_body = resp
861 .into_body()
862 .read_to_string()
863 .map_err(|e| format!("Failed to read response: {e}"))?;
864
865 let json: serde_json::Value =
866 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
867
868 Ok(json["plan"].as_str().unwrap_or("free").to_string())
869}
870
871pub fn start_checkout(plan: &str, interval: &str) -> Result<String, String> {
876 let bearer = auth_bearer_token()?;
877 let url = format!("{}/api/account/checkout", api_url());
878 let body = serde_json::json!({ "plan": plan, "interval": interval });
879
880 let resp = ureq::post(&url)
881 .header("Authorization", &format!("Bearer {bearer}"))
882 .header("Content-Type", "application/json")
883 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
884 .map_err(|e| format!("Checkout request failed: {e}"))?;
885
886 let resp_body = resp
887 .into_body()
888 .read_to_string()
889 .map_err(|e| format!("Failed to read response: {e}"))?;
890
891 let json: serde_json::Value =
892 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
893
894 json["url"]
895 .as_str()
896 .map(str::to_string)
897 .ok_or_else(|| "Billing did not return a checkout URL.".to_string())
898}
899
900pub fn push_commands(entries: &[serde_json::Value]) -> Result<String, String> {
901 let bearer = auth_bearer_token()?;
902 let url = format!("{}/api/sync/commands", api_url());
903 let body = serde_json::json!({ "commands": entries });
904 let resp = ureq::post(&url)
905 .header("Authorization", &format!("Bearer {bearer}"))
906 .header("Content-Type", "application/json")
907 .header("X-Device-Label", &device_label())
908 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
909 .map_err(|e| format!("Push failed: {e}"))?;
910 let resp_body = resp
911 .into_body()
912 .read_to_string()
913 .map_err(|e| format!("Failed to read response: {e}"))?;
914 let json: serde_json::Value =
915 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
916 Ok(format!(
917 "{} commands synced",
918 json["synced"].as_i64().unwrap_or(0)
919 ))
920}
921
922pub fn push_cep(entries: &[serde_json::Value]) -> Result<String, String> {
923 let bearer = auth_bearer_token()?;
924 let url = format!("{}/api/sync/cep", api_url());
925 let body = serde_json::json!({ "scores": entries });
926 let resp = ureq::post(&url)
927 .header("Authorization", &format!("Bearer {bearer}"))
928 .header("Content-Type", "application/json")
929 .header("X-Device-Label", &device_label())
930 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
931 .map_err(|e| format!("Push failed: {e}"))?;
932 let resp_body = resp
933 .into_body()
934 .read_to_string()
935 .map_err(|e| format!("Failed to read response: {e}"))?;
936 let json: serde_json::Value =
937 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
938 Ok(format!(
939 "{} sessions synced",
940 json["synced"].as_i64().unwrap_or(0)
941 ))
942}
943
944pub fn push_gain(entries: &[serde_json::Value]) -> Result<String, String> {
945 let bearer = auth_bearer_token()?;
946 let url = format!("{}/api/sync/gain", api_url());
947 let body = serde_json::json!({ "scores": entries });
948 let resp = ureq::post(&url)
949 .header("Authorization", &format!("Bearer {bearer}"))
950 .header("Content-Type", "application/json")
951 .header("X-Device-Label", &device_label())
952 .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
953 .map_err(|e| format!("Push failed: {e}"))?;
954 let resp_body = resp
955 .into_body()
956 .read_to_string()
957 .map_err(|e| format!("Failed to read response: {e}"))?;
958 let json: serde_json::Value =
959 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
960 Ok(format!(
961 "{} gain scores synced",
962 json["synced"].as_i64().unwrap_or(0)
963 ))
964}
965
966pub fn push_gotchas(entries: &[serde_json::Value]) -> Result<String, String> {
971 let bearer = auth_bearer_token()?;
972 let key = gotcha_vault_key()?;
973 let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
974 let url = format!("{}/api/sync/gotchas", api_url());
975
976 let resp = ureq::post(&url)
977 .header("Authorization", &format!("Bearer {bearer}"))
978 .header("Content-Type", "application/octet-stream")
979 .header("X-Entry-Count", &entries.len().to_string())
980 .header("X-Device-Label", &device_label())
981 .send(blob.as_slice())
982 .map_err(|e| format!("Push failed: {e}"))?;
983 let resp_body = resp
984 .into_body()
985 .read_to_string()
986 .map_err(|e| format!("Failed to read response: {e}"))?;
987 let json: serde_json::Value =
988 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
989 Ok(format!(
990 "{} gotchas synced (end-to-end encrypted)",
991 json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
992 ))
993}
994
995fn gotcha_vault_key() -> Result<[u8; 32], String> {
998 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
999 if api_key.trim().is_empty() {
1000 return Err("Not logged in. Run: lean-ctx login".into());
1001 }
1002 Ok(crate::core::knowledge_vault::derive_gotcha_vault_key(
1003 &api_key,
1004 ))
1005}
1006
1007pub fn push_buddy(data: &serde_json::Value) -> Result<String, String> {
1008 let bearer = auth_bearer_token()?;
1009 let url = format!("{}/api/sync/buddy", api_url());
1010 let resp = ureq::post(&url)
1011 .header("Authorization", &format!("Bearer {bearer}"))
1012 .header("Content-Type", "application/json")
1013 .header("X-Device-Label", &device_label())
1014 .send(&serde_json::to_vec(data).map_err(|e| format!("JSON error: {e}"))?)
1015 .map_err(|e| format!("Push failed: {e}"))?;
1016 let resp_body = resp
1017 .into_body()
1018 .read_to_string()
1019 .map_err(|e| format!("Failed to read response: {e}"))?;
1020 let _json: serde_json::Value =
1021 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1022 Ok("Buddy synced".to_string())
1023}
1024
1025pub fn push_feedback(entries: &[serde_json::Value]) -> Result<String, String> {
1026 let bearer = auth_bearer_token()?;
1027 let url = format!("{}/api/sync/feedback", api_url());
1028 let resp = ureq::post(&url)
1029 .header("Authorization", &format!("Bearer {bearer}"))
1030 .header("Content-Type", "application/json")
1031 .header("X-Device-Label", &device_label())
1032 .send(&serde_json::to_vec(entries).map_err(|e| format!("JSON error: {e}"))?)
1033 .map_err(|e| format!("Push failed: {e}"))?;
1034 let resp_body = resp
1035 .into_body()
1036 .read_to_string()
1037 .map_err(|e| format!("Failed to read response: {e}"))?;
1038 let json: serde_json::Value =
1039 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1040 Ok(format!(
1041 "{} thresholds synced",
1042 json["synced"].as_i64().unwrap_or(0)
1043 ))
1044}
1045
1046pub fn account_email() -> Option<String> {
1048 load_credentials().map(|c| c.email)
1049}
1050
1051pub fn fetch_account_cloud() -> Result<serde_json::Value, String> {
1055 let bearer = auth_bearer_token()?;
1056 let url = format!("{}/api/account/cloud", api_url());
1057
1058 let resp = ureq::get(&url)
1059 .header("Authorization", &format!("Bearer {bearer}"))
1060 .call()
1061 .map_err(|e| format!("Status fetch failed: {e}"))?;
1062
1063 let resp_body = resp
1064 .into_body()
1065 .read_to_string()
1066 .map_err(|e| format!("Failed to read response: {e}"))?;
1067
1068 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))
1069}
1070
1071pub fn pull_knowledge() -> Result<Vec<serde_json::Value>, String> {
1074 let bearer = auth_bearer_token()?;
1075 let url = format!("{}/api/sync/knowledge", api_url());
1076
1077 match ureq::get(&url)
1079 .header("Authorization", &format!("Bearer {bearer}"))
1080 .header("Accept", "application/octet-stream")
1081 .call()
1082 {
1083 Ok(resp) => {
1084 let is_blob = resp
1085 .headers()
1086 .get("content-type")
1087 .and_then(|v| v.to_str().ok())
1088 .is_some_and(|v| v.starts_with("application/octet-stream"));
1089 if is_blob {
1090 let mut blob = Vec::new();
1091 use std::io::Read;
1092 resp.into_body()
1093 .into_reader()
1094 .read_to_end(&mut blob)
1095 .map_err(|e| format!("Failed to read vault: {e}"))?;
1096 let key = knowledge_vault_key()?;
1097 return crate::core::knowledge_vault::open(&blob, &key).map_err(|e| e.to_string());
1098 }
1099 let body = resp
1102 .into_body()
1103 .read_to_string()
1104 .map_err(|e| format!("Failed to read response: {e}"))?;
1105 return serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"));
1106 }
1107 Err(ureq::Error::StatusCode(404)) => {}
1109 Err(e) => return Err(format!("Pull failed: {e}")),
1110 }
1111
1112 let resp = ureq::get(&url)
1113 .header("Authorization", &format!("Bearer {bearer}"))
1114 .call()
1115 .map_err(|e| format!("Pull failed: {e}"))?;
1116
1117 let resp_body = resp
1118 .into_body()
1119 .read_to_string()
1120 .map_err(|e| format!("Failed to read response: {e}"))?;
1121
1122 let entries: Vec<serde_json::Value> =
1123 serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1124
1125 Ok(entries)
1126}
1127
1128fn index_bundle_key() -> Result<[u8; 32], String> {
1136 let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
1137 if api_key.trim().is_empty() {
1138 return Err("Not logged in. Run: lean-ctx login".into());
1139 }
1140 Ok(crate::core::index_bundle::derive_key(&api_key))
1141}
1142
1143pub fn push_index_bundle(project_root: &std::path::Path) -> Result<(String, u64), String> {
1146 let (container, manifest) =
1147 crate::core::index_bundle::pack(project_root).map_err(|e| e.to_string())?;
1148 let blob = crate::core::index_bundle::encrypt(&container, &index_bundle_key()?)
1149 .map_err(|e| e.to_string())?;
1150
1151 let bearer = auth_bearer_token()?;
1152 let url = format!("{}/api/sync/index/{}", api_url(), manifest.project_hash);
1153 let resp = ureq::put(&url)
1154 .header("Authorization", &format!("Bearer {bearer}"))
1155 .header("Content-Type", "application/octet-stream")
1156 .header("X-Device-Label", &device_label())
1157 .send(blob.as_slice())
1158 .map_err(|e| match e {
1159 ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1160 Run: lean-ctx cloud upgrade --plan pro"
1161 .to_string(),
1162 ureq::Error::StatusCode(413) => {
1163 "Quota exceeded — the push was blocked (nothing is billed). \
1164 Free space with `lean-ctx sync index status` / delete, then retry."
1165 .to_string()
1166 }
1167 other => format!("Push failed: {other}"),
1168 })?;
1169
1170 let body = resp
1171 .into_body()
1172 .read_to_string()
1173 .map_err(|e| format!("Failed to read response: {e}"))?;
1174 let _ack: serde_json::Value =
1175 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
1176 Ok((manifest.project_hash, blob.len() as u64))
1177}
1178
1179pub fn pull_index_bundle(
1182 project_root: &std::path::Path,
1183) -> Result<crate::core::index_bundle::BundleManifest, String> {
1184 let project_hash = crate::core::index_namespace::namespace_hash(project_root);
1185 let bearer = auth_bearer_token()?;
1186 let url = format!("{}/api/sync/index/{project_hash}", api_url());
1187
1188 let resp = ureq::get(&url)
1189 .header("Authorization", &format!("Bearer {bearer}"))
1190 .call()
1191 .map_err(|e| match e {
1192 ureq::Error::StatusCode(404) => format!(
1193 "No hosted index for this project yet ({project_hash}). \
1194 Push one from a device with a built index: lean-ctx sync index push"
1195 ),
1196 ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1197 Run: lean-ctx cloud upgrade --plan pro"
1198 .to_string(),
1199 other => format!("Pull failed: {other}"),
1200 })?;
1201
1202 let mut blob = Vec::new();
1203 use std::io::Read;
1204 resp.into_body()
1205 .into_reader()
1206 .read_to_end(&mut blob)
1207 .map_err(|e| format!("Failed to read bundle: {e}"))?;
1208
1209 let container = crate::core::index_bundle::decrypt(&blob, &index_bundle_key()?)
1210 .map_err(|e| e.to_string())?;
1211 crate::core::index_bundle::unpack(project_root, &container).map_err(|e| e.to_string())
1212}
1213
1214pub fn index_bundle_status() -> Result<serde_json::Value, String> {
1216 let bearer = auth_bearer_token()?;
1217 let url = format!("{}/api/sync/index", api_url());
1218 let resp = ureq::get(&url)
1219 .header("Authorization", &format!("Bearer {bearer}"))
1220 .call()
1221 .map_err(|e| format!("Status fetch failed: {e}"))?;
1222 let body = resp
1223 .into_body()
1224 .read_to_string()
1225 .map_err(|e| format!("Failed to read response: {e}"))?;
1226 serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))
1227}
1228
1229#[cfg(test)]
1230mod tests {
1231 use super::*;
1232 use crate::core::billing::Plan;
1233 #[cfg(unix)]
1237 use crate::core::data_dir::test_env_lock;
1238
1239 #[test]
1240 fn existing_card_publish_response_carries_recovery_challenge() {
1241 let card: PublishedCard = serde_json::from_value(serde_json::json!({
1242 "id": "card-1",
1243 "url": "https://leanctx.com/w/card-1",
1244 "edit_token_challenge": "nonce-1",
1245 "challenge_expires_in_secs": 300
1246 }))
1247 .unwrap();
1248 assert!(card.edit_token.is_none());
1249 assert_eq!(card.edit_token_challenge.as_deref(), Some("nonce-1"));
1250 assert_eq!(card.challenge_expires_in_secs, Some(300));
1251 assert!(!card.account_claimed);
1252 }
1253
1254 #[test]
1255 fn grace_window_boundaries_are_inclusive_and_skew_safe() {
1256 let now = 1_000_000_000;
1257 let day = 86_400;
1258 assert_eq!(plan_within_grace(now, now, 14), (true, 0));
1259 assert_eq!(plan_within_grace(now - 14 * day, now, 14), (true, 14));
1261 assert_eq!(plan_within_grace(now - 15 * day, now, 14), (false, 15));
1263 assert_eq!(plan_within_grace(now + day, now, 14), (true, 0));
1265 }
1266
1267 #[test]
1268 fn plan_cache_roundtrips_through_json() {
1269 let c = PlanCache {
1270 plan: "pro".into(),
1271 verified_at: 42,
1272 };
1273 let back: PlanCache = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
1274 assert_eq!(back.plan, "pro");
1275 assert_eq!(back.verified_at, 42);
1276 }
1277
1278 #[test]
1279 fn cached_resolve_grants_within_grace_then_expires_to_free() {
1280 let _iso = crate::core::data_dir::isolated_data_dir();
1283
1284 save_plan("pro").unwrap();
1286 let eff = resolve_effective_plan_cached();
1287 assert_eq!(eff.plan, Plan::Pro);
1288 assert_eq!(eff.source, PlanSource::Cached);
1289
1290 let stale = PlanCache {
1292 plan: "pro".into(),
1293 verified_at: now_unix() - (PLAN_GRACE_DAYS + 1) * 86_400,
1294 };
1295 std::fs::write(plan_cache_path(), serde_json::to_string(&stale).unwrap()).unwrap();
1296 let eff = resolve_effective_plan_cached();
1297 assert_eq!(eff.plan, Plan::Free);
1298 assert_eq!(eff.source, PlanSource::Expired);
1299 }
1300
1301 #[test]
1302 fn no_cache_resolves_to_free_none() {
1303 let _iso = crate::core::data_dir::isolated_data_dir();
1304 let eff = resolve_effective_plan_cached();
1305 assert_eq!(eff.plan, Plan::Free);
1306 assert_eq!(eff.source, PlanSource::None);
1307 }
1308
1309 #[cfg(unix)]
1311 #[test]
1312 fn credentials_are_written_owner_only_and_atomic() {
1313 use std::os::unix::fs::PermissionsExt;
1314 let _env = test_env_lock();
1315 let tmp = tempfile::tempdir().unwrap();
1316 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1317
1318 save_credentials("sk-test-key", "user-1", "a@b.c").unwrap();
1319
1320 let path = credentials_path();
1321 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1322 assert_eq!(mode & 0o777, 0o600, "credentials.json must be 0o600");
1323
1324 let dir_mode = std::fs::metadata(config_dir())
1325 .unwrap()
1326 .permissions()
1327 .mode();
1328 assert_eq!(
1329 dir_mode & 0o077,
1330 0,
1331 "cloud dir must not be group/world accessible"
1332 );
1333
1334 let leftovers: Vec<_> = std::fs::read_dir(config_dir())
1336 .unwrap()
1337 .filter_map(Result::ok)
1338 .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
1339 .collect();
1340 assert!(leftovers.is_empty(), "atomic write must not leak tmp files");
1341
1342 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1343 }
1344
1345 #[cfg(unix)]
1347 #[test]
1348 fn loose_credential_permissions_are_tightened_on_load() {
1349 use std::os::unix::fs::PermissionsExt;
1350 let _env = test_env_lock();
1351 let tmp = tempfile::tempdir().unwrap();
1352 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1353
1354 std::fs::create_dir_all(config_dir()).unwrap();
1355 let path = credentials_path();
1356 std::fs::write(&path, "{}").unwrap();
1357 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
1358
1359 let _ = load_credentials();
1360
1361 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1362 assert_eq!(
1363 mode & 0o777,
1364 0o600,
1365 "legacy file must be tightened to 0o600"
1366 );
1367
1368 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1369 }
1370
1371 #[test]
1372 fn legacy_plan_txt_is_migrated_but_treated_as_stale() {
1373 let _iso = crate::core::data_dir::isolated_data_dir();
1374 std::fs::create_dir_all(config_dir()).unwrap();
1376 std::fs::write(config_dir().join("plan.txt"), "team").unwrap();
1377 let cache = cached_plan().unwrap();
1378 assert_eq!(cache.plan, "team");
1379 assert_eq!(cache.verified_at, 0);
1380 assert_eq!(resolve_effective_plan_cached().source, PlanSource::Expired);
1381 }
1382}