Skip to main content

lean_ctx/
cloud_client.rs

1use std::path::PathBuf;
2
3#[allow(dead_code, unreachable_pub)]
4mod entitlement_cache;
5pub use entitlement_cache::EffectivePlan as VerifiedEffectivePlan;
6
7pub const ENTITLEMENT_DENIAL_PREFIX: &str = "Signed entitlement does not allow ";
8
9fn config_dir() -> PathBuf {
10    // GH #439: data_dir() already honors LEAN_CTX_DATA_DIR + legacy/XDG, so the
11    // cloud cache follows the migration instead of pinning ~/.lean-ctx.
12    crate::core::paths::data_dir()
13        .unwrap_or_else(|_| PathBuf::from("."))
14        .join("cloud")
15}
16
17fn credentials_path() -> PathBuf {
18    config_dir().join("credentials.json")
19}
20
21/// Base URL of the lean-ctx cloud API. Unit tests and cargo-launched binaries
22/// get the discard port instead of any non-loopback endpoint, so test fixtures
23/// (telemetry probes, feedback, stats, wrapped cards) can never reach
24/// production; their requests fail fast with "connection refused".
25pub fn api_url() -> String {
26    const LOOPBACK_SINK: &str = "http://127.0.0.1:9";
27    let configured =
28        std::env::var("LEAN_CTX_API_URL").unwrap_or_else(|_| "https://api.leanctx.com".to_string());
29    if cloud_endpoint_allowed(&configured, launched_by_cargo()) {
30        configured
31    } else {
32        LOOPBACK_SINK.to_string()
33    }
34}
35
36#[derive(serde::Serialize, serde::Deserialize)]
37struct Credentials {
38    api_key: String,
39    user_id: String,
40    email: String,
41    #[serde(default)]
42    oauth_client_id: Option<String>,
43    #[serde(default)]
44    oauth_client_secret: Option<String>,
45    #[serde(default)]
46    oauth_access_token: Option<String>,
47    #[serde(default)]
48    oauth_expires_at_unix: Option<i64>,
49}
50
51fn load_credentials() -> Option<Credentials> {
52    let path = credentials_path();
53    // One-time migration for files written before permissions were enforced:
54    // tighten anything looser than owner-only on every load.
55    tighten_secret_permissions(&path);
56    let data = std::fs::read_to_string(&path).ok()?;
57    serde_json::from_str(&data).ok()
58}
59
60fn write_credentials(creds: &Credentials) -> std::io::Result<()> {
61    let dir = config_dir();
62    std::fs::create_dir_all(&dir)?;
63    restrict_dir_permissions(&dir);
64    let json = serde_json::to_string_pretty(creds).map_err(std::io::Error::other)?;
65    write_secret_file(&credentials_path(), json.as_bytes())
66}
67
68/// Writes a secret file atomically (tmp + rename) with owner-only permissions
69/// (0o600 on Unix), so credentials are never world-readable — not even
70/// transiently between create and chmod.
71fn write_secret_file(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
72    use std::io::Write;
73
74    let parent = path
75        .parent()
76        .ok_or_else(|| std::io::Error::other("credentials path has no parent directory"))?;
77    let name = path
78        .file_name()
79        .ok_or_else(|| std::io::Error::other("credentials path has no file name"))?
80        .to_string_lossy();
81    let tmp = parent.join(format!(".{name}.tmp.{}", std::process::id()));
82
83    let mut opts = std::fs::OpenOptions::new();
84    opts.write(true).create_new(true);
85    #[cfg(unix)]
86    {
87        use std::os::unix::fs::OpenOptionsExt;
88        opts.mode(0o600);
89    }
90
91    let result = (|| {
92        let mut f = opts.open(&tmp)?;
93        f.write_all(bytes)?;
94        f.sync_all()?;
95        drop(f);
96        #[cfg(windows)]
97        {
98            if path.exists() {
99                std::fs::remove_file(path)?;
100            }
101        }
102        std::fs::rename(&tmp, path)
103    })();
104
105    if result.is_err() {
106        let _ = std::fs::remove_file(&tmp);
107    }
108    result
109}
110
111#[cfg(unix)]
112fn restrict_dir_permissions(dir: &std::path::Path) {
113    use std::os::unix::fs::PermissionsExt;
114    let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
115}
116
117#[cfg(not(unix))]
118fn restrict_dir_permissions(_dir: &std::path::Path) {}
119
120#[cfg(unix)]
121fn tighten_secret_permissions(path: &std::path::Path) {
122    use std::os::unix::fs::PermissionsExt;
123    if let Ok(meta) = std::fs::metadata(path)
124        && meta.permissions().mode() & 0o077 != 0
125    {
126        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
127    }
128}
129
130#[cfg(not(unix))]
131fn tighten_secret_permissions(_path: &std::path::Path) {}
132
133pub fn save_credentials(api_key: &str, user_id: &str, email: &str) -> std::io::Result<()> {
134    let mut creds = load_credentials().unwrap_or(Credentials {
135        api_key: api_key.to_string(),
136        user_id: user_id.to_string(),
137        email: email.to_string(),
138        oauth_client_id: None,
139        oauth_client_secret: None,
140        oauth_access_token: None,
141        oauth_expires_at_unix: None,
142    });
143    creds.api_key = api_key.to_string();
144    creds.user_id = user_id.to_string();
145    creds.email = email.to_string();
146    // Access tokens are bound to a client and should be re-fetched after login changes.
147    creds.oauth_access_token = None;
148    creds.oauth_expires_at_unix = None;
149    write_credentials(&creds)
150}
151
152pub fn load_api_key() -> Option<String> {
153    load_credentials().map(|c| c.api_key)
154}
155
156pub fn is_logged_in() -> bool {
157    load_credentials().is_some()
158}
159
160fn now_unix() -> i64 {
161    use std::time::{SystemTime, UNIX_EPOCH};
162    SystemTime::now()
163        .duration_since(UNIX_EPOCH)
164        .unwrap_or_default()
165        .as_secs() as i64
166}
167
168/// This machine's legacy account-key label, sent with login/registration and
169/// attached as `X-Device-Label` to sync pushes. It lets the account service
170/// replace this machine's key without replacing the account's other keys.
171/// This display label is not the authenticated device identity of a v2 lease.
172fn device_label() -> String {
173    gethostname::gethostname().to_string_lossy().into_owned()
174}
175
176fn auth_bearer_token() -> Result<String, String> {
177    let mut creds = load_credentials().ok_or("Not logged in. Run: lean-ctx login")?;
178
179    if let (Some(client_id), Some(client_secret)) = (
180        creds.oauth_client_id.clone(),
181        creds.oauth_client_secret.clone(),
182    ) {
183        let now = now_unix();
184        if let (Some(token), Some(exp)) = (
185            creds.oauth_access_token.clone(),
186            creds.oauth_expires_at_unix,
187        ) && exp > now + 10
188        {
189            return Ok(token);
190        }
191
192        let url = format!("{}/oauth/token", api_url());
193        let resp = ureq::post(&url)
194            .header("Content-Type", "application/x-www-form-urlencoded")
195            .send_form([
196                ("grant_type", "client_credentials"),
197                ("client_id", client_id.as_str()),
198                ("client_secret", client_secret.as_str()),
199            ])
200            .map_err(|e| format!("OAuth token request failed: {e}"))?;
201
202        let resp_body = resp
203            .into_body()
204            .read_to_string()
205            .map_err(|e| format!("Failed to read OAuth response: {e}"))?;
206
207        let json: serde_json::Value =
208            serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
209
210        let token = json["access_token"]
211            .as_str()
212            .ok_or("Missing access_token in response")?
213            .to_string();
214        let expires_in = json["expires_in"].as_i64().unwrap_or(3600);
215        let exp = now + expires_in.saturating_sub(30);
216
217        creds.oauth_access_token = Some(token.clone());
218        creds.oauth_expires_at_unix = Some(exp);
219        let _ = write_credentials(&creds);
220
221        return Ok(token);
222    }
223
224    Ok(creds.api_key)
225}
226
227pub fn oauth_register_client(client_name: Option<&str>) -> Result<String, String> {
228    let mut creds = load_credentials().ok_or("Not logged in. Run: lean-ctx login")?;
229    if creds.oauth_client_id.is_some() && creds.oauth_client_secret.is_some() {
230        return Ok("OAuth client already registered.".to_string());
231    }
232
233    let url = format!("{}/oauth/register", api_url());
234    let body = if let Some(name) = client_name {
235        serde_json::json!({ "client_name": name })
236    } else {
237        serde_json::json!({})
238    };
239
240    let resp = ureq::post(&url)
241        .header("Authorization", &format!("Bearer {}", creds.api_key))
242        .header("Content-Type", "application/json")
243        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
244        .map_err(|e| format!("OAuth register failed: {e}"))?;
245
246    let resp_body = resp
247        .into_body()
248        .read_to_string()
249        .map_err(|e| format!("Failed to read response: {e}"))?;
250
251    let json: serde_json::Value =
252        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
253
254    creds.oauth_client_id = Some(
255        json["client_id"]
256            .as_str()
257            .ok_or("Missing client_id in response")?
258            .to_string(),
259    );
260    creds.oauth_client_secret = Some(
261        json["client_secret"]
262            .as_str()
263            .ok_or("Missing client_secret in response")?
264            .to_string(),
265    );
266    creds.oauth_access_token = None;
267    creds.oauth_expires_at_unix = None;
268    write_credentials(&creds).map_err(|e| format!("Failed to persist OAuth credentials: {e}"))?;
269
270    Ok("OAuth client registered. Cloud requests will use short-lived access tokens.".to_string())
271}
272
273pub struct RegisterResult {
274    pub api_key: String,
275    pub user_id: String,
276    pub email_verified: bool,
277    pub verification_sent: bool,
278}
279
280pub fn register(email: &str, password: Option<&str>) -> Result<RegisterResult, String> {
281    let url = format!("{}/api/auth/register", api_url());
282    // The label names the key this call issues, so the account page can tell
283    // one machine from another. Keys are per-device and additive.
284    let mut body = serde_json::json!({ "email": email, "device_label": device_label() });
285    if let Some(pw) = password {
286        body["password"] = serde_json::Value::String(pw.to_string());
287    }
288
289    let resp = ureq::post(&url)
290        .header("Content-Type", "application/json")
291        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
292        .map_err(|e| format!("Request failed: {e}"))?;
293
294    let resp_body = resp
295        .into_body()
296        .read_to_string()
297        .map_err(|e| format!("Failed to read response: {e}"))?;
298
299    let json: serde_json::Value =
300        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
301
302    Ok(RegisterResult {
303        api_key: json["api_key"]
304            .as_str()
305            .ok_or("Missing api_key in response")?
306            .to_string(),
307        user_id: json["user_id"]
308            .as_str()
309            .ok_or("Missing user_id in response")?
310            .to_string(),
311        email_verified: json["email_verified"].as_bool().unwrap_or(false),
312        verification_sent: json["verification_sent"].as_bool().unwrap_or(false),
313    })
314}
315
316pub fn forgot_password(email: &str) -> Result<String, String> {
317    let url = format!("{}/api/auth/forgot-password", api_url());
318    let body = serde_json::json!({ "email": email });
319
320    let resp = ureq::post(&url)
321        .header("Content-Type", "application/json")
322        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
323        .map_err(|e| format!("Request failed: {e}"))?;
324
325    let resp_body = resp
326        .into_body()
327        .read_to_string()
328        .map_err(|e| format!("Failed to read response: {e}"))?;
329
330    let json: serde_json::Value =
331        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
332
333    Ok(json["message"]
334        .as_str()
335        .unwrap_or("If an account exists, a reset email has been sent.")
336        .to_string())
337}
338
339pub fn login(email: &str, password: &str) -> Result<RegisterResult, String> {
340    let url = format!("{}/api/auth/login", api_url());
341    let body = serde_json::json!({
342        "email": email,
343        "password": password,
344        "device_label": device_label(),
345    });
346
347    let resp = ureq::post(&url)
348        .header("Content-Type", "application/json")
349        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
350        .map_err(|e| {
351            let msg = e.to_string();
352            if msg.contains("401") {
353                "Invalid email or password".to_string()
354            } else {
355                format!("Request failed: {e}")
356            }
357        })?;
358
359    let resp_body = resp
360        .into_body()
361        .read_to_string()
362        .map_err(|e| format!("Failed to read response: {e}"))?;
363
364    let json: serde_json::Value =
365        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
366
367    Ok(RegisterResult {
368        api_key: json["api_key"]
369            .as_str()
370            .ok_or("Missing api_key in response")?
371            .to_string(),
372        user_id: json["user_id"]
373            .as_str()
374            .ok_or("Missing user_id in response")?
375            .to_string(),
376        email_verified: json["email_verified"].as_bool().unwrap_or(false),
377        verification_sent: false,
378    })
379}
380
381pub fn sync_stats(stats: &[serde_json::Value]) -> Result<String, String> {
382    let bearer = auth_bearer_token()?;
383    let url = format!("{}/api/stats", api_url());
384
385    let body = serde_json::json!({ "stats": stats });
386
387    let resp = ureq::post(&url)
388        .header("Authorization", &format!("Bearer {bearer}"))
389        .header("Content-Type", "application/json")
390        .header("X-Device-Label", &device_label())
391        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
392        .map_err(|e| format!("Sync failed: {e}"))?;
393
394    let resp_body = resp
395        .into_body()
396        .read_to_string()
397        .map_err(|e| format!("Failed to read response: {e}"))?;
398
399    let json: serde_json::Value =
400        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
401
402    Ok(json["message"].as_str().unwrap_or("Synced").to_string())
403}
404
405pub fn contribute(entries: &[serde_json::Value]) -> Result<String, String> {
406    let url = format!("{}/api/contribute", api_url());
407
408    let body = serde_json::json!({ "entries": entries });
409
410    let resp = ureq::post(&url)
411        .header("Content-Type", "application/json")
412        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
413        .map_err(|e| format!("Contribute failed: {e}"))?;
414
415    let resp_body = resp
416        .into_body()
417        .read_to_string()
418        .map_err(|e| format!("Failed to read response: {e}"))?;
419
420    let json: serde_json::Value =
421        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
422
423    Ok(json["message"]
424        .as_str()
425        .unwrap_or("Contributed")
426        .to_string())
427}
428
429/// Send an anonymous telemetry heartbeat. No authentication required.
430/// Payload: installation_id (random UUID), version, OS, arch — nothing else.
431pub fn heartbeat(payload: &serde_json::Value) -> Result<String, String> {
432    let url = format!("{}/api/telemetry/heartbeat", api_url());
433
434    let resp = ureq::post(&url)
435        .header("Content-Type", "application/json")
436        .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
437        .map_err(|e| format!("Heartbeat failed: {e}"))?;
438
439    let resp_body = resp
440        .into_body()
441        .read_to_string()
442        .map_err(|e| format!("Failed to read response: {e}"))?;
443
444    let json: serde_json::Value =
445        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
446
447    Ok(json["message"].as_str().unwrap_or("OK").to_string())
448}
449
450/// Send one volunteered product-feedback submission. No authentication.
451///
452/// Anonymous like [`heartbeat`], and for the same reason: there is no account to
453/// attach this to, and requiring one would silence exactly the users worth
454/// hearing from. The payload carries only what the person typed into the form,
455/// plus the installation id and version so answers can be read in context —
456/// never anything derived from their code, paths or usage.
457///
458/// The server may answer 429 when one installation has already sent several
459/// today; that is surfaced to the caller rather than swallowed, so the UI can
460/// say what happened instead of reporting a send that was dropped.
461pub fn submit_product_feedback(payload: &serde_json::Value) -> Result<String, String> {
462    let url = format!("{}/api/feedback/product", api_url());
463
464    let resp = ureq::post(&url)
465        .header("Content-Type", "application/json")
466        .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
467        .map_err(|e| format!("Could not send feedback: {e}"))?;
468
469    let body = resp
470        .into_body()
471        .read_to_string()
472        .map_err(|e| format!("Failed to read response: {e}"))?;
473
474    let json: serde_json::Value =
475        serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
476
477    Ok(json["message"].as_str().unwrap_or("Thanks").to_string())
478}
479
480/// Cargo exports `CARGO_PKG_NAME` to `cargo test` / `cargo run` processes and
481/// every child they spawn, so integration tests driving the binary carry it too.
482fn launched_by_cargo() -> bool {
483    std::env::var("CARGO_PKG_NAME").is_ok_and(|name| name == env!("CARGO_PKG_NAME"))
484}
485
486/// Unit tests and cargo-launched binaries may only talk to a loopback
487/// endpoint; otherwise test fixtures would pollute production data.
488fn cloud_endpoint_allowed(base_url: &str, launched_by_cargo: bool) -> bool {
489    if !cfg!(test) && !launched_by_cargo {
490        return true;
491    }
492    let Some(authority) = base_url
493        .strip_prefix("http://")
494        .or_else(|| base_url.strip_prefix("https://"))
495        .and_then(|rest| rest.split(['/', '?', '#']).next())
496    else {
497        return false;
498    };
499    if authority.contains('@') {
500        return false;
501    }
502    let host = match authority.strip_prefix('[') {
503        Some(bracketed) => bracketed.split(']').next().unwrap_or_default(),
504        None => authority.split(':').next().unwrap_or_default(),
505    };
506    host.eq_ignore_ascii_case("localhost")
507        || host
508            .parse::<std::net::IpAddr>()
509            .is_ok_and(|ip| ip.is_loopback())
510}
511
512/// Send one validated telemetry-v2 daily batch. No authentication required.
513pub fn telemetry_v2_batch(
514    batch: &crate::core::telemetry_v2::TelemetryBatchV2,
515) -> Result<String, String> {
516    telemetry_v2_batch_with_timeout(batch, std::time::Duration::from_secs(10))
517}
518
519pub(crate) fn telemetry_v2_batch_with_timeout(
520    batch: &crate::core::telemetry_v2::TelemetryBatchV2,
521    timeout: std::time::Duration,
522) -> Result<String, String> {
523    // A sender may have waited for another lease since its initial precheck.
524    let config = crate::core::config::Config::try_load_global()
525        .map_err(|_| "Telemetry configuration unavailable".to_string())?;
526    let do_not_track = crate::core::host_env::var("DO_NOT_TRACK");
527    let telemetry_override = crate::core::host_env::var("LEAN_CTX_TELEMETRY");
528    if !config
529        .telemetry
530        .send_eligible(do_not_track.as_deref(), telemetry_override.as_deref())
531    {
532        return Err("Telemetry sending is disabled".to_string());
533    }
534    if crate::core::telemetry_consent::running_in_ci() {
535        return Err("Telemetry is not sent from CI".to_string());
536    }
537    batch
538        .validate()
539        .map_err(|error| format!("Telemetry validation failed: {error:?}"))?;
540    let url = format!("{}/api/telemetry/v2/batch", api_url());
541    let response = ureq::post(&url)
542        .config()
543        .timeout_global(Some(timeout))
544        .build()
545        .header("Content-Type", "application/json")
546        .send(&serde_json::to_vec(batch).map_err(|error| format!("JSON error: {error}"))?)
547        .map_err(|error| format!("Telemetry v2 batch failed: {error}"))?;
548    let body = response
549        .into_body()
550        .read_to_string()
551        .map_err(|error| format!("Failed to read response: {error}"))?;
552    let json: serde_json::Value =
553        serde_json::from_str(&body).map_err(|error| format!("Invalid JSON: {error}"))?;
554    crate::core::telemetry_notices::remember(crate::core::telemetry_notices::from_response(&json));
555    Ok(json["message"].as_str().unwrap_or("OK").to_string())
556}
557
558/// Delete every server-side aggregate associated with one installation ID.
559pub fn delete_remote_telemetry(
560    installation_id: &str,
561    deletion_token: &str,
562) -> Result<bool, String> {
563    let installation_id = uuid::Uuid::parse_str(installation_id)
564        .map_err(|_| "Invalid installation ID".to_string())?;
565    let url = format!(
566        "{}/api/telemetry/v2/installations/{installation_id}",
567        api_url()
568    );
569    if deletion_token.len() != 64
570        || !deletion_token
571            .bytes()
572            .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
573    {
574        return Err("Invalid telemetry deletion credential".to_string());
575    }
576    let response = ureq::delete(&url)
577        .header(
578            "Authorization",
579            &format!("TelemetryDelete v1.{deletion_token}"),
580        )
581        .call()
582        .map_err(|error| format!("Remote telemetry deletion failed: {error}"))?;
583    let status = response.status().as_u16();
584    let body = response
585        .into_body()
586        .read_to_string()
587        .map_err(|error| format!("Failed to read deletion response: {error}"))?;
588    deletion_confirmed(status, &body)
589}
590
591fn deletion_confirmed(status: u16, body: &str) -> Result<bool, String> {
592    if status == 204 {
593        return Ok(false);
594    }
595    let value: serde_json::Value = serde_json::from_str(body)
596        .map_err(|error| format!("Invalid deletion response: {error}"))?;
597    Ok(value.get("deleted").and_then(serde_json::Value::as_bool) == Some(true))
598}
599
600/// Result of a successful Wrapped publish (`POST /api/wrapped`). The `edit_token` is returned
601/// (and must be stored to delete/claim later) only on a *fresh* insert; on a signed re-publish
602/// the server updates the existing card in place and omits it (the client keeps the stored one).
603#[derive(serde::Deserialize)]
604pub struct PublishedCard {
605    pub id: String,
606    #[serde(default)]
607    pub edit_token: Option<String>,
608    #[serde(default)]
609    pub edit_token_challenge: Option<String>,
610    #[serde(default)]
611    pub challenge_expires_in_secs: Option<i64>,
612    pub url: String,
613    #[serde(skip)]
614    pub account_claimed: bool,
615}
616
617/// Publish a whitelisted Wrapped payload. Accepts either a bare payload (legacy anonymous) or a
618/// signed envelope `{payload_json, public_key, signature}` (login-less identity → server upsert).
619/// If the user is logged in, attaches a Bearer token so the server can auto-claim
620/// the card (leaderboard consolidation).
621pub fn publish_wrapped(payload: &serde_json::Value) -> Result<PublishedCard, String> {
622    let url = format!("{}/api/wrapped", api_url());
623
624    let mut req = ureq::post(&url).header("Content-Type", "application/json");
625    if let Ok(token) = auth_bearer_token() {
626        req = req.header("Authorization", &format!("Bearer {token}"));
627    }
628    let resp = req
629        .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
630        .map_err(|e| format!("Publish failed: {e}"))?;
631
632    let resp_body = resp
633        .into_body()
634        .read_to_string()
635        .map_err(|e| format!("Failed to read response: {e}"))?;
636
637    serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
638}
639
640#[derive(serde::Deserialize)]
641struct RecoveredEditToken {
642    edit_token: String,
643}
644
645/// Exchange a one-time server challenge for a rotated edit token after the
646/// caller proves possession of the card's persistent publisher key.
647pub fn recover_wrapped_edit_token(
648    id: &str,
649    nonce: &str,
650    public_key: &str,
651    signature: &str,
652) -> Result<String, String> {
653    let url = format!("{}/api/wrapped/{id}/edit-token/recover", api_url());
654    let body = serde_json::json!({
655        "nonce": nonce,
656        "public_key": public_key,
657        "signature": signature,
658    });
659    let resp = ureq::post(&url)
660        .header("Content-Type", "application/json")
661        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
662        .map_err(|e| format!("Edit-token recovery failed: {e}"))?;
663    let response = resp
664        .into_body()
665        .read_to_string()
666        .map_err(|e| format!("Failed to read response: {e}"))?;
667    let recovered: RecoveredEditToken =
668        serde_json::from_str(&response).map_err(|e| format!("Invalid recovery response: {e}"))?;
669    if recovered.edit_token.is_empty() {
670        return Err("Invalid recovery response: empty edit token".to_string());
671    }
672    Ok(recovered.edit_token)
673}
674
675/// Delete a previously published card using its one-time `edit_token` (sent as `X-Edit-Token`).
676///
677/// Idempotent: a card the server no longer has (404/410) counts as removed.
678/// The caller's goal is "this page is not public any more", and failing a
679/// takedown because it already succeeded would strand the local record with no
680/// way to clear it (#1726).
681pub fn unpublish_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
682    let url = format!("{}/api/wrapped/{id}", api_url());
683
684    match ureq::delete(&url).header("X-Edit-Token", edit_token).call() {
685        // Removed now, or already gone (404/410) — either way it is not public.
686        Ok(_) | Err(ureq::Error::StatusCode(404 | 410)) => Ok(()),
687        Err(e) => Err(format!("Unpublish failed: {e}")),
688    }
689}
690
691/// Bind a published card to the logged-in account so the leaderboard stacks all of the
692/// user's machines under one entry (#488). Auth: account Bearer + the card's `edit_token`
693/// (`X-Edit-Token`). Server: `POST /api/wrapped/:id/claim`. Requires being logged in.
694pub fn claim_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
695    let bearer = auth_bearer_token()?;
696    let url = format!("{}/api/wrapped/{id}/claim", api_url());
697
698    ureq::post(&url)
699        .header("Authorization", &format!("Bearer {bearer}"))
700        .header("X-Edit-Token", edit_token)
701        .send_empty()
702        .map_err(|e| format!("Claim failed: {e}"))?;
703    Ok(())
704}
705
706/// A freshly minted pairing code for login-less machine linking (GH #736).
707#[derive(serde::Deserialize)]
708pub struct LinkCode {
709    pub code: String,
710    pub expires_in_secs: i64,
711}
712
713/// Start a login-less machine link: mint a short-lived pairing code for this card.
714/// Auth: the card's `edit_token` only — no account. Server: `POST /api/wrapped/:id/link/start`.
715pub fn link_wrapped_start(id: &str, edit_token: &str) -> Result<LinkCode, String> {
716    let url = format!("{}/api/wrapped/{id}/link/start", api_url());
717
718    let resp = ureq::post(&url)
719        .header("X-Edit-Token", edit_token)
720        .send_empty()
721        .map_err(|e| format!("Link start failed: {e}"))?;
722    let body = resp
723        .into_body()
724        .read_to_string()
725        .map_err(|e| format!("Failed to read response: {e}"))?;
726    serde_json::from_str(&body).map_err(|e| format!("Invalid response: {e}"))
727}
728
729/// Complete a login-less machine link on the second machine: join this card into
730/// the pairing code's group. Auth: this card's `edit_token` — no account.
731/// Server: `POST /api/wrapped/:id/link/complete`.
732pub fn link_wrapped_complete(id: &str, edit_token: &str, code: &str) -> Result<(), String> {
733    let url = format!("{}/api/wrapped/{id}/link/complete", api_url());
734    let body = serde_json::json!({ "code": code });
735
736    ureq::post(&url)
737        .header("X-Edit-Token", edit_token)
738        .header("Content-Type", "application/json")
739        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
740        .map_err(|e| match e {
741            ureq::Error::StatusCode(404) => {
742                "code invalid or expired — mint a fresh one with  lean-ctx gain --link".to_string()
743            }
744            other => format!("Link failed: {other}"),
745        })?;
746    Ok(())
747}
748
749/// Push the knowledge store as a zero-knowledge vault (GL #467): entries are
750/// sealed client-side (XChaCha20-Poly1305, domain-separated HKDF key) — the
751/// backend stores ciphertext and can never read them. The first vault push
752/// also purges the account's legacy plaintext rows server-side.
753pub fn push_knowledge(entries: &[serde_json::Value]) -> Result<String, String> {
754    let bearer = auth_bearer_token()?;
755    let key = knowledge_vault_key()?;
756    let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
757    let url = format!("{}/api/sync/knowledge", api_url());
758
759    let resp = ureq::post(&url)
760        .header("Authorization", &format!("Bearer {bearer}"))
761        .header("Content-Type", "application/octet-stream")
762        .header("X-Entry-Count", &entries.len().to_string())
763        .header("X-Device-Label", &device_label())
764        .send(blob.as_slice())
765        .map_err(|e| format!("Push failed: {e}"))?;
766
767    let resp_body = resp
768        .into_body()
769        .read_to_string()
770        .map_err(|e| format!("Failed to read response: {e}"))?;
771
772    let json: serde_json::Value =
773        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
774
775    Ok(format!(
776        "{} entries synced (end-to-end encrypted)",
777        json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
778    ))
779}
780
781/// The account's knowledge-vault key — same stable-API-key derivation rule as
782/// [`index_bundle_key`], different HKDF domain (`knowledge-vault-v1`).
783fn knowledge_vault_key() -> Result<[u8; 32], String> {
784    let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
785    if api_key.trim().is_empty() {
786        return Err("Not logged in. Run: lean-ctx login".into());
787    }
788    Ok(crate::core::knowledge_vault::derive_vault_key(&api_key))
789}
790
791pub fn pull_cloud_models() -> Result<serde_json::Value, String> {
792    let bearer = auth_bearer_token()?;
793    let url = format!("{}/api/cloud/models", api_url());
794
795    let resp = ureq::get(&url)
796        .header("Authorization", &format!("Bearer {bearer}"))
797        .call()
798        .map_err(|e| {
799            let msg = e.to_string();
800            if msg.contains("403") {
801                "This feature is not available for your account.".to_string()
802            } else {
803                format!("Connection failed. Check your internet connection. ({e})")
804            }
805        })?;
806
807    let resp_body = resp
808        .into_body()
809        .read_to_string()
810        .map_err(|e| format!("Failed to read response: {e}"))?;
811
812    serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
813}
814
815pub fn save_cloud_models(data: &serde_json::Value) -> std::io::Result<()> {
816    let dir = config_dir();
817    std::fs::create_dir_all(&dir)?;
818    let json = serde_json::to_string_pretty(data).map_err(std::io::Error::other)?;
819    std::fs::write(dir.join("cloud_models.json"), json)
820}
821
822pub fn load_cloud_models() -> Option<serde_json::Value> {
823    let path = config_dir().join("cloud_models.json");
824    let data = std::fs::read_to_string(path).ok()?;
825    serde_json::from_str(&data).ok()
826}
827
828/// Fetch the public community leaderboard as JSON (`{ "entries": [ … ] }`).
829///
830/// Public, login-less endpoint (`GET /api/leaderboard`, contract:
831/// `docs/contracts/wrapped-permalink-v1.md`). The dashboard proxies it
832/// same-origin (#466) so the browser never reaches `api.leanctx.com` directly —
833/// the dashboard CSP pins `connect-src` to `'self'`. A 10s global timeout keeps
834/// a slow upstream from tying up a dashboard request thread.
835pub fn fetch_leaderboard() -> Result<serde_json::Value, String> {
836    let url = format!("{}/api/leaderboard", api_url());
837    let resp = ureq::get(&url)
838        .config()
839        .timeout_global(Some(std::time::Duration::from_secs(10)))
840        .build()
841        .call()
842        .map_err(|e| format!("Could not reach the leaderboard service: {e}"))?;
843    let body = resp
844        .into_body()
845        .read_to_string()
846        .map_err(|e| format!("Failed to read leaderboard response: {e}"))?;
847    serde_json::from_str(&body).map_err(|e| format!("Invalid leaderboard JSON: {e}"))
848}
849
850pub fn is_cloud_user() -> bool {
851    let path = config_dir().join("plan.txt");
852    std::fs::read_to_string(path).is_ok_and(|value| plan_value_has_cloud_access(&value))
853}
854
855fn plan_value_has_cloud_access(value: &str) -> bool {
856    value.trim().eq_ignore_ascii_case("cloud")
857        || crate::core::billing::Plan::parse_known(value)
858            .is_some_and(|plan| plan.rank() >= crate::core::billing::Plan::Pro.rank())
859}
860
861/// Days a cached plan keeps granting its hosted entitlements while the billing
862/// backend is unreachable. Generous on purpose: a network blip or a weekend
863/// offline must never silently demote a paying user to Community.
864pub const PLAN_GRACE_DAYS: i64 = 14;
865
866fn plan_cache_path() -> PathBuf {
867    config_dir().join("plan.json")
868}
869
870/// The locally cached plan plus *when* it was last confirmed against the billing
871/// backend. The timestamp is what powers offline grace.
872#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
873pub struct PlanCache {
874    pub plan: String,
875    /// Unix seconds of the last successful backend confirmation.
876    pub verified_at: i64,
877}
878
879pub fn save_plan(plan: &str) -> std::io::Result<()> {
880    let dir = config_dir();
881    std::fs::create_dir_all(&dir)?;
882    // Legacy flat file kept for back-compat (`is_cloud_user` still reads it).
883    std::fs::write(dir.join("plan.txt"), plan)?;
884    // Structured cache carrying the verification time for offline grace.
885    let cache = PlanCache {
886        plan: plan.to_string(),
887        verified_at: now_unix(),
888    };
889    let json = serde_json::to_string_pretty(&cache).map_err(std::io::Error::other)?;
890    std::fs::write(plan_cache_path(), json)
891}
892
893/// The cached plan, if any. Prefers the structured `plan.json`; falls back to a
894/// legacy `plan.txt` (no timestamp → `verified_at = 0`, i.e. immediately past
895/// grace until the next successful refresh re-stamps it).
896pub fn cached_plan() -> Option<PlanCache> {
897    if let Ok(data) = std::fs::read_to_string(plan_cache_path())
898        && let Ok(cache) = serde_json::from_str::<PlanCache>(&data)
899    {
900        return Some(cache);
901    }
902    let legacy = std::fs::read_to_string(config_dir().join("plan.txt")).ok()?;
903    Some(PlanCache {
904        plan: legacy.trim().to_string(),
905        verified_at: 0,
906    })
907}
908
909/// Where an effective plan came from — drives the wording in `billing status`
910/// and the dashboard badge.
911#[derive(Debug, Clone, Copy, PartialEq, Eq)]
912pub enum PlanSource {
913    /// Just confirmed against the backend this run.
914    Live,
915    /// Served from the local cache and still within the grace window.
916    Cached,
917    /// Cached confirmation is past the grace window → demoted to Community.
918    Expired,
919    /// No cached plan at all (never logged in / never synced) → Community.
920    None,
921}
922
923/// A resolved plan plus provenance and donation/support recognition.
924#[derive(Debug, Clone)]
925pub struct EffectivePlan {
926    pub plan: crate::core::billing::Plan,
927    pub supporter_recognition: bool,
928    pub source: PlanSource,
929    pub verified_at: Option<i64>,
930    pub grace_days: i64,
931}
932
933/// Pure grace check (no clock/IO) so it is unit-testable: is a plan confirmed at
934/// `verified_at` still within `grace_days` of `now`? Returns the age in days too.
935#[must_use]
936pub fn plan_within_grace(verified_at: i64, now: i64, grace_days: i64) -> (bool, i64) {
937    let age_days = (now - verified_at).max(0) / 86_400;
938    (age_days <= grace_days, age_days)
939}
940
941/// Resolve the effective plan from the **local cache only** (no network),
942/// applying the offline-grace policy. Use this on hot paths (dashboard
943/// requests); use [`refresh_effective_plan`] when a live confirmation is
944/// acceptable.
945///
946/// Commercial entitlements (incl. any self-hosted offline Enterprise license)
947/// are resolved by the control-plane and reach this client as the cached/live
948/// plan — the open engine carries no licensing logic (oss-plane-separation-v1).
949#[must_use]
950pub fn resolve_effective_plan_cached() -> EffectivePlan {
951    let grace_days = PLAN_GRACE_DAYS;
952    let Some(cache) = cached_plan() else {
953        return EffectivePlan {
954            plan: crate::core::billing::Plan::Community,
955            supporter_recognition: false,
956            source: PlanSource::None,
957            verified_at: None,
958            grace_days,
959        };
960    };
961    let (fresh, _age) = plan_within_grace(cache.verified_at, now_unix(), grace_days);
962    if fresh {
963        let selection = crate::core::billing::Plan::parse_selection(&cache.plan);
964        EffectivePlan {
965            plan: selection.plan,
966            supporter_recognition: selection.supporter_recognition,
967            source: PlanSource::Cached,
968            verified_at: Some(cache.verified_at),
969            grace_days,
970        }
971    } else {
972        // Fail closed for paid entitlements once grace lapses. Explicit
973        // Community/Trust Core capabilities remain unaffected.
974        EffectivePlan {
975            plan: crate::core::billing::Plan::Community,
976            supporter_recognition: false,
977            source: PlanSource::Expired,
978            verified_at: Some(cache.verified_at),
979            grace_days,
980        }
981    }
982}
983
984/// Authoritative, local-only paid-capability decision from a verified signed
985/// entitlement. Unsigned plan caches are display state and never reach here.
986#[must_use]
987pub fn signed_entitlement_allows(capability: &str) -> bool {
988    entitlement_cache::resolve_cached().allows(capability)
989}
990
991/// Resolve signed rights for reports without trusting unsigned display plans.
992#[must_use]
993pub fn resolve_verified_plan_cached() -> VerifiedEffectivePlan {
994    entitlement_cache::resolve_cached()
995}
996
997/// Refresh signed authority, retaining only cryptographically valid grace.
998#[must_use]
999pub fn refresh_verified_plan() -> VerifiedEffectivePlan {
1000    entitlement_cache::refresh()
1001}
1002
1003#[cfg(test)]
1004pub(crate) fn install_test_signed_entitlement_paths(
1005    trust: PathBuf,
1006    credentials: PathBuf,
1007    cache: PathBuf,
1008    anchors: Vec<(String, [u8; 32])>,
1009) -> impl Drop {
1010    entitlement_cache::install_test_paths(trust, credentials, cache, anchors)
1011}
1012
1013#[cfg(test)]
1014pub(crate) fn accept_test_signed_entitlement(account: &str, bytes: &[u8]) {
1015    entitlement_cache::accept_test_cache(account, bytes);
1016}
1017
1018/// Best-effort *live* resolve: try the backend (refreshing the cache on success),
1019/// otherwise fall back to the cached-with-grace plan. Suitable for explicit
1020/// commands like `lean-ctx billing status` where a network round-trip is fine.
1021#[must_use]
1022pub fn refresh_effective_plan() -> EffectivePlan {
1023    if is_logged_in()
1024        && let Ok(plan_str) = fetch_plan()
1025    {
1026        let _ = save_plan(&plan_str);
1027        let selection = crate::core::billing::Plan::parse_selection(&plan_str);
1028        return EffectivePlan {
1029            plan: selection.plan,
1030            supporter_recognition: selection.supporter_recognition,
1031            source: PlanSource::Live,
1032            verified_at: Some(now_unix()),
1033            grace_days: PLAN_GRACE_DAYS,
1034        };
1035    }
1036    resolve_effective_plan_cached()
1037}
1038
1039pub fn fetch_plan() -> Result<String, String> {
1040    let bearer = auth_bearer_token()?;
1041    let url = format!("{}/api/auth/me", api_url());
1042
1043    let resp = ureq::get(&url)
1044        .header("Authorization", &format!("Bearer {bearer}"))
1045        .call()
1046        .map_err(|e| format!("Failed to check plan: {e}"))?;
1047
1048    let resp_body = resp
1049        .into_body()
1050        .read_to_string()
1051        .map_err(|e| format!("Failed to read response: {e}"))?;
1052
1053    let json: serde_json::Value =
1054        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
1055
1056    Ok(json["plan"].as_str().unwrap_or("community").to_string())
1057}
1058
1059/// Start a Stripe Checkout session for the logged-in account and return the
1060/// hosted URL to open. `plan` is e.g. `"pro"` or `"team"`; `interval` is
1061/// `"monthly"` or `"yearly"`. The open backend proxies this to the private
1062/// billing plane (which returns `503` when billing is not configured).
1063pub fn start_checkout(plan: &str, interval: &str) -> Result<String, String> {
1064    let bearer = auth_bearer_token()?;
1065    let url = format!("{}/api/account/checkout", api_url());
1066    let body = serde_json::json!({ "plan": plan, "interval": interval });
1067
1068    let resp = ureq::post(&url)
1069        .header("Authorization", &format!("Bearer {bearer}"))
1070        .header("Content-Type", "application/json")
1071        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
1072        .map_err(|e| format!("Checkout request failed: {e}"))?;
1073
1074    let resp_body = resp
1075        .into_body()
1076        .read_to_string()
1077        .map_err(|e| format!("Failed to read response: {e}"))?;
1078
1079    let json: serde_json::Value =
1080        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
1081
1082    parse_checkout_url(&json)
1083}
1084
1085fn parse_checkout_url(json: &serde_json::Value) -> Result<String, String> {
1086    let raw = json["url"]
1087        .as_str()
1088        .ok_or_else(|| "Billing did not return a checkout URL.".to_string())?;
1089    // The URL is printed to the terminal and handed to the browser opener:
1090    // control characters (CR/LF, ESC sequences) must never pass through.
1091    if raw.chars().any(char::is_control) {
1092        return Err("Billing returned an invalid checkout URL.".to_string());
1093    }
1094    let parsed = reqwest::Url::parse(raw)
1095        .map_err(|_| "Billing returned an invalid checkout URL.".to_string())?;
1096    if parsed.scheme() != "https"
1097        || parsed.host_str().is_none()
1098        || !parsed.username().is_empty()
1099        || parsed.password().is_some()
1100    {
1101        return Err("Billing returned an invalid checkout URL.".to_string());
1102    }
1103    Ok(parsed.to_string())
1104}
1105
1106pub fn push_commands(entries: &[serde_json::Value]) -> Result<String, String> {
1107    let bearer = auth_bearer_token()?;
1108    let url = format!("{}/api/sync/commands", api_url());
1109    let body = serde_json::json!({ "commands": entries });
1110    let resp = ureq::post(&url)
1111        .header("Authorization", &format!("Bearer {bearer}"))
1112        .header("Content-Type", "application/json")
1113        .header("X-Device-Label", &device_label())
1114        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
1115        .map_err(|e| format!("Push failed: {e}"))?;
1116    let resp_body = resp
1117        .into_body()
1118        .read_to_string()
1119        .map_err(|e| format!("Failed to read response: {e}"))?;
1120    let json: serde_json::Value =
1121        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1122    Ok(format!(
1123        "{} commands synced",
1124        json["synced"].as_i64().unwrap_or(0)
1125    ))
1126}
1127
1128pub fn push_cep(entries: &[serde_json::Value]) -> Result<String, String> {
1129    let bearer = auth_bearer_token()?;
1130    let url = format!("{}/api/sync/cep", api_url());
1131    let body = serde_json::json!({ "scores": entries });
1132    let resp = ureq::post(&url)
1133        .header("Authorization", &format!("Bearer {bearer}"))
1134        .header("Content-Type", "application/json")
1135        .header("X-Device-Label", &device_label())
1136        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
1137        .map_err(|e| format!("Push failed: {e}"))?;
1138    let resp_body = resp
1139        .into_body()
1140        .read_to_string()
1141        .map_err(|e| format!("Failed to read response: {e}"))?;
1142    let json: serde_json::Value =
1143        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1144    Ok(format!(
1145        "{} sessions synced",
1146        json["synced"].as_i64().unwrap_or(0)
1147    ))
1148}
1149
1150pub fn push_gain(entries: &[serde_json::Value]) -> Result<String, String> {
1151    let bearer = auth_bearer_token()?;
1152    let url = format!("{}/api/sync/gain", api_url());
1153    let body = serde_json::json!({ "scores": entries });
1154    let resp = ureq::post(&url)
1155        .header("Authorization", &format!("Bearer {bearer}"))
1156        .header("Content-Type", "application/json")
1157        .header("X-Device-Label", &device_label())
1158        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
1159        .map_err(|e| format!("Push failed: {e}"))?;
1160    let resp_body = resp
1161        .into_body()
1162        .read_to_string()
1163        .map_err(|e| format!("Failed to read response: {e}"))?;
1164    let json: serde_json::Value =
1165        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1166    Ok(format!(
1167        "{} gain scores synced",
1168        json["synced"].as_i64().unwrap_or(0)
1169    ))
1170}
1171
1172/// Push gotchas as a zero-knowledge vault (GL #467 follow-up): sealed
1173/// client-side under the `gotcha-vault-v1` HKDF domain — the backend stores
1174/// ciphertext only and purges the account's legacy plaintext rows on the
1175/// first vault push.
1176pub fn push_gotchas(entries: &[serde_json::Value]) -> Result<String, String> {
1177    let bearer = auth_bearer_token()?;
1178    let key = gotcha_vault_key()?;
1179    let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
1180    let url = format!("{}/api/sync/gotchas", api_url());
1181
1182    let resp = ureq::post(&url)
1183        .header("Authorization", &format!("Bearer {bearer}"))
1184        .header("Content-Type", "application/octet-stream")
1185        .header("X-Entry-Count", &entries.len().to_string())
1186        .header("X-Device-Label", &device_label())
1187        .send(blob.as_slice())
1188        .map_err(|e| format!("Push failed: {e}"))?;
1189    let resp_body = resp
1190        .into_body()
1191        .read_to_string()
1192        .map_err(|e| format!("Failed to read response: {e}"))?;
1193    let json: serde_json::Value =
1194        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1195    Ok(format!(
1196        "{} gotchas synced (end-to-end encrypted)",
1197        json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
1198    ))
1199}
1200
1201/// The account's gotcha-vault key — own HKDF domain (`gotcha-vault-v1`),
1202/// derivation rule identical to [`knowledge_vault_key`].
1203fn gotcha_vault_key() -> Result<[u8; 32], String> {
1204    let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
1205    if api_key.trim().is_empty() {
1206        return Err("Not logged in. Run: lean-ctx login".into());
1207    }
1208    Ok(crate::core::knowledge_vault::derive_gotcha_vault_key(
1209        &api_key,
1210    ))
1211}
1212
1213pub fn push_buddy(data: &serde_json::Value) -> Result<String, String> {
1214    let bearer = auth_bearer_token()?;
1215    let url = format!("{}/api/sync/buddy", api_url());
1216    let resp = ureq::post(&url)
1217        .header("Authorization", &format!("Bearer {bearer}"))
1218        .header("Content-Type", "application/json")
1219        .header("X-Device-Label", &device_label())
1220        .send(&serde_json::to_vec(data).map_err(|e| format!("JSON error: {e}"))?)
1221        .map_err(|e| format!("Push failed: {e}"))?;
1222    let resp_body = resp
1223        .into_body()
1224        .read_to_string()
1225        .map_err(|e| format!("Failed to read response: {e}"))?;
1226    let _json: serde_json::Value =
1227        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1228    Ok("Buddy synced".to_string())
1229}
1230
1231pub fn push_feedback(entries: &[serde_json::Value]) -> Result<String, String> {
1232    let bearer = auth_bearer_token()?;
1233    let url = format!("{}/api/sync/feedback", api_url());
1234    let resp = ureq::post(&url)
1235        .header("Authorization", &format!("Bearer {bearer}"))
1236        .header("Content-Type", "application/json")
1237        .header("X-Device-Label", &device_label())
1238        .send(&serde_json::to_vec(entries).map_err(|e| format!("JSON error: {e}"))?)
1239        .map_err(|e| format!("Push failed: {e}"))?;
1240    let resp_body = resp
1241        .into_body()
1242        .read_to_string()
1243        .map_err(|e| format!("Failed to read response: {e}"))?;
1244    let json: serde_json::Value =
1245        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1246    Ok(format!(
1247        "{} thresholds synced",
1248        json["synced"].as_i64().unwrap_or(0)
1249    ))
1250}
1251
1252/// The signed-in account's email, for status displays.
1253pub fn account_email() -> Option<String> {
1254    load_credentials().map(|c| c.email)
1255}
1256
1257/// `GET /api/account/cloud` — the Personal Cloud dashboard payload (entitlement
1258/// gate, per-bucket sync footprint, buddy, usage totals). Powers
1259/// `lean-ctx cloud status`, mirroring what leanctx.com/account/cloud shows.
1260pub fn fetch_account_cloud() -> Result<serde_json::Value, String> {
1261    let bearer = auth_bearer_token()?;
1262    let url = format!("{}/api/account/cloud", api_url());
1263
1264    let resp = ureq::get(&url)
1265        .header("Authorization", &format!("Bearer {bearer}"))
1266        .call()
1267        .map_err(|e| format!("Status fetch failed: {e}"))?;
1268
1269    let resp_body = resp
1270        .into_body()
1271        .read_to_string()
1272        .map_err(|e| format!("Failed to read response: {e}"))?;
1273
1274    serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))
1275}
1276
1277/// Pull the knowledge store: vault-first (encrypted blob, decrypted locally),
1278/// with a legacy plaintext fallback for accounts that never pushed a vault.
1279pub fn pull_knowledge() -> Result<Vec<serde_json::Value>, String> {
1280    let bearer = auth_bearer_token()?;
1281    let url = format!("{}/api/sync/knowledge", api_url());
1282
1283    // Vault path (GL #467).
1284    match ureq::get(&url)
1285        .header("Authorization", &format!("Bearer {bearer}"))
1286        .header("Accept", "application/octet-stream")
1287        .call()
1288    {
1289        Ok(resp) => {
1290            let is_blob = resp
1291                .headers()
1292                .get("content-type")
1293                .and_then(|v| v.to_str().ok())
1294                .is_some_and(|v| v.starts_with("application/octet-stream"));
1295            if is_blob {
1296                let mut blob = Vec::new();
1297                use std::io::Read;
1298                resp.into_body()
1299                    .into_reader()
1300                    .read_to_end(&mut blob)
1301                    .map_err(|e| format!("Failed to read vault: {e}"))?;
1302                let key = knowledge_vault_key()?;
1303                return crate::core::knowledge_vault::open(&blob, &key).map_err(|e| e.to_string());
1304            }
1305            // Pre-vault server ignored the Accept header and answered with
1306            // the legacy JSON listing — parse it directly.
1307            let body = resp
1308                .into_body()
1309                .read_to_string()
1310                .map_err(|e| format!("Failed to read response: {e}"))?;
1311            return serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"));
1312        }
1313        // No vault yet → fall through to the legacy listing.
1314        Err(ureq::Error::StatusCode(404)) => {}
1315        Err(e) => return Err(format!("Pull failed: {e}")),
1316    }
1317
1318    let resp = ureq::get(&url)
1319        .header("Authorization", &format!("Bearer {bearer}"))
1320        .call()
1321        .map_err(|e| format!("Pull failed: {e}"))?;
1322
1323    let resp_body = resp
1324        .into_body()
1325        .read_to_string()
1326        .map_err(|e| format!("Failed to read response: {e}"))?;
1327
1328    let entries: Vec<serde_json::Value> =
1329        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1330
1331    Ok(entries)
1332}
1333
1334// ── Hosted Personal Index (GL #392) ──────────────────────────────────────────
1335// Contract: docs/contracts/hosted-personal-index-v1.md. Bundles are encrypted
1336// client-side (core::index_bundle); the backend only ever sees ciphertext.
1337
1338/// The account's bundle encryption key, HKDF-derived from the stable API key
1339/// (never from the rotating OAuth token — the key must be identical on every
1340/// logged-in device).
1341fn index_bundle_key() -> Result<[u8; 32], String> {
1342    let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
1343    if api_key.trim().is_empty() {
1344        return Err("Not logged in. Run: lean-ctx login".into());
1345    }
1346    Ok(crate::core::index_bundle::derive_key(&api_key))
1347}
1348
1349/// Pack, encrypt and upload the project's index bundle.
1350/// Returns `(project_hash, encrypted_size_bytes)`.
1351pub fn push_index_bundle(project_root: &std::path::Path) -> Result<(String, u64), String> {
1352    let (container, manifest) =
1353        crate::core::index_bundle::pack(project_root).map_err(|e| e.to_string())?;
1354    let blob = crate::core::index_bundle::encrypt(&container, &index_bundle_key()?)
1355        .map_err(|e| e.to_string())?;
1356
1357    let bearer = auth_bearer_token()?;
1358    let url = format!("{}/api/sync/index/{}", api_url(), manifest.project_hash);
1359    let resp = ureq::put(&url)
1360        .header("Authorization", &format!("Bearer {bearer}"))
1361        .header("Content-Type", "application/octet-stream")
1362        .header("X-Device-Label", &device_label())
1363        .send(blob.as_slice())
1364        .map_err(|e| match e {
1365            ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1366                 Run: lean-ctx cloud upgrade --plan pro"
1367                .to_string(),
1368            ureq::Error::StatusCode(413) => {
1369                "Quota exceeded — the push was blocked (nothing is billed). \
1370                 Free space with `lean-ctx sync index status` / delete, then retry."
1371                    .to_string()
1372            }
1373            other => format!("Push failed: {other}"),
1374        })?;
1375
1376    let body = resp
1377        .into_body()
1378        .read_to_string()
1379        .map_err(|e| format!("Failed to read response: {e}"))?;
1380    let _ack: serde_json::Value =
1381        serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
1382    Ok((manifest.project_hash, blob.len() as u64))
1383}
1384
1385/// Download, decrypt and unpack the hosted bundle for this project.
1386/// Returns the bundle manifest on success.
1387pub fn pull_index_bundle(
1388    project_root: &std::path::Path,
1389) -> Result<crate::core::index_bundle::BundleManifest, String> {
1390    let project_hash = crate::core::index_namespace::namespace_hash(project_root);
1391    let bearer = auth_bearer_token()?;
1392    let url = format!("{}/api/sync/index/{project_hash}", api_url());
1393
1394    let resp = ureq::get(&url)
1395        .header("Authorization", &format!("Bearer {bearer}"))
1396        .call()
1397        .map_err(|e| match e {
1398            ureq::Error::StatusCode(404) => format!(
1399                "No hosted index for this project yet ({project_hash}). \
1400                 Push one from a device with a built index: lean-ctx sync index push"
1401            ),
1402            ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1403                 Run: lean-ctx cloud upgrade --plan pro"
1404                .to_string(),
1405            other => format!("Pull failed: {other}"),
1406        })?;
1407
1408    let mut blob = Vec::new();
1409    use std::io::Read;
1410    resp.into_body()
1411        .into_reader()
1412        .read_to_end(&mut blob)
1413        .map_err(|e| format!("Failed to read bundle: {e}"))?;
1414
1415    let container = crate::core::index_bundle::decrypt(&blob, &index_bundle_key()?)
1416        .map_err(|e| e.to_string())?;
1417    crate::core::index_bundle::unpack(project_root, &container).map_err(|e| e.to_string())
1418}
1419
1420/// `GET /api/sync/index` — hosted-bucket listing + quota usage for the account.
1421pub fn index_bundle_status() -> Result<serde_json::Value, String> {
1422    let bearer = auth_bearer_token()?;
1423    let url = format!("{}/api/sync/index", api_url());
1424    let resp = ureq::get(&url)
1425        .header("Authorization", &format!("Bearer {bearer}"))
1426        .call()
1427        .map_err(|e| format!("Status fetch failed: {e}"))?;
1428    let body = resp
1429        .into_body()
1430        .read_to_string()
1431        .map_err(|e| format!("Failed to read response: {e}"))?;
1432    serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))
1433}
1434
1435#[cfg(test)]
1436#[path = "cloud_client/inline_tests.rs"]
1437mod tests;