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/// Send an anonymous telemetry heartbeat. No authentication required.
407/// Payload: installation_id (random UUID), version, OS, arch — nothing else.
408pub 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
427/// Result of a successful Wrapped publish (`POST /api/wrapped`). The `edit_token` is returned
428/// (and must be stored to delete/claim later) only on a *fresh* insert; on a signed re-publish
429/// the server updates the existing card in place and omits it (the client keeps the stored one).
430#[derive(serde::Deserialize)]
431pub struct PublishedCard {
432    pub id: String,
433    #[serde(default)]
434    pub edit_token: Option<String>,
435    #[serde(default)]
436    pub edit_token_challenge: Option<String>,
437    #[serde(default)]
438    pub challenge_expires_in_secs: Option<i64>,
439    pub url: String,
440    #[serde(skip)]
441    pub account_claimed: bool,
442}
443
444/// Publish a whitelisted Wrapped payload. Accepts either a bare payload (legacy anonymous) or a
445/// signed envelope `{payload_json, public_key, signature}` (login-less identity → server upsert).
446/// No account auth; the server rate-limits per IP. Contract: `docs/contracts/wrapped-permalink-v1.md`.
447pub fn publish_wrapped(payload: &serde_json::Value) -> Result<PublishedCard, String> {
448    let url = format!("{}/api/wrapped", api_url());
449
450    let resp = ureq::post(&url)
451        .header("Content-Type", "application/json")
452        .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
453        .map_err(|e| format!("Publish failed: {e}"))?;
454
455    let resp_body = resp
456        .into_body()
457        .read_to_string()
458        .map_err(|e| format!("Failed to read response: {e}"))?;
459
460    serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
461}
462
463#[derive(serde::Deserialize)]
464struct RecoveredEditToken {
465    edit_token: String,
466}
467
468/// Exchange a one-time server challenge for a rotated edit token after the
469/// caller proves possession of the card's persistent publisher key.
470pub fn recover_wrapped_edit_token(
471    id: &str,
472    nonce: &str,
473    public_key: &str,
474    signature: &str,
475) -> Result<String, String> {
476    let url = format!("{}/api/wrapped/{id}/edit-token/recover", api_url());
477    let body = serde_json::json!({
478        "nonce": nonce,
479        "public_key": public_key,
480        "signature": signature,
481    });
482    let resp = ureq::post(&url)
483        .header("Content-Type", "application/json")
484        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
485        .map_err(|e| format!("Edit-token recovery failed: {e}"))?;
486    let response = resp
487        .into_body()
488        .read_to_string()
489        .map_err(|e| format!("Failed to read response: {e}"))?;
490    let recovered: RecoveredEditToken =
491        serde_json::from_str(&response).map_err(|e| format!("Invalid recovery response: {e}"))?;
492    if recovered.edit_token.is_empty() {
493        return Err("Invalid recovery response: empty edit token".to_string());
494    }
495    Ok(recovered.edit_token)
496}
497
498/// Delete a previously published card using its one-time `edit_token` (sent as `X-Edit-Token`).
499pub fn unpublish_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
500    let url = format!("{}/api/wrapped/{id}", api_url());
501
502    ureq::delete(&url)
503        .header("X-Edit-Token", edit_token)
504        .call()
505        .map_err(|e| format!("Unpublish failed: {e}"))?;
506    Ok(())
507}
508
509/// Bind a published card to the logged-in account so the leaderboard stacks all of the
510/// user's machines under one entry (#488). Auth: account Bearer + the card's `edit_token`
511/// (`X-Edit-Token`). Server: `POST /api/wrapped/:id/claim`. Requires being logged in.
512pub fn claim_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
513    let bearer = auth_bearer_token()?;
514    let url = format!("{}/api/wrapped/{id}/claim", api_url());
515
516    ureq::post(&url)
517        .header("Authorization", &format!("Bearer {bearer}"))
518        .header("X-Edit-Token", edit_token)
519        .send_empty()
520        .map_err(|e| format!("Claim failed: {e}"))?;
521    Ok(())
522}
523
524/// A freshly minted pairing code for login-less machine linking (GH #736).
525#[derive(serde::Deserialize)]
526pub struct LinkCode {
527    pub code: String,
528    pub expires_in_secs: i64,
529}
530
531/// Start a login-less machine link: mint a short-lived pairing code for this card.
532/// Auth: the card's `edit_token` only — no account. Server: `POST /api/wrapped/:id/link/start`.
533pub fn link_wrapped_start(id: &str, edit_token: &str) -> Result<LinkCode, String> {
534    let url = format!("{}/api/wrapped/{id}/link/start", api_url());
535
536    let resp = ureq::post(&url)
537        .header("X-Edit-Token", edit_token)
538        .send_empty()
539        .map_err(|e| format!("Link start failed: {e}"))?;
540    let body = resp
541        .into_body()
542        .read_to_string()
543        .map_err(|e| format!("Failed to read response: {e}"))?;
544    serde_json::from_str(&body).map_err(|e| format!("Invalid response: {e}"))
545}
546
547/// Complete a login-less machine link on the second machine: join this card into
548/// the pairing code's group. Auth: this card's `edit_token` — no account.
549/// Server: `POST /api/wrapped/:id/link/complete`.
550pub fn link_wrapped_complete(id: &str, edit_token: &str, code: &str) -> Result<(), String> {
551    let url = format!("{}/api/wrapped/{id}/link/complete", api_url());
552    let body = serde_json::json!({ "code": code });
553
554    ureq::post(&url)
555        .header("X-Edit-Token", edit_token)
556        .header("Content-Type", "application/json")
557        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
558        .map_err(|e| match e {
559            ureq::Error::StatusCode(404) => {
560                "code invalid or expired — mint a fresh one with  lean-ctx gain --link".to_string()
561            }
562            other => format!("Link failed: {other}"),
563        })?;
564    Ok(())
565}
566
567/// Push the knowledge store as a zero-knowledge vault (GL #467): entries are
568/// sealed client-side (XChaCha20-Poly1305, domain-separated HKDF key) — the
569/// backend stores ciphertext and can never read them. The first vault push
570/// also purges the account's legacy plaintext rows server-side.
571pub fn push_knowledge(entries: &[serde_json::Value]) -> Result<String, String> {
572    let bearer = auth_bearer_token()?;
573    let key = knowledge_vault_key()?;
574    let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
575    let url = format!("{}/api/sync/knowledge", api_url());
576
577    let resp = ureq::post(&url)
578        .header("Authorization", &format!("Bearer {bearer}"))
579        .header("Content-Type", "application/octet-stream")
580        .header("X-Entry-Count", &entries.len().to_string())
581        .header("X-Device-Label", &device_label())
582        .send(blob.as_slice())
583        .map_err(|e| format!("Push failed: {e}"))?;
584
585    let resp_body = resp
586        .into_body()
587        .read_to_string()
588        .map_err(|e| format!("Failed to read response: {e}"))?;
589
590    let json: serde_json::Value =
591        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
592
593    Ok(format!(
594        "{} entries synced (end-to-end encrypted)",
595        json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
596    ))
597}
598
599/// The account's knowledge-vault key — same stable-API-key derivation rule as
600/// [`index_bundle_key`], different HKDF domain (`knowledge-vault-v1`).
601fn knowledge_vault_key() -> Result<[u8; 32], String> {
602    let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
603    if api_key.trim().is_empty() {
604        return Err("Not logged in. Run: lean-ctx login".into());
605    }
606    Ok(crate::core::knowledge_vault::derive_vault_key(&api_key))
607}
608
609pub fn pull_cloud_models() -> Result<serde_json::Value, String> {
610    let bearer = auth_bearer_token()?;
611    let url = format!("{}/api/cloud/models", api_url());
612
613    let resp = ureq::get(&url)
614        .header("Authorization", &format!("Bearer {bearer}"))
615        .call()
616        .map_err(|e| {
617            let msg = e.to_string();
618            if msg.contains("403") {
619                "This feature is not available for your account.".to_string()
620            } else {
621                format!("Connection failed. Check your internet connection. ({e})")
622            }
623        })?;
624
625    let resp_body = resp
626        .into_body()
627        .read_to_string()
628        .map_err(|e| format!("Failed to read response: {e}"))?;
629
630    serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
631}
632
633pub fn save_cloud_models(data: &serde_json::Value) -> std::io::Result<()> {
634    let dir = config_dir();
635    std::fs::create_dir_all(&dir)?;
636    let json = serde_json::to_string_pretty(data).map_err(std::io::Error::other)?;
637    std::fs::write(dir.join("cloud_models.json"), json)
638}
639
640pub fn load_cloud_models() -> Option<serde_json::Value> {
641    let path = config_dir().join("cloud_models.json");
642    let data = std::fs::read_to_string(path).ok()?;
643    serde_json::from_str(&data).ok()
644}
645
646/// Fetch the public community leaderboard as JSON (`{ "entries": [ … ] }`).
647///
648/// Public, login-less endpoint (`GET /api/leaderboard`, contract:
649/// `docs/contracts/wrapped-permalink-v1.md`). The dashboard proxies it
650/// same-origin (#466) so the browser never reaches `api.leanctx.com` directly —
651/// the dashboard CSP pins `connect-src` to `'self'`. A 10s global timeout keeps
652/// a slow upstream from tying up a dashboard request thread.
653pub fn fetch_leaderboard() -> Result<serde_json::Value, String> {
654    let url = format!("{}/api/leaderboard", api_url());
655    let resp = ureq::get(&url)
656        .config()
657        .timeout_global(Some(std::time::Duration::from_secs(10)))
658        .build()
659        .call()
660        .map_err(|e| format!("Could not reach the leaderboard service: {e}"))?;
661    let body = resp
662        .into_body()
663        .read_to_string()
664        .map_err(|e| format!("Failed to read leaderboard response: {e}"))?;
665    serde_json::from_str(&body).map_err(|e| format!("Invalid leaderboard JSON: {e}"))
666}
667
668pub fn is_cloud_user() -> bool {
669    let path = config_dir().join("plan.txt");
670    std::fs::read_to_string(path).is_ok_and(|p| matches!(p.trim(), "cloud" | "pro"))
671}
672
673/// Days a cached plan keeps granting its hosted entitlements while the billing
674/// backend is unreachable. Generous on purpose: a network blip or a weekend
675/// offline must never silently demote a paying user to Free.
676pub const PLAN_GRACE_DAYS: i64 = 14;
677
678fn plan_cache_path() -> PathBuf {
679    config_dir().join("plan.json")
680}
681
682/// The locally cached plan plus *when* it was last confirmed against the billing
683/// backend. The timestamp is what powers offline grace.
684#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
685pub struct PlanCache {
686    pub plan: String,
687    /// Unix seconds of the last successful backend confirmation.
688    pub verified_at: i64,
689}
690
691pub fn save_plan(plan: &str) -> std::io::Result<()> {
692    let dir = config_dir();
693    std::fs::create_dir_all(&dir)?;
694    // Legacy flat file kept for back-compat (`is_cloud_user` still reads it).
695    std::fs::write(dir.join("plan.txt"), plan)?;
696    // Structured cache carrying the verification time for offline grace.
697    let cache = PlanCache {
698        plan: plan.to_string(),
699        verified_at: now_unix(),
700    };
701    let json = serde_json::to_string_pretty(&cache).map_err(std::io::Error::other)?;
702    std::fs::write(plan_cache_path(), json)
703}
704
705/// The cached plan, if any. Prefers the structured `plan.json`; falls back to a
706/// legacy `plan.txt` (no timestamp → `verified_at = 0`, i.e. immediately past
707/// grace until the next successful refresh re-stamps it).
708pub fn cached_plan() -> Option<PlanCache> {
709    if let Ok(data) = std::fs::read_to_string(plan_cache_path())
710        && let Ok(cache) = serde_json::from_str::<PlanCache>(&data)
711    {
712        return Some(cache);
713    }
714    let legacy = std::fs::read_to_string(config_dir().join("plan.txt")).ok()?;
715    Some(PlanCache {
716        plan: legacy.trim().to_string(),
717        verified_at: 0,
718    })
719}
720
721/// Where an effective plan came from — drives the wording in `billing status`
722/// and the dashboard badge.
723#[derive(Debug, Clone, Copy, PartialEq, Eq)]
724pub enum PlanSource {
725    /// Just confirmed against the backend this run.
726    Live,
727    /// Served from the local cache and still within the grace window.
728    Cached,
729    /// Cached confirmation is past the grace window → demoted to Free.
730    Expired,
731    /// No cached plan at all (never logged in / never synced) → Free.
732    None,
733}
734
735/// A resolved plan plus its provenance. The plan here is only ever used for
736/// *display* and for gating **hosted** surfaces — it never gates a local
737/// capability (Local-Free Invariant; the local engine has no entitlement checks).
738#[derive(Debug, Clone)]
739pub struct EffectivePlan {
740    pub plan: crate::core::billing::Plan,
741    pub source: PlanSource,
742    pub verified_at: Option<i64>,
743    pub grace_days: i64,
744}
745
746/// Pure grace check (no clock/IO) so it is unit-testable: is a plan confirmed at
747/// `verified_at` still within `grace_days` of `now`? Returns the age in days too.
748#[must_use]
749pub fn plan_within_grace(verified_at: i64, now: i64, grace_days: i64) -> (bool, i64) {
750    let age_days = (now - verified_at).max(0) / 86_400;
751    (age_days <= grace_days, age_days)
752}
753
754/// Resolve the effective plan from the **local cache only** (no network),
755/// applying the offline-grace policy. Use this on hot paths (dashboard
756/// requests); use [`refresh_effective_plan`] when a live confirmation is
757/// acceptable.
758///
759/// Commercial entitlements (incl. any self-hosted offline Enterprise license)
760/// are resolved by the control-plane and reach this client as the cached/live
761/// plan — the open engine carries no licensing logic (oss-plane-separation-v1).
762#[must_use]
763pub fn resolve_effective_plan_cached() -> EffectivePlan {
764    let grace_days = PLAN_GRACE_DAYS;
765    let Some(cache) = cached_plan() else {
766        return EffectivePlan {
767            plan: crate::core::billing::Plan::Free,
768            source: PlanSource::None,
769            verified_at: None,
770            grace_days,
771        };
772    };
773    let (fresh, _age) = plan_within_grace(cache.verified_at, now_unix(), grace_days);
774    if fresh {
775        EffectivePlan {
776            plan: crate::core::billing::Plan::parse(&cache.plan),
777            source: PlanSource::Cached,
778            verified_at: Some(cache.verified_at),
779            grace_days,
780        }
781    } else {
782        // Fail closed for *hosted* entitlements once grace lapses. Local features
783        // remain unaffected — they are never gated.
784        EffectivePlan {
785            plan: crate::core::billing::Plan::Free,
786            source: PlanSource::Expired,
787            verified_at: Some(cache.verified_at),
788            grace_days,
789        }
790    }
791}
792
793/// Best-effort *live* resolve: try the backend (refreshing the cache on success),
794/// otherwise fall back to the cached-with-grace plan. Suitable for explicit
795/// commands like `lean-ctx billing status` where a network round-trip is fine.
796#[must_use]
797pub fn refresh_effective_plan() -> EffectivePlan {
798    if is_logged_in()
799        && let Ok(plan_str) = fetch_plan()
800    {
801        let _ = save_plan(&plan_str);
802        return EffectivePlan {
803            plan: crate::core::billing::Plan::parse(&plan_str),
804            source: PlanSource::Live,
805            verified_at: Some(now_unix()),
806            grace_days: PLAN_GRACE_DAYS,
807        };
808    }
809    resolve_effective_plan_cached()
810}
811
812pub fn fetch_plan() -> Result<String, String> {
813    let bearer = auth_bearer_token()?;
814    let url = format!("{}/api/auth/me", api_url());
815
816    let resp = ureq::get(&url)
817        .header("Authorization", &format!("Bearer {bearer}"))
818        .call()
819        .map_err(|e| format!("Failed to check plan: {e}"))?;
820
821    let resp_body = resp
822        .into_body()
823        .read_to_string()
824        .map_err(|e| format!("Failed to read response: {e}"))?;
825
826    let json: serde_json::Value =
827        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
828
829    Ok(json["plan"].as_str().unwrap_or("free").to_string())
830}
831
832/// Start a Stripe Checkout session for the logged-in account and return the
833/// hosted URL to open. `plan` is e.g. `"pro"` or `"team"`; `interval` is
834/// `"monthly"` or `"yearly"`. The open backend proxies this to the private
835/// billing plane (which returns `503` when billing is not configured).
836pub fn start_checkout(plan: &str, interval: &str) -> Result<String, String> {
837    let bearer = auth_bearer_token()?;
838    let url = format!("{}/api/account/checkout", api_url());
839    let body = serde_json::json!({ "plan": plan, "interval": interval });
840
841    let resp = ureq::post(&url)
842        .header("Authorization", &format!("Bearer {bearer}"))
843        .header("Content-Type", "application/json")
844        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
845        .map_err(|e| format!("Checkout request failed: {e}"))?;
846
847    let resp_body = resp
848        .into_body()
849        .read_to_string()
850        .map_err(|e| format!("Failed to read response: {e}"))?;
851
852    let json: serde_json::Value =
853        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
854
855    json["url"]
856        .as_str()
857        .map(str::to_string)
858        .ok_or_else(|| "Billing did not return a checkout URL.".to_string())
859}
860
861pub fn push_commands(entries: &[serde_json::Value]) -> Result<String, String> {
862    let bearer = auth_bearer_token()?;
863    let url = format!("{}/api/sync/commands", api_url());
864    let body = serde_json::json!({ "commands": entries });
865    let resp = ureq::post(&url)
866        .header("Authorization", &format!("Bearer {bearer}"))
867        .header("Content-Type", "application/json")
868        .header("X-Device-Label", &device_label())
869        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
870        .map_err(|e| format!("Push failed: {e}"))?;
871    let resp_body = resp
872        .into_body()
873        .read_to_string()
874        .map_err(|e| format!("Failed to read response: {e}"))?;
875    let json: serde_json::Value =
876        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
877    Ok(format!(
878        "{} commands synced",
879        json["synced"].as_i64().unwrap_or(0)
880    ))
881}
882
883pub fn push_cep(entries: &[serde_json::Value]) -> Result<String, String> {
884    let bearer = auth_bearer_token()?;
885    let url = format!("{}/api/sync/cep", api_url());
886    let body = serde_json::json!({ "scores": entries });
887    let resp = ureq::post(&url)
888        .header("Authorization", &format!("Bearer {bearer}"))
889        .header("Content-Type", "application/json")
890        .header("X-Device-Label", &device_label())
891        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
892        .map_err(|e| format!("Push failed: {e}"))?;
893    let resp_body = resp
894        .into_body()
895        .read_to_string()
896        .map_err(|e| format!("Failed to read response: {e}"))?;
897    let json: serde_json::Value =
898        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
899    Ok(format!(
900        "{} sessions synced",
901        json["synced"].as_i64().unwrap_or(0)
902    ))
903}
904
905pub fn push_gain(entries: &[serde_json::Value]) -> Result<String, String> {
906    let bearer = auth_bearer_token()?;
907    let url = format!("{}/api/sync/gain", api_url());
908    let body = serde_json::json!({ "scores": entries });
909    let resp = ureq::post(&url)
910        .header("Authorization", &format!("Bearer {bearer}"))
911        .header("Content-Type", "application/json")
912        .header("X-Device-Label", &device_label())
913        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
914        .map_err(|e| format!("Push failed: {e}"))?;
915    let resp_body = resp
916        .into_body()
917        .read_to_string()
918        .map_err(|e| format!("Failed to read response: {e}"))?;
919    let json: serde_json::Value =
920        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
921    Ok(format!(
922        "{} gain scores synced",
923        json["synced"].as_i64().unwrap_or(0)
924    ))
925}
926
927/// Push gotchas as a zero-knowledge vault (GL #467 follow-up): sealed
928/// client-side under the `gotcha-vault-v1` HKDF domain — the backend stores
929/// ciphertext only and purges the account's legacy plaintext rows on the
930/// first vault push.
931pub fn push_gotchas(entries: &[serde_json::Value]) -> Result<String, String> {
932    let bearer = auth_bearer_token()?;
933    let key = gotcha_vault_key()?;
934    let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
935    let url = format!("{}/api/sync/gotchas", api_url());
936
937    let resp = ureq::post(&url)
938        .header("Authorization", &format!("Bearer {bearer}"))
939        .header("Content-Type", "application/octet-stream")
940        .header("X-Entry-Count", &entries.len().to_string())
941        .header("X-Device-Label", &device_label())
942        .send(blob.as_slice())
943        .map_err(|e| format!("Push failed: {e}"))?;
944    let resp_body = resp
945        .into_body()
946        .read_to_string()
947        .map_err(|e| format!("Failed to read response: {e}"))?;
948    let json: serde_json::Value =
949        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
950    Ok(format!(
951        "{} gotchas synced (end-to-end encrypted)",
952        json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
953    ))
954}
955
956/// The account's gotcha-vault key — own HKDF domain (`gotcha-vault-v1`),
957/// derivation rule identical to [`knowledge_vault_key`].
958fn gotcha_vault_key() -> Result<[u8; 32], String> {
959    let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
960    if api_key.trim().is_empty() {
961        return Err("Not logged in. Run: lean-ctx login".into());
962    }
963    Ok(crate::core::knowledge_vault::derive_gotcha_vault_key(
964        &api_key,
965    ))
966}
967
968pub fn push_buddy(data: &serde_json::Value) -> Result<String, String> {
969    let bearer = auth_bearer_token()?;
970    let url = format!("{}/api/sync/buddy", api_url());
971    let resp = ureq::post(&url)
972        .header("Authorization", &format!("Bearer {bearer}"))
973        .header("Content-Type", "application/json")
974        .header("X-Device-Label", &device_label())
975        .send(&serde_json::to_vec(data).map_err(|e| format!("JSON error: {e}"))?)
976        .map_err(|e| format!("Push failed: {e}"))?;
977    let resp_body = resp
978        .into_body()
979        .read_to_string()
980        .map_err(|e| format!("Failed to read response: {e}"))?;
981    let _json: serde_json::Value =
982        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
983    Ok("Buddy synced".to_string())
984}
985
986pub fn push_feedback(entries: &[serde_json::Value]) -> Result<String, String> {
987    let bearer = auth_bearer_token()?;
988    let url = format!("{}/api/sync/feedback", api_url());
989    let resp = ureq::post(&url)
990        .header("Authorization", &format!("Bearer {bearer}"))
991        .header("Content-Type", "application/json")
992        .header("X-Device-Label", &device_label())
993        .send(&serde_json::to_vec(entries).map_err(|e| format!("JSON error: {e}"))?)
994        .map_err(|e| format!("Push failed: {e}"))?;
995    let resp_body = resp
996        .into_body()
997        .read_to_string()
998        .map_err(|e| format!("Failed to read response: {e}"))?;
999    let json: serde_json::Value =
1000        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1001    Ok(format!(
1002        "{} thresholds synced",
1003        json["synced"].as_i64().unwrap_or(0)
1004    ))
1005}
1006
1007/// The signed-in account's email, for status displays.
1008pub fn account_email() -> Option<String> {
1009    load_credentials().map(|c| c.email)
1010}
1011
1012/// `GET /api/account/cloud` — the Personal Cloud dashboard payload (entitlement
1013/// gate, per-bucket sync footprint, buddy, usage totals). Powers
1014/// `lean-ctx cloud status`, mirroring what leanctx.com/account/cloud shows.
1015pub fn fetch_account_cloud() -> Result<serde_json::Value, String> {
1016    let bearer = auth_bearer_token()?;
1017    let url = format!("{}/api/account/cloud", api_url());
1018
1019    let resp = ureq::get(&url)
1020        .header("Authorization", &format!("Bearer {bearer}"))
1021        .call()
1022        .map_err(|e| format!("Status fetch failed: {e}"))?;
1023
1024    let resp_body = resp
1025        .into_body()
1026        .read_to_string()
1027        .map_err(|e| format!("Failed to read response: {e}"))?;
1028
1029    serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))
1030}
1031
1032/// Pull the knowledge store: vault-first (encrypted blob, decrypted locally),
1033/// with a legacy plaintext fallback for accounts that never pushed a vault.
1034pub fn pull_knowledge() -> Result<Vec<serde_json::Value>, String> {
1035    let bearer = auth_bearer_token()?;
1036    let url = format!("{}/api/sync/knowledge", api_url());
1037
1038    // Vault path (GL #467).
1039    match ureq::get(&url)
1040        .header("Authorization", &format!("Bearer {bearer}"))
1041        .header("Accept", "application/octet-stream")
1042        .call()
1043    {
1044        Ok(resp) => {
1045            let is_blob = resp
1046                .headers()
1047                .get("content-type")
1048                .and_then(|v| v.to_str().ok())
1049                .is_some_and(|v| v.starts_with("application/octet-stream"));
1050            if is_blob {
1051                let mut blob = Vec::new();
1052                use std::io::Read;
1053                resp.into_body()
1054                    .into_reader()
1055                    .read_to_end(&mut blob)
1056                    .map_err(|e| format!("Failed to read vault: {e}"))?;
1057                let key = knowledge_vault_key()?;
1058                return crate::core::knowledge_vault::open(&blob, &key).map_err(|e| e.to_string());
1059            }
1060            // Pre-vault server ignored the Accept header and answered with
1061            // the legacy JSON listing — parse it directly.
1062            let body = resp
1063                .into_body()
1064                .read_to_string()
1065                .map_err(|e| format!("Failed to read response: {e}"))?;
1066            return serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"));
1067        }
1068        // No vault yet → fall through to the legacy listing.
1069        Err(ureq::Error::StatusCode(404)) => {}
1070        Err(e) => return Err(format!("Pull failed: {e}")),
1071    }
1072
1073    let resp = ureq::get(&url)
1074        .header("Authorization", &format!("Bearer {bearer}"))
1075        .call()
1076        .map_err(|e| format!("Pull failed: {e}"))?;
1077
1078    let resp_body = resp
1079        .into_body()
1080        .read_to_string()
1081        .map_err(|e| format!("Failed to read response: {e}"))?;
1082
1083    let entries: Vec<serde_json::Value> =
1084        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1085
1086    Ok(entries)
1087}
1088
1089// ── Hosted Personal Index (GL #392) ──────────────────────────────────────────
1090// Contract: docs/contracts/hosted-personal-index-v1.md. Bundles are encrypted
1091// client-side (core::index_bundle); the backend only ever sees ciphertext.
1092
1093/// The account's bundle encryption key, HKDF-derived from the stable API key
1094/// (never from the rotating OAuth token — the key must be identical on every
1095/// logged-in device).
1096fn index_bundle_key() -> Result<[u8; 32], String> {
1097    let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
1098    if api_key.trim().is_empty() {
1099        return Err("Not logged in. Run: lean-ctx login".into());
1100    }
1101    Ok(crate::core::index_bundle::derive_key(&api_key))
1102}
1103
1104/// Pack, encrypt and upload the project's index bundle.
1105/// Returns `(project_hash, encrypted_size_bytes)`.
1106pub fn push_index_bundle(project_root: &std::path::Path) -> Result<(String, u64), String> {
1107    let (container, manifest) =
1108        crate::core::index_bundle::pack(project_root).map_err(|e| e.to_string())?;
1109    let blob = crate::core::index_bundle::encrypt(&container, &index_bundle_key()?)
1110        .map_err(|e| e.to_string())?;
1111
1112    let bearer = auth_bearer_token()?;
1113    let url = format!("{}/api/sync/index/{}", api_url(), manifest.project_hash);
1114    let resp = ureq::put(&url)
1115        .header("Authorization", &format!("Bearer {bearer}"))
1116        .header("Content-Type", "application/octet-stream")
1117        .header("X-Device-Label", &device_label())
1118        .send(blob.as_slice())
1119        .map_err(|e| match e {
1120            ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1121                 Run: lean-ctx cloud upgrade --plan pro"
1122                .to_string(),
1123            ureq::Error::StatusCode(413) => {
1124                "Quota exceeded — the push was blocked (nothing is billed). \
1125                 Free space with `lean-ctx sync index status` / delete, then retry."
1126                    .to_string()
1127            }
1128            other => format!("Push failed: {other}"),
1129        })?;
1130
1131    let body = resp
1132        .into_body()
1133        .read_to_string()
1134        .map_err(|e| format!("Failed to read response: {e}"))?;
1135    let _ack: serde_json::Value =
1136        serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
1137    Ok((manifest.project_hash, blob.len() as u64))
1138}
1139
1140/// Download, decrypt and unpack the hosted bundle for this project.
1141/// Returns the bundle manifest on success.
1142pub fn pull_index_bundle(
1143    project_root: &std::path::Path,
1144) -> Result<crate::core::index_bundle::BundleManifest, String> {
1145    let project_hash = crate::core::index_namespace::namespace_hash(project_root);
1146    let bearer = auth_bearer_token()?;
1147    let url = format!("{}/api/sync/index/{project_hash}", api_url());
1148
1149    let resp = ureq::get(&url)
1150        .header("Authorization", &format!("Bearer {bearer}"))
1151        .call()
1152        .map_err(|e| match e {
1153            ureq::Error::StatusCode(404) => format!(
1154                "No hosted index for this project yet ({project_hash}). \
1155                 Push one from a device with a built index: lean-ctx sync index push"
1156            ),
1157            ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1158                 Run: lean-ctx cloud upgrade --plan pro"
1159                .to_string(),
1160            other => format!("Pull failed: {other}"),
1161        })?;
1162
1163    let mut blob = Vec::new();
1164    use std::io::Read;
1165    resp.into_body()
1166        .into_reader()
1167        .read_to_end(&mut blob)
1168        .map_err(|e| format!("Failed to read bundle: {e}"))?;
1169
1170    let container = crate::core::index_bundle::decrypt(&blob, &index_bundle_key()?)
1171        .map_err(|e| e.to_string())?;
1172    crate::core::index_bundle::unpack(project_root, &container).map_err(|e| e.to_string())
1173}
1174
1175/// `GET /api/sync/index` — hosted-bucket listing + quota usage for the account.
1176pub fn index_bundle_status() -> Result<serde_json::Value, String> {
1177    let bearer = auth_bearer_token()?;
1178    let url = format!("{}/api/sync/index", api_url());
1179    let resp = ureq::get(&url)
1180        .header("Authorization", &format!("Bearer {bearer}"))
1181        .call()
1182        .map_err(|e| format!("Status fetch failed: {e}"))?;
1183    let body = resp
1184        .into_body()
1185        .read_to_string()
1186        .map_err(|e| format!("Failed to read response: {e}"))?;
1187    serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))
1188}
1189
1190#[cfg(test)]
1191mod tests {
1192    use super::*;
1193    use crate::core::billing::Plan;
1194    // Only the `#[cfg(unix)]` credential-permission tests still take the env lock
1195    // directly; the plan-resolver tests use `isolated_data_dir()` (which locks
1196    // internally). Gating the import keeps the Windows cross-compile warning-free.
1197    #[cfg(unix)]
1198    use crate::core::data_dir::test_env_lock;
1199
1200    #[test]
1201    fn existing_card_publish_response_carries_recovery_challenge() {
1202        let card: PublishedCard = serde_json::from_value(serde_json::json!({
1203            "id": "card-1",
1204            "url": "https://leanctx.com/w/card-1",
1205            "edit_token_challenge": "nonce-1",
1206            "challenge_expires_in_secs": 300
1207        }))
1208        .unwrap();
1209        assert!(card.edit_token.is_none());
1210        assert_eq!(card.edit_token_challenge.as_deref(), Some("nonce-1"));
1211        assert_eq!(card.challenge_expires_in_secs, Some(300));
1212        assert!(!card.account_claimed);
1213    }
1214
1215    #[test]
1216    fn grace_window_boundaries_are_inclusive_and_skew_safe() {
1217        let now = 1_000_000_000;
1218        let day = 86_400;
1219        assert_eq!(plan_within_grace(now, now, 14), (true, 0));
1220        // Exactly at the edge stays valid (inclusive).
1221        assert_eq!(plan_within_grace(now - 14 * day, now, 14), (true, 14));
1222        // One day past → expired.
1223        assert_eq!(plan_within_grace(now - 15 * day, now, 14), (false, 15));
1224        // Clock skew (future timestamp) is clamped to age 0, never negative.
1225        assert_eq!(plan_within_grace(now + day, now, 14), (true, 0));
1226    }
1227
1228    #[test]
1229    fn plan_cache_roundtrips_through_json() {
1230        let c = PlanCache {
1231            plan: "pro".into(),
1232            verified_at: 42,
1233        };
1234        let back: PlanCache = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
1235        assert_eq!(back.plan, "pro");
1236        assert_eq!(back.verified_at, 42);
1237    }
1238
1239    #[test]
1240    fn cached_resolve_grants_within_grace_then_expires_to_free() {
1241        // Isolate all dirs (config + cache) so the resolver reads only the cache
1242        // this test writes, not a developer's real plan cache.
1243        let _iso = crate::core::data_dir::isolated_data_dir();
1244
1245        // A fresh save is served from cache, within grace, at full plan.
1246        save_plan("pro").unwrap();
1247        let eff = resolve_effective_plan_cached();
1248        assert_eq!(eff.plan, Plan::Pro);
1249        assert_eq!(eff.source, PlanSource::Cached);
1250
1251        // Backdate beyond grace → hosted entitlements fail closed to Free.
1252        let stale = PlanCache {
1253            plan: "pro".into(),
1254            verified_at: now_unix() - (PLAN_GRACE_DAYS + 1) * 86_400,
1255        };
1256        std::fs::write(plan_cache_path(), serde_json::to_string(&stale).unwrap()).unwrap();
1257        let eff = resolve_effective_plan_cached();
1258        assert_eq!(eff.plan, Plan::Free);
1259        assert_eq!(eff.source, PlanSource::Expired);
1260    }
1261
1262    #[test]
1263    fn no_cache_resolves_to_free_none() {
1264        let _iso = crate::core::data_dir::isolated_data_dir();
1265        let eff = resolve_effective_plan_cached();
1266        assert_eq!(eff.plan, Plan::Free);
1267        assert_eq!(eff.source, PlanSource::None);
1268    }
1269
1270    // P0-2 (#414): credentials must be owner-only on disk.
1271    #[cfg(unix)]
1272    #[test]
1273    fn credentials_are_written_owner_only_and_atomic() {
1274        use std::os::unix::fs::PermissionsExt;
1275        let _env = test_env_lock();
1276        let tmp = tempfile::tempdir().unwrap();
1277        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1278
1279        save_credentials("sk-test-key", "user-1", "a@b.c").unwrap();
1280
1281        let path = credentials_path();
1282        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1283        assert_eq!(mode & 0o777, 0o600, "credentials.json must be 0o600");
1284
1285        let dir_mode = std::fs::metadata(config_dir())
1286            .unwrap()
1287            .permissions()
1288            .mode();
1289        assert_eq!(
1290            dir_mode & 0o077,
1291            0,
1292            "cloud dir must not be group/world accessible"
1293        );
1294
1295        // No tmp file leftovers from the atomic write.
1296        let leftovers: Vec<_> = std::fs::read_dir(config_dir())
1297            .unwrap()
1298            .filter_map(Result::ok)
1299            .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
1300            .collect();
1301        assert!(leftovers.is_empty(), "atomic write must not leak tmp files");
1302
1303        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1304    }
1305
1306    // P0-2 (#414): pre-existing world-readable credentials are tightened on load.
1307    #[cfg(unix)]
1308    #[test]
1309    fn loose_credential_permissions_are_tightened_on_load() {
1310        use std::os::unix::fs::PermissionsExt;
1311        let _env = test_env_lock();
1312        let tmp = tempfile::tempdir().unwrap();
1313        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1314
1315        std::fs::create_dir_all(config_dir()).unwrap();
1316        let path = credentials_path();
1317        std::fs::write(&path, "{}").unwrap();
1318        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
1319
1320        let _ = load_credentials();
1321
1322        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1323        assert_eq!(
1324            mode & 0o777,
1325            0o600,
1326            "legacy file must be tightened to 0o600"
1327        );
1328
1329        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1330    }
1331
1332    #[test]
1333    fn legacy_plan_txt_is_migrated_but_treated_as_stale() {
1334        let _iso = crate::core::data_dir::isolated_data_dir();
1335        // Only the legacy flat file exists (no timestamp) → past grace until refresh.
1336        std::fs::create_dir_all(config_dir()).unwrap();
1337        std::fs::write(config_dir().join("plan.txt"), "team").unwrap();
1338        let cache = cached_plan().unwrap();
1339        assert_eq!(cache.plan, "team");
1340        assert_eq!(cache.verified_at, 0);
1341        assert_eq!(resolve_effective_plan_cached().source, PlanSource::Expired);
1342    }
1343}