Skip to main content

lean_ctx/
cloud_client.rs

1use std::path::PathBuf;
2
3fn config_dir() -> PathBuf {
4    // GH #439: data_dir() already honors LEAN_CTX_DATA_DIR + legacy/XDG, so the
5    // cloud cache follows the migration instead of pinning ~/.lean-ctx.
6    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    // One-time migration for files written before permissions were enforced:
37    // tighten anything looser than owner-only on every load.
38    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
51/// Writes a secret file atomically (tmp + rename) with owner-only permissions
52/// (0o600 on Unix), so credentials are never world-readable — not even
53/// transiently between create and chmod.
54fn 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    // Access tokens are bound to a client and should be re-fetched after login changes.
130    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
151/// This machine's display label for the device overview (GL #387): the
152/// hostname, attached as `X-Device-Label` to every sync push. Display
153/// metadata only — the server treats it as an opaque, sanitized string and
154/// silently skips tracking when it is empty.
155fn 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/// Result of a successful Wrapped publish (`POST /api/wrapped`). The `edit_token` is returned
407/// (and must be stored to delete/claim later) only on a *fresh* insert; on a signed re-publish
408/// the server updates the existing card in place and omits it (the client keeps the stored one).
409#[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
417/// Publish a whitelisted Wrapped payload. Accepts either a bare payload (legacy anonymous) or a
418/// signed envelope `{payload_json, public_key, signature}` (login-less identity → server upsert).
419/// No account auth; the server rate-limits per IP. Contract: `docs/contracts/wrapped-permalink-v1.md`.
420pub 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
436/// Delete a previously published card using its one-time `edit_token` (sent as `X-Edit-Token`).
437pub 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
447/// Push the knowledge store as a zero-knowledge vault (GL #467): entries are
448/// sealed client-side (XChaCha20-Poly1305, domain-separated HKDF key) — the
449/// backend stores ciphertext and can never read them. The first vault push
450/// also purges the account's legacy plaintext rows server-side.
451pub 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
479/// The account's knowledge-vault key — same stable-API-key derivation rule as
480/// [`index_bundle_key`], different HKDF domain (`knowledge-vault-v1`).
481fn 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
531/// Days a cached plan keeps granting its hosted entitlements while the billing
532/// backend is unreachable. Generous on purpose: a network blip or a weekend
533/// offline must never silently demote a paying user to Free.
534pub const PLAN_GRACE_DAYS: i64 = 14;
535
536fn plan_cache_path() -> PathBuf {
537    config_dir().join("plan.json")
538}
539
540/// The locally cached plan plus *when* it was last confirmed against the billing
541/// backend. The timestamp is what powers offline grace.
542#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
543pub struct PlanCache {
544    pub plan: String,
545    /// Unix seconds of the last successful backend confirmation.
546    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    // Legacy flat file kept for back-compat (`is_cloud_user` still reads it).
553    std::fs::write(dir.join("plan.txt"), plan)?;
554    // Structured cache carrying the verification time for offline grace.
555    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
563/// The cached plan, if any. Prefers the structured `plan.json`; falls back to a
564/// legacy `plan.txt` (no timestamp → `verified_at = 0`, i.e. immediately past
565/// grace until the next successful refresh re-stamps it).
566pub 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/// Where an effective plan came from — drives the wording in `billing status`
580/// and the dashboard badge.
581#[derive(Debug, Clone, Copy, PartialEq, Eq)]
582pub enum PlanSource {
583    /// Just confirmed against the backend this run.
584    Live,
585    /// Served from the local cache and still within the grace window.
586    Cached,
587    /// Cached confirmation is past the grace window → demoted to Free.
588    Expired,
589    /// No cached plan at all (never logged in / never synced) → Free.
590    None,
591}
592
593/// A resolved plan plus its provenance. The plan here is only ever used for
594/// *display* and for gating **hosted** surfaces — it never gates a local
595/// capability (Local-Free Invariant; the local engine has no entitlement checks).
596#[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/// Pure grace check (no clock/IO) so it is unit-testable: is a plan confirmed at
605/// `verified_at` still within `grace_days` of `now`? Returns the age in days too.
606#[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/// Resolve the effective plan from the **local cache only** (no network), applying
613/// the offline-grace policy. Use this on hot paths (dashboard requests); use
614/// [`refresh_effective_plan`] when a live confirmation is acceptable.
615#[must_use]
616pub fn resolve_effective_plan_cached() -> EffectivePlan {
617    let grace_days = PLAN_GRACE_DAYS;
618    let Some(cache) = cached_plan() else {
619        return EffectivePlan {
620            plan: crate::core::billing::Plan::Free,
621            source: PlanSource::None,
622            verified_at: None,
623            grace_days,
624        };
625    };
626    let (fresh, _age) = plan_within_grace(cache.verified_at, now_unix(), grace_days);
627    if fresh {
628        EffectivePlan {
629            plan: crate::core::billing::Plan::parse(&cache.plan),
630            source: PlanSource::Cached,
631            verified_at: Some(cache.verified_at),
632            grace_days,
633        }
634    } else {
635        // Fail closed for *hosted* entitlements once grace lapses. Local features
636        // remain unaffected — they are never gated.
637        EffectivePlan {
638            plan: crate::core::billing::Plan::Free,
639            source: PlanSource::Expired,
640            verified_at: Some(cache.verified_at),
641            grace_days,
642        }
643    }
644}
645
646/// Best-effort *live* resolve: try the backend (refreshing the cache on success),
647/// otherwise fall back to the cached-with-grace plan. Suitable for explicit
648/// commands like `lean-ctx billing status` where a network round-trip is fine.
649#[must_use]
650pub fn refresh_effective_plan() -> EffectivePlan {
651    if is_logged_in()
652        && let Ok(plan_str) = fetch_plan()
653    {
654        let _ = save_plan(&plan_str);
655        return EffectivePlan {
656            plan: crate::core::billing::Plan::parse(&plan_str),
657            source: PlanSource::Live,
658            verified_at: Some(now_unix()),
659            grace_days: PLAN_GRACE_DAYS,
660        };
661    }
662    resolve_effective_plan_cached()
663}
664
665pub fn fetch_plan() -> Result<String, String> {
666    let bearer = auth_bearer_token()?;
667    let url = format!("{}/api/auth/me", api_url());
668
669    let resp = ureq::get(&url)
670        .header("Authorization", &format!("Bearer {bearer}"))
671        .call()
672        .map_err(|e| format!("Failed to check plan: {e}"))?;
673
674    let resp_body = resp
675        .into_body()
676        .read_to_string()
677        .map_err(|e| format!("Failed to read response: {e}"))?;
678
679    let json: serde_json::Value =
680        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
681
682    Ok(json["plan"].as_str().unwrap_or("free").to_string())
683}
684
685/// Start a Stripe Checkout session for the logged-in account and return the
686/// hosted URL to open. `plan` is e.g. `"pro"` or `"team"`; `interval` is
687/// `"monthly"` or `"yearly"`. The open backend proxies this to the private
688/// billing plane (which returns `503` when billing is not configured).
689pub fn start_checkout(plan: &str, interval: &str) -> Result<String, String> {
690    let bearer = auth_bearer_token()?;
691    let url = format!("{}/api/account/checkout", api_url());
692    let body = serde_json::json!({ "plan": plan, "interval": interval });
693
694    let resp = ureq::post(&url)
695        .header("Authorization", &format!("Bearer {bearer}"))
696        .header("Content-Type", "application/json")
697        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
698        .map_err(|e| format!("Checkout request failed: {e}"))?;
699
700    let resp_body = resp
701        .into_body()
702        .read_to_string()
703        .map_err(|e| format!("Failed to read response: {e}"))?;
704
705    let json: serde_json::Value =
706        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
707
708    json["url"]
709        .as_str()
710        .map(str::to_string)
711        .ok_or_else(|| "Billing did not return a checkout URL.".to_string())
712}
713
714pub fn push_commands(entries: &[serde_json::Value]) -> Result<String, String> {
715    let bearer = auth_bearer_token()?;
716    let url = format!("{}/api/sync/commands", api_url());
717    let body = serde_json::json!({ "commands": entries });
718    let resp = ureq::post(&url)
719        .header("Authorization", &format!("Bearer {bearer}"))
720        .header("Content-Type", "application/json")
721        .header("X-Device-Label", &device_label())
722        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
723        .map_err(|e| format!("Push failed: {e}"))?;
724    let resp_body = resp
725        .into_body()
726        .read_to_string()
727        .map_err(|e| format!("Failed to read response: {e}"))?;
728    let json: serde_json::Value =
729        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
730    Ok(format!(
731        "{} commands synced",
732        json["synced"].as_i64().unwrap_or(0)
733    ))
734}
735
736pub fn push_cep(entries: &[serde_json::Value]) -> Result<String, String> {
737    let bearer = auth_bearer_token()?;
738    let url = format!("{}/api/sync/cep", api_url());
739    let body = serde_json::json!({ "scores": entries });
740    let resp = ureq::post(&url)
741        .header("Authorization", &format!("Bearer {bearer}"))
742        .header("Content-Type", "application/json")
743        .header("X-Device-Label", &device_label())
744        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
745        .map_err(|e| format!("Push failed: {e}"))?;
746    let resp_body = resp
747        .into_body()
748        .read_to_string()
749        .map_err(|e| format!("Failed to read response: {e}"))?;
750    let json: serde_json::Value =
751        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
752    Ok(format!(
753        "{} sessions synced",
754        json["synced"].as_i64().unwrap_or(0)
755    ))
756}
757
758pub fn push_gain(entries: &[serde_json::Value]) -> Result<String, String> {
759    let bearer = auth_bearer_token()?;
760    let url = format!("{}/api/sync/gain", api_url());
761    let body = serde_json::json!({ "scores": entries });
762    let resp = ureq::post(&url)
763        .header("Authorization", &format!("Bearer {bearer}"))
764        .header("Content-Type", "application/json")
765        .header("X-Device-Label", &device_label())
766        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
767        .map_err(|e| format!("Push failed: {e}"))?;
768    let resp_body = resp
769        .into_body()
770        .read_to_string()
771        .map_err(|e| format!("Failed to read response: {e}"))?;
772    let json: serde_json::Value =
773        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
774    Ok(format!(
775        "{} gain scores synced",
776        json["synced"].as_i64().unwrap_or(0)
777    ))
778}
779
780/// Push gotchas as a zero-knowledge vault (GL #467 follow-up): sealed
781/// client-side under the `gotcha-vault-v1` HKDF domain — the backend stores
782/// ciphertext only and purges the account's legacy plaintext rows on the
783/// first vault push.
784pub fn push_gotchas(entries: &[serde_json::Value]) -> Result<String, String> {
785    let bearer = auth_bearer_token()?;
786    let key = gotcha_vault_key()?;
787    let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
788    let url = format!("{}/api/sync/gotchas", api_url());
789
790    let resp = ureq::post(&url)
791        .header("Authorization", &format!("Bearer {bearer}"))
792        .header("Content-Type", "application/octet-stream")
793        .header("X-Entry-Count", &entries.len().to_string())
794        .header("X-Device-Label", &device_label())
795        .send(blob.as_slice())
796        .map_err(|e| format!("Push failed: {e}"))?;
797    let resp_body = resp
798        .into_body()
799        .read_to_string()
800        .map_err(|e| format!("Failed to read response: {e}"))?;
801    let json: serde_json::Value =
802        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
803    Ok(format!(
804        "{} gotchas synced (end-to-end encrypted)",
805        json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
806    ))
807}
808
809/// The account's gotcha-vault key — own HKDF domain (`gotcha-vault-v1`),
810/// derivation rule identical to [`knowledge_vault_key`].
811fn gotcha_vault_key() -> Result<[u8; 32], String> {
812    let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
813    if api_key.trim().is_empty() {
814        return Err("Not logged in. Run: lean-ctx login".into());
815    }
816    Ok(crate::core::knowledge_vault::derive_gotcha_vault_key(
817        &api_key,
818    ))
819}
820
821pub fn push_buddy(data: &serde_json::Value) -> Result<String, String> {
822    let bearer = auth_bearer_token()?;
823    let url = format!("{}/api/sync/buddy", api_url());
824    let resp = ureq::post(&url)
825        .header("Authorization", &format!("Bearer {bearer}"))
826        .header("Content-Type", "application/json")
827        .header("X-Device-Label", &device_label())
828        .send(&serde_json::to_vec(data).map_err(|e| format!("JSON error: {e}"))?)
829        .map_err(|e| format!("Push failed: {e}"))?;
830    let resp_body = resp
831        .into_body()
832        .read_to_string()
833        .map_err(|e| format!("Failed to read response: {e}"))?;
834    let _json: serde_json::Value =
835        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
836    Ok("Buddy synced".to_string())
837}
838
839pub fn push_feedback(entries: &[serde_json::Value]) -> Result<String, String> {
840    let bearer = auth_bearer_token()?;
841    let url = format!("{}/api/sync/feedback", api_url());
842    let resp = ureq::post(&url)
843        .header("Authorization", &format!("Bearer {bearer}"))
844        .header("Content-Type", "application/json")
845        .header("X-Device-Label", &device_label())
846        .send(&serde_json::to_vec(entries).map_err(|e| format!("JSON error: {e}"))?)
847        .map_err(|e| format!("Push failed: {e}"))?;
848    let resp_body = resp
849        .into_body()
850        .read_to_string()
851        .map_err(|e| format!("Failed to read response: {e}"))?;
852    let json: serde_json::Value =
853        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
854    Ok(format!(
855        "{} thresholds synced",
856        json["synced"].as_i64().unwrap_or(0)
857    ))
858}
859
860/// The signed-in account's email, for status displays.
861pub fn account_email() -> Option<String> {
862    load_credentials().map(|c| c.email)
863}
864
865/// `GET /api/account/cloud` — the Personal Cloud dashboard payload (entitlement
866/// gate, per-bucket sync footprint, buddy, usage totals). Powers
867/// `lean-ctx cloud status`, mirroring what leanctx.com/account/cloud shows.
868pub fn fetch_account_cloud() -> Result<serde_json::Value, String> {
869    let bearer = auth_bearer_token()?;
870    let url = format!("{}/api/account/cloud", api_url());
871
872    let resp = ureq::get(&url)
873        .header("Authorization", &format!("Bearer {bearer}"))
874        .call()
875        .map_err(|e| format!("Status fetch failed: {e}"))?;
876
877    let resp_body = resp
878        .into_body()
879        .read_to_string()
880        .map_err(|e| format!("Failed to read response: {e}"))?;
881
882    serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))
883}
884
885/// Pull the knowledge store: vault-first (encrypted blob, decrypted locally),
886/// with a legacy plaintext fallback for accounts that never pushed a vault.
887pub fn pull_knowledge() -> Result<Vec<serde_json::Value>, String> {
888    let bearer = auth_bearer_token()?;
889    let url = format!("{}/api/sync/knowledge", api_url());
890
891    // Vault path (GL #467).
892    match ureq::get(&url)
893        .header("Authorization", &format!("Bearer {bearer}"))
894        .header("Accept", "application/octet-stream")
895        .call()
896    {
897        Ok(resp) => {
898            let is_blob = resp
899                .headers()
900                .get("content-type")
901                .and_then(|v| v.to_str().ok())
902                .is_some_and(|v| v.starts_with("application/octet-stream"));
903            if is_blob {
904                let mut blob = Vec::new();
905                use std::io::Read;
906                resp.into_body()
907                    .into_reader()
908                    .read_to_end(&mut blob)
909                    .map_err(|e| format!("Failed to read vault: {e}"))?;
910                let key = knowledge_vault_key()?;
911                return crate::core::knowledge_vault::open(&blob, &key).map_err(|e| e.to_string());
912            }
913            // Pre-vault server ignored the Accept header and answered with
914            // the legacy JSON listing — parse it directly.
915            let body = resp
916                .into_body()
917                .read_to_string()
918                .map_err(|e| format!("Failed to read response: {e}"))?;
919            return serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"));
920        }
921        // No vault yet → fall through to the legacy listing.
922        Err(ureq::Error::StatusCode(404)) => {}
923        Err(e) => return Err(format!("Pull failed: {e}")),
924    }
925
926    let resp = ureq::get(&url)
927        .header("Authorization", &format!("Bearer {bearer}"))
928        .call()
929        .map_err(|e| format!("Pull failed: {e}"))?;
930
931    let resp_body = resp
932        .into_body()
933        .read_to_string()
934        .map_err(|e| format!("Failed to read response: {e}"))?;
935
936    let entries: Vec<serde_json::Value> =
937        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
938
939    Ok(entries)
940}
941
942// ── Hosted Personal Index (GL #392) ──────────────────────────────────────────
943// Contract: docs/contracts/hosted-personal-index-v1.md. Bundles are encrypted
944// client-side (core::index_bundle); the backend only ever sees ciphertext.
945
946/// The account's bundle encryption key, HKDF-derived from the stable API key
947/// (never from the rotating OAuth token — the key must be identical on every
948/// logged-in device).
949fn index_bundle_key() -> Result<[u8; 32], String> {
950    let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
951    if api_key.trim().is_empty() {
952        return Err("Not logged in. Run: lean-ctx login".into());
953    }
954    Ok(crate::core::index_bundle::derive_key(&api_key))
955}
956
957/// Pack, encrypt and upload the project's index bundle.
958/// Returns `(project_hash, encrypted_size_bytes)`.
959pub fn push_index_bundle(project_root: &std::path::Path) -> Result<(String, u64), String> {
960    let (container, manifest) =
961        crate::core::index_bundle::pack(project_root).map_err(|e| e.to_string())?;
962    let blob = crate::core::index_bundle::encrypt(&container, &index_bundle_key()?)
963        .map_err(|e| e.to_string())?;
964
965    let bearer = auth_bearer_token()?;
966    let url = format!("{}/api/sync/index/{}", api_url(), manifest.project_hash);
967    let resp = ureq::put(&url)
968        .header("Authorization", &format!("Bearer {bearer}"))
969        .header("Content-Type", "application/octet-stream")
970        .header("X-Device-Label", &device_label())
971        .send(blob.as_slice())
972        .map_err(|e| match e {
973            ureq::Error::StatusCode(402) => {
974                "Hosted index requires lean-ctx Pro. Run: lean-ctx upgrade".to_string()
975            }
976            ureq::Error::StatusCode(413) => {
977                "Quota exceeded — the push was blocked (nothing is billed). \
978                 Free space with `lean-ctx sync index status` / delete, then retry."
979                    .to_string()
980            }
981            other => format!("Push failed: {other}"),
982        })?;
983
984    let body = resp
985        .into_body()
986        .read_to_string()
987        .map_err(|e| format!("Failed to read response: {e}"))?;
988    let _ack: serde_json::Value =
989        serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
990    Ok((manifest.project_hash, blob.len() as u64))
991}
992
993/// Download, decrypt and unpack the hosted bundle for this project.
994/// Returns the bundle manifest on success.
995pub fn pull_index_bundle(
996    project_root: &std::path::Path,
997) -> Result<crate::core::index_bundle::BundleManifest, String> {
998    let project_hash = crate::core::index_namespace::namespace_hash(project_root);
999    let bearer = auth_bearer_token()?;
1000    let url = format!("{}/api/sync/index/{project_hash}", api_url());
1001
1002    let resp = ureq::get(&url)
1003        .header("Authorization", &format!("Bearer {bearer}"))
1004        .call()
1005        .map_err(|e| match e {
1006            ureq::Error::StatusCode(404) => format!(
1007                "No hosted index for this project yet ({project_hash}). \
1008                 Push one from a device with a built index: lean-ctx sync index push"
1009            ),
1010            ureq::Error::StatusCode(402) => {
1011                "Hosted index requires lean-ctx Pro. Run: lean-ctx upgrade".to_string()
1012            }
1013            other => format!("Pull failed: {other}"),
1014        })?;
1015
1016    let mut blob = Vec::new();
1017    use std::io::Read;
1018    resp.into_body()
1019        .into_reader()
1020        .read_to_end(&mut blob)
1021        .map_err(|e| format!("Failed to read bundle: {e}"))?;
1022
1023    let container = crate::core::index_bundle::decrypt(&blob, &index_bundle_key()?)
1024        .map_err(|e| e.to_string())?;
1025    crate::core::index_bundle::unpack(project_root, &container).map_err(|e| e.to_string())
1026}
1027
1028/// `GET /api/sync/index` — hosted-bucket listing + quota usage for the account.
1029pub fn index_bundle_status() -> Result<serde_json::Value, String> {
1030    let bearer = auth_bearer_token()?;
1031    let url = format!("{}/api/sync/index", api_url());
1032    let resp = ureq::get(&url)
1033        .header("Authorization", &format!("Bearer {bearer}"))
1034        .call()
1035        .map_err(|e| format!("Status fetch failed: {e}"))?;
1036    let body = resp
1037        .into_body()
1038        .read_to_string()
1039        .map_err(|e| format!("Failed to read response: {e}"))?;
1040    serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))
1041}
1042
1043#[cfg(test)]
1044mod tests {
1045    use super::*;
1046    use crate::core::billing::Plan;
1047    use crate::core::data_dir::test_env_lock;
1048
1049    #[test]
1050    fn grace_window_boundaries_are_inclusive_and_skew_safe() {
1051        let now = 1_000_000_000;
1052        let day = 86_400;
1053        assert_eq!(plan_within_grace(now, now, 14), (true, 0));
1054        // Exactly at the edge stays valid (inclusive).
1055        assert_eq!(plan_within_grace(now - 14 * day, now, 14), (true, 14));
1056        // One day past → expired.
1057        assert_eq!(plan_within_grace(now - 15 * day, now, 14), (false, 15));
1058        // Clock skew (future timestamp) is clamped to age 0, never negative.
1059        assert_eq!(plan_within_grace(now + day, now, 14), (true, 0));
1060    }
1061
1062    #[test]
1063    fn plan_cache_roundtrips_through_json() {
1064        let c = PlanCache {
1065            plan: "pro".into(),
1066            verified_at: 42,
1067        };
1068        let back: PlanCache = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
1069        assert_eq!(back.plan, "pro");
1070        assert_eq!(back.verified_at, 42);
1071    }
1072
1073    #[test]
1074    fn cached_resolve_grants_within_grace_then_expires_to_free() {
1075        let _env = test_env_lock();
1076        let tmp = tempfile::tempdir().unwrap();
1077        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1078
1079        // A fresh save is served from cache, within grace, at full plan.
1080        save_plan("pro").unwrap();
1081        let eff = resolve_effective_plan_cached();
1082        assert_eq!(eff.plan, Plan::Pro);
1083        assert_eq!(eff.source, PlanSource::Cached);
1084
1085        // Backdate beyond grace → hosted entitlements fail closed to Free.
1086        let stale = PlanCache {
1087            plan: "pro".into(),
1088            verified_at: now_unix() - (PLAN_GRACE_DAYS + 1) * 86_400,
1089        };
1090        std::fs::write(plan_cache_path(), serde_json::to_string(&stale).unwrap()).unwrap();
1091        let eff = resolve_effective_plan_cached();
1092        assert_eq!(eff.plan, Plan::Free);
1093        assert_eq!(eff.source, PlanSource::Expired);
1094
1095        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1096    }
1097
1098    #[test]
1099    fn no_cache_resolves_to_free_none() {
1100        let _env = test_env_lock();
1101        let tmp = tempfile::tempdir().unwrap();
1102        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1103        let eff = resolve_effective_plan_cached();
1104        assert_eq!(eff.plan, Plan::Free);
1105        assert_eq!(eff.source, PlanSource::None);
1106        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1107    }
1108
1109    // P0-2 (#414): credentials must be owner-only on disk.
1110    #[cfg(unix)]
1111    #[test]
1112    fn credentials_are_written_owner_only_and_atomic() {
1113        use std::os::unix::fs::PermissionsExt;
1114        let _env = test_env_lock();
1115        let tmp = tempfile::tempdir().unwrap();
1116        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1117
1118        save_credentials("sk-test-key", "user-1", "a@b.c").unwrap();
1119
1120        let path = credentials_path();
1121        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1122        assert_eq!(mode & 0o777, 0o600, "credentials.json must be 0o600");
1123
1124        let dir_mode = std::fs::metadata(config_dir())
1125            .unwrap()
1126            .permissions()
1127            .mode();
1128        assert_eq!(
1129            dir_mode & 0o077,
1130            0,
1131            "cloud dir must not be group/world accessible"
1132        );
1133
1134        // No tmp file leftovers from the atomic write.
1135        let leftovers: Vec<_> = std::fs::read_dir(config_dir())
1136            .unwrap()
1137            .filter_map(Result::ok)
1138            .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
1139            .collect();
1140        assert!(leftovers.is_empty(), "atomic write must not leak tmp files");
1141
1142        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1143    }
1144
1145    // P0-2 (#414): pre-existing world-readable credentials are tightened on load.
1146    #[cfg(unix)]
1147    #[test]
1148    fn loose_credential_permissions_are_tightened_on_load() {
1149        use std::os::unix::fs::PermissionsExt;
1150        let _env = test_env_lock();
1151        let tmp = tempfile::tempdir().unwrap();
1152        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1153
1154        std::fs::create_dir_all(config_dir()).unwrap();
1155        let path = credentials_path();
1156        std::fs::write(&path, "{}").unwrap();
1157        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
1158
1159        let _ = load_credentials();
1160
1161        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1162        assert_eq!(
1163            mode & 0o777,
1164            0o600,
1165            "legacy file must be tightened to 0o600"
1166        );
1167
1168        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1169    }
1170
1171    #[test]
1172    fn legacy_plan_txt_is_migrated_but_treated_as_stale() {
1173        let _env = test_env_lock();
1174        let tmp = tempfile::tempdir().unwrap();
1175        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1176        // Only the legacy flat file exists (no timestamp) → past grace until refresh.
1177        std::fs::create_dir_all(config_dir()).unwrap();
1178        std::fs::write(config_dir().join("plan.txt"), "team").unwrap();
1179        let cache = cached_plan().unwrap();
1180        assert_eq!(cache.plan, "team");
1181        assert_eq!(cache.verified_at, 0);
1182        assert_eq!(resolve_effective_plan_cached().source, PlanSource::Expired);
1183        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1184    }
1185}