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 = std::env::var("DO_NOT_TRACK").ok();
527    let telemetry_override = std::env::var("LEAN_CTX_TELEMETRY").ok();
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    Ok(json["message"].as_str().unwrap_or("OK").to_string())
555}
556
557/// Delete every server-side aggregate associated with one installation ID.
558pub fn delete_remote_telemetry(
559    installation_id: &str,
560    deletion_token: &str,
561) -> Result<bool, String> {
562    let installation_id = uuid::Uuid::parse_str(installation_id)
563        .map_err(|_| "Invalid installation ID".to_string())?;
564    let url = format!(
565        "{}/api/telemetry/v2/installations/{installation_id}",
566        api_url()
567    );
568    if deletion_token.len() != 64
569        || !deletion_token
570            .bytes()
571            .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
572    {
573        return Err("Invalid telemetry deletion credential".to_string());
574    }
575    let response = ureq::delete(&url)
576        .header(
577            "Authorization",
578            &format!("TelemetryDelete v1.{deletion_token}"),
579        )
580        .call()
581        .map_err(|error| format!("Remote telemetry deletion failed: {error}"))?;
582    let status = response.status().as_u16();
583    let body = response
584        .into_body()
585        .read_to_string()
586        .map_err(|error| format!("Failed to read deletion response: {error}"))?;
587    deletion_confirmed(status, &body)
588}
589
590fn deletion_confirmed(status: u16, body: &str) -> Result<bool, String> {
591    if status == 204 {
592        return Ok(false);
593    }
594    let value: serde_json::Value = serde_json::from_str(body)
595        .map_err(|error| format!("Invalid deletion response: {error}"))?;
596    Ok(value.get("deleted").and_then(serde_json::Value::as_bool) == Some(true))
597}
598
599/// Result of a successful Wrapped publish (`POST /api/wrapped`). The `edit_token` is returned
600/// (and must be stored to delete/claim later) only on a *fresh* insert; on a signed re-publish
601/// the server updates the existing card in place and omits it (the client keeps the stored one).
602#[derive(serde::Deserialize)]
603pub struct PublishedCard {
604    pub id: String,
605    #[serde(default)]
606    pub edit_token: Option<String>,
607    #[serde(default)]
608    pub edit_token_challenge: Option<String>,
609    #[serde(default)]
610    pub challenge_expires_in_secs: Option<i64>,
611    pub url: String,
612    #[serde(skip)]
613    pub account_claimed: bool,
614}
615
616/// Publish a whitelisted Wrapped payload. Accepts either a bare payload (legacy anonymous) or a
617/// signed envelope `{payload_json, public_key, signature}` (login-less identity → server upsert).
618/// If the user is logged in, attaches a Bearer token so the server can auto-claim
619/// the card (leaderboard consolidation).
620pub fn publish_wrapped(payload: &serde_json::Value) -> Result<PublishedCard, String> {
621    let url = format!("{}/api/wrapped", api_url());
622
623    let mut req = ureq::post(&url).header("Content-Type", "application/json");
624    if let Ok(token) = auth_bearer_token() {
625        req = req.header("Authorization", &format!("Bearer {token}"));
626    }
627    let resp = req
628        .send(&serde_json::to_vec(payload).map_err(|e| format!("JSON error: {e}"))?)
629        .map_err(|e| format!("Publish failed: {e}"))?;
630
631    let resp_body = resp
632        .into_body()
633        .read_to_string()
634        .map_err(|e| format!("Failed to read response: {e}"))?;
635
636    serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
637}
638
639#[derive(serde::Deserialize)]
640struct RecoveredEditToken {
641    edit_token: String,
642}
643
644/// Exchange a one-time server challenge for a rotated edit token after the
645/// caller proves possession of the card's persistent publisher key.
646pub fn recover_wrapped_edit_token(
647    id: &str,
648    nonce: &str,
649    public_key: &str,
650    signature: &str,
651) -> Result<String, String> {
652    let url = format!("{}/api/wrapped/{id}/edit-token/recover", api_url());
653    let body = serde_json::json!({
654        "nonce": nonce,
655        "public_key": public_key,
656        "signature": signature,
657    });
658    let resp = ureq::post(&url)
659        .header("Content-Type", "application/json")
660        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
661        .map_err(|e| format!("Edit-token recovery failed: {e}"))?;
662    let response = resp
663        .into_body()
664        .read_to_string()
665        .map_err(|e| format!("Failed to read response: {e}"))?;
666    let recovered: RecoveredEditToken =
667        serde_json::from_str(&response).map_err(|e| format!("Invalid recovery response: {e}"))?;
668    if recovered.edit_token.is_empty() {
669        return Err("Invalid recovery response: empty edit token".to_string());
670    }
671    Ok(recovered.edit_token)
672}
673
674/// Delete a previously published card using its one-time `edit_token` (sent as `X-Edit-Token`).
675///
676/// Idempotent: a card the server no longer has (404/410) counts as removed.
677/// The caller's goal is "this page is not public any more", and failing a
678/// takedown because it already succeeded would strand the local record with no
679/// way to clear it (#1726).
680pub fn unpublish_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
681    let url = format!("{}/api/wrapped/{id}", api_url());
682
683    match ureq::delete(&url).header("X-Edit-Token", edit_token).call() {
684        // Removed now, or already gone (404/410) — either way it is not public.
685        Ok(_) | Err(ureq::Error::StatusCode(404 | 410)) => Ok(()),
686        Err(e) => Err(format!("Unpublish failed: {e}")),
687    }
688}
689
690/// Bind a published card to the logged-in account so the leaderboard stacks all of the
691/// user's machines under one entry (#488). Auth: account Bearer + the card's `edit_token`
692/// (`X-Edit-Token`). Server: `POST /api/wrapped/:id/claim`. Requires being logged in.
693pub fn claim_wrapped(id: &str, edit_token: &str) -> Result<(), String> {
694    let bearer = auth_bearer_token()?;
695    let url = format!("{}/api/wrapped/{id}/claim", api_url());
696
697    ureq::post(&url)
698        .header("Authorization", &format!("Bearer {bearer}"))
699        .header("X-Edit-Token", edit_token)
700        .send_empty()
701        .map_err(|e| format!("Claim failed: {e}"))?;
702    Ok(())
703}
704
705/// A freshly minted pairing code for login-less machine linking (GH #736).
706#[derive(serde::Deserialize)]
707pub struct LinkCode {
708    pub code: String,
709    pub expires_in_secs: i64,
710}
711
712/// Start a login-less machine link: mint a short-lived pairing code for this card.
713/// Auth: the card's `edit_token` only — no account. Server: `POST /api/wrapped/:id/link/start`.
714pub fn link_wrapped_start(id: &str, edit_token: &str) -> Result<LinkCode, String> {
715    let url = format!("{}/api/wrapped/{id}/link/start", api_url());
716
717    let resp = ureq::post(&url)
718        .header("X-Edit-Token", edit_token)
719        .send_empty()
720        .map_err(|e| format!("Link start failed: {e}"))?;
721    let body = resp
722        .into_body()
723        .read_to_string()
724        .map_err(|e| format!("Failed to read response: {e}"))?;
725    serde_json::from_str(&body).map_err(|e| format!("Invalid response: {e}"))
726}
727
728/// Complete a login-less machine link on the second machine: join this card into
729/// the pairing code's group. Auth: this card's `edit_token` — no account.
730/// Server: `POST /api/wrapped/:id/link/complete`.
731pub fn link_wrapped_complete(id: &str, edit_token: &str, code: &str) -> Result<(), String> {
732    let url = format!("{}/api/wrapped/{id}/link/complete", api_url());
733    let body = serde_json::json!({ "code": code });
734
735    ureq::post(&url)
736        .header("X-Edit-Token", edit_token)
737        .header("Content-Type", "application/json")
738        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
739        .map_err(|e| match e {
740            ureq::Error::StatusCode(404) => {
741                "code invalid or expired — mint a fresh one with  lean-ctx gain --link".to_string()
742            }
743            other => format!("Link failed: {other}"),
744        })?;
745    Ok(())
746}
747
748/// Push the knowledge store as a zero-knowledge vault (GL #467): entries are
749/// sealed client-side (XChaCha20-Poly1305, domain-separated HKDF key) — the
750/// backend stores ciphertext and can never read them. The first vault push
751/// also purges the account's legacy plaintext rows server-side.
752pub fn push_knowledge(entries: &[serde_json::Value]) -> Result<String, String> {
753    let bearer = auth_bearer_token()?;
754    let key = knowledge_vault_key()?;
755    let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
756    let url = format!("{}/api/sync/knowledge", api_url());
757
758    let resp = ureq::post(&url)
759        .header("Authorization", &format!("Bearer {bearer}"))
760        .header("Content-Type", "application/octet-stream")
761        .header("X-Entry-Count", &entries.len().to_string())
762        .header("X-Device-Label", &device_label())
763        .send(blob.as_slice())
764        .map_err(|e| format!("Push failed: {e}"))?;
765
766    let resp_body = resp
767        .into_body()
768        .read_to_string()
769        .map_err(|e| format!("Failed to read response: {e}"))?;
770
771    let json: serde_json::Value =
772        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
773
774    Ok(format!(
775        "{} entries synced (end-to-end encrypted)",
776        json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
777    ))
778}
779
780/// The account's knowledge-vault key — same stable-API-key derivation rule as
781/// [`index_bundle_key`], different HKDF domain (`knowledge-vault-v1`).
782fn knowledge_vault_key() -> Result<[u8; 32], String> {
783    let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
784    if api_key.trim().is_empty() {
785        return Err("Not logged in. Run: lean-ctx login".into());
786    }
787    Ok(crate::core::knowledge_vault::derive_vault_key(&api_key))
788}
789
790pub fn pull_cloud_models() -> Result<serde_json::Value, String> {
791    let bearer = auth_bearer_token()?;
792    let url = format!("{}/api/cloud/models", api_url());
793
794    let resp = ureq::get(&url)
795        .header("Authorization", &format!("Bearer {bearer}"))
796        .call()
797        .map_err(|e| {
798            let msg = e.to_string();
799            if msg.contains("403") {
800                "This feature is not available for your account.".to_string()
801            } else {
802                format!("Connection failed. Check your internet connection. ({e})")
803            }
804        })?;
805
806    let resp_body = resp
807        .into_body()
808        .read_to_string()
809        .map_err(|e| format!("Failed to read response: {e}"))?;
810
811    serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))
812}
813
814pub fn save_cloud_models(data: &serde_json::Value) -> std::io::Result<()> {
815    let dir = config_dir();
816    std::fs::create_dir_all(&dir)?;
817    let json = serde_json::to_string_pretty(data).map_err(std::io::Error::other)?;
818    std::fs::write(dir.join("cloud_models.json"), json)
819}
820
821pub fn load_cloud_models() -> Option<serde_json::Value> {
822    let path = config_dir().join("cloud_models.json");
823    let data = std::fs::read_to_string(path).ok()?;
824    serde_json::from_str(&data).ok()
825}
826
827/// Fetch the public community leaderboard as JSON (`{ "entries": [ … ] }`).
828///
829/// Public, login-less endpoint (`GET /api/leaderboard`, contract:
830/// `docs/contracts/wrapped-permalink-v1.md`). The dashboard proxies it
831/// same-origin (#466) so the browser never reaches `api.leanctx.com` directly —
832/// the dashboard CSP pins `connect-src` to `'self'`. A 10s global timeout keeps
833/// a slow upstream from tying up a dashboard request thread.
834pub fn fetch_leaderboard() -> Result<serde_json::Value, String> {
835    let url = format!("{}/api/leaderboard", api_url());
836    let resp = ureq::get(&url)
837        .config()
838        .timeout_global(Some(std::time::Duration::from_secs(10)))
839        .build()
840        .call()
841        .map_err(|e| format!("Could not reach the leaderboard service: {e}"))?;
842    let body = resp
843        .into_body()
844        .read_to_string()
845        .map_err(|e| format!("Failed to read leaderboard response: {e}"))?;
846    serde_json::from_str(&body).map_err(|e| format!("Invalid leaderboard JSON: {e}"))
847}
848
849pub fn is_cloud_user() -> bool {
850    let path = config_dir().join("plan.txt");
851    std::fs::read_to_string(path).is_ok_and(|value| plan_value_has_cloud_access(&value))
852}
853
854fn plan_value_has_cloud_access(value: &str) -> bool {
855    value.trim().eq_ignore_ascii_case("cloud")
856        || crate::core::billing::Plan::parse_known(value)
857            .is_some_and(|plan| plan.rank() >= crate::core::billing::Plan::Pro.rank())
858}
859
860/// Days a cached plan keeps granting its hosted entitlements while the billing
861/// backend is unreachable. Generous on purpose: a network blip or a weekend
862/// offline must never silently demote a paying user to Community.
863pub const PLAN_GRACE_DAYS: i64 = 14;
864
865fn plan_cache_path() -> PathBuf {
866    config_dir().join("plan.json")
867}
868
869/// The locally cached plan plus *when* it was last confirmed against the billing
870/// backend. The timestamp is what powers offline grace.
871#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
872pub struct PlanCache {
873    pub plan: String,
874    /// Unix seconds of the last successful backend confirmation.
875    pub verified_at: i64,
876}
877
878pub fn save_plan(plan: &str) -> std::io::Result<()> {
879    let dir = config_dir();
880    std::fs::create_dir_all(&dir)?;
881    // Legacy flat file kept for back-compat (`is_cloud_user` still reads it).
882    std::fs::write(dir.join("plan.txt"), plan)?;
883    // Structured cache carrying the verification time for offline grace.
884    let cache = PlanCache {
885        plan: plan.to_string(),
886        verified_at: now_unix(),
887    };
888    let json = serde_json::to_string_pretty(&cache).map_err(std::io::Error::other)?;
889    std::fs::write(plan_cache_path(), json)
890}
891
892/// The cached plan, if any. Prefers the structured `plan.json`; falls back to a
893/// legacy `plan.txt` (no timestamp → `verified_at = 0`, i.e. immediately past
894/// grace until the next successful refresh re-stamps it).
895pub fn cached_plan() -> Option<PlanCache> {
896    if let Ok(data) = std::fs::read_to_string(plan_cache_path())
897        && let Ok(cache) = serde_json::from_str::<PlanCache>(&data)
898    {
899        return Some(cache);
900    }
901    let legacy = std::fs::read_to_string(config_dir().join("plan.txt")).ok()?;
902    Some(PlanCache {
903        plan: legacy.trim().to_string(),
904        verified_at: 0,
905    })
906}
907
908/// Where an effective plan came from — drives the wording in `billing status`
909/// and the dashboard badge.
910#[derive(Debug, Clone, Copy, PartialEq, Eq)]
911pub enum PlanSource {
912    /// Just confirmed against the backend this run.
913    Live,
914    /// Served from the local cache and still within the grace window.
915    Cached,
916    /// Cached confirmation is past the grace window → demoted to Community.
917    Expired,
918    /// No cached plan at all (never logged in / never synced) → Community.
919    None,
920}
921
922/// A resolved plan plus provenance and donation/support recognition.
923#[derive(Debug, Clone)]
924pub struct EffectivePlan {
925    pub plan: crate::core::billing::Plan,
926    pub supporter_recognition: bool,
927    pub source: PlanSource,
928    pub verified_at: Option<i64>,
929    pub grace_days: i64,
930}
931
932/// Pure grace check (no clock/IO) so it is unit-testable: is a plan confirmed at
933/// `verified_at` still within `grace_days` of `now`? Returns the age in days too.
934#[must_use]
935pub fn plan_within_grace(verified_at: i64, now: i64, grace_days: i64) -> (bool, i64) {
936    let age_days = (now - verified_at).max(0) / 86_400;
937    (age_days <= grace_days, age_days)
938}
939
940/// Resolve the effective plan from the **local cache only** (no network),
941/// applying the offline-grace policy. Use this on hot paths (dashboard
942/// requests); use [`refresh_effective_plan`] when a live confirmation is
943/// acceptable.
944///
945/// Commercial entitlements (incl. any self-hosted offline Enterprise license)
946/// are resolved by the control-plane and reach this client as the cached/live
947/// plan — the open engine carries no licensing logic (oss-plane-separation-v1).
948#[must_use]
949pub fn resolve_effective_plan_cached() -> EffectivePlan {
950    let grace_days = PLAN_GRACE_DAYS;
951    let Some(cache) = cached_plan() else {
952        return EffectivePlan {
953            plan: crate::core::billing::Plan::Community,
954            supporter_recognition: false,
955            source: PlanSource::None,
956            verified_at: None,
957            grace_days,
958        };
959    };
960    let (fresh, _age) = plan_within_grace(cache.verified_at, now_unix(), grace_days);
961    if fresh {
962        let selection = crate::core::billing::Plan::parse_selection(&cache.plan);
963        EffectivePlan {
964            plan: selection.plan,
965            supporter_recognition: selection.supporter_recognition,
966            source: PlanSource::Cached,
967            verified_at: Some(cache.verified_at),
968            grace_days,
969        }
970    } else {
971        // Fail closed for paid entitlements once grace lapses. Explicit
972        // Community/Trust Core capabilities remain unaffected.
973        EffectivePlan {
974            plan: crate::core::billing::Plan::Community,
975            supporter_recognition: false,
976            source: PlanSource::Expired,
977            verified_at: Some(cache.verified_at),
978            grace_days,
979        }
980    }
981}
982
983/// Authoritative, local-only paid-capability decision from a verified signed
984/// entitlement. Unsigned plan caches are display state and never reach here.
985#[must_use]
986pub fn signed_entitlement_allows(capability: &str) -> bool {
987    entitlement_cache::resolve_cached().allows(capability)
988}
989
990/// Resolve signed rights for reports without trusting unsigned display plans.
991#[must_use]
992pub fn resolve_verified_plan_cached() -> VerifiedEffectivePlan {
993    entitlement_cache::resolve_cached()
994}
995
996/// Refresh signed authority, retaining only cryptographically valid grace.
997#[must_use]
998pub fn refresh_verified_plan() -> VerifiedEffectivePlan {
999    entitlement_cache::refresh()
1000}
1001
1002#[cfg(test)]
1003pub(crate) fn install_test_signed_entitlement_paths(
1004    trust: PathBuf,
1005    credentials: PathBuf,
1006    cache: PathBuf,
1007    anchors: Vec<(String, [u8; 32])>,
1008) -> impl Drop {
1009    entitlement_cache::install_test_paths(trust, credentials, cache, anchors)
1010}
1011
1012#[cfg(test)]
1013pub(crate) fn accept_test_signed_entitlement(account: &str, bytes: &[u8]) {
1014    entitlement_cache::accept_test_cache(account, bytes);
1015}
1016
1017/// Best-effort *live* resolve: try the backend (refreshing the cache on success),
1018/// otherwise fall back to the cached-with-grace plan. Suitable for explicit
1019/// commands like `lean-ctx billing status` where a network round-trip is fine.
1020#[must_use]
1021pub fn refresh_effective_plan() -> EffectivePlan {
1022    if is_logged_in()
1023        && let Ok(plan_str) = fetch_plan()
1024    {
1025        let _ = save_plan(&plan_str);
1026        let selection = crate::core::billing::Plan::parse_selection(&plan_str);
1027        return EffectivePlan {
1028            plan: selection.plan,
1029            supporter_recognition: selection.supporter_recognition,
1030            source: PlanSource::Live,
1031            verified_at: Some(now_unix()),
1032            grace_days: PLAN_GRACE_DAYS,
1033        };
1034    }
1035    resolve_effective_plan_cached()
1036}
1037
1038pub fn fetch_plan() -> Result<String, String> {
1039    let bearer = auth_bearer_token()?;
1040    let url = format!("{}/api/auth/me", api_url());
1041
1042    let resp = ureq::get(&url)
1043        .header("Authorization", &format!("Bearer {bearer}"))
1044        .call()
1045        .map_err(|e| format!("Failed to check plan: {e}"))?;
1046
1047    let resp_body = resp
1048        .into_body()
1049        .read_to_string()
1050        .map_err(|e| format!("Failed to read response: {e}"))?;
1051
1052    let json: serde_json::Value =
1053        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
1054
1055    Ok(json["plan"].as_str().unwrap_or("community").to_string())
1056}
1057
1058/// Start a Stripe Checkout session for the logged-in account and return the
1059/// hosted URL to open. `plan` is e.g. `"pro"` or `"team"`; `interval` is
1060/// `"monthly"` or `"yearly"`. The open backend proxies this to the private
1061/// billing plane (which returns `503` when billing is not configured).
1062pub fn start_checkout(plan: &str, interval: &str) -> Result<String, String> {
1063    let bearer = auth_bearer_token()?;
1064    let url = format!("{}/api/account/checkout", api_url());
1065    let body = serde_json::json!({ "plan": plan, "interval": interval });
1066
1067    let resp = ureq::post(&url)
1068        .header("Authorization", &format!("Bearer {bearer}"))
1069        .header("Content-Type", "application/json")
1070        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
1071        .map_err(|e| format!("Checkout request failed: {e}"))?;
1072
1073    let resp_body = resp
1074        .into_body()
1075        .read_to_string()
1076        .map_err(|e| format!("Failed to read response: {e}"))?;
1077
1078    let json: serde_json::Value =
1079        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid response: {e}"))?;
1080
1081    parse_checkout_url(&json)
1082}
1083
1084fn parse_checkout_url(json: &serde_json::Value) -> Result<String, String> {
1085    let raw = json["url"]
1086        .as_str()
1087        .ok_or_else(|| "Billing did not return a checkout URL.".to_string())?;
1088    // The URL is printed to the terminal and handed to the browser opener:
1089    // control characters (CR/LF, ESC sequences) must never pass through.
1090    if raw.chars().any(char::is_control) {
1091        return Err("Billing returned an invalid checkout URL.".to_string());
1092    }
1093    let parsed = reqwest::Url::parse(raw)
1094        .map_err(|_| "Billing returned an invalid checkout URL.".to_string())?;
1095    if parsed.scheme() != "https"
1096        || parsed.host_str().is_none()
1097        || !parsed.username().is_empty()
1098        || parsed.password().is_some()
1099    {
1100        return Err("Billing returned an invalid checkout URL.".to_string());
1101    }
1102    Ok(parsed.to_string())
1103}
1104
1105pub fn push_commands(entries: &[serde_json::Value]) -> Result<String, String> {
1106    let bearer = auth_bearer_token()?;
1107    let url = format!("{}/api/sync/commands", api_url());
1108    let body = serde_json::json!({ "commands": entries });
1109    let resp = ureq::post(&url)
1110        .header("Authorization", &format!("Bearer {bearer}"))
1111        .header("Content-Type", "application/json")
1112        .header("X-Device-Label", &device_label())
1113        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
1114        .map_err(|e| format!("Push failed: {e}"))?;
1115    let resp_body = resp
1116        .into_body()
1117        .read_to_string()
1118        .map_err(|e| format!("Failed to read response: {e}"))?;
1119    let json: serde_json::Value =
1120        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1121    Ok(format!(
1122        "{} commands synced",
1123        json["synced"].as_i64().unwrap_or(0)
1124    ))
1125}
1126
1127pub fn push_cep(entries: &[serde_json::Value]) -> Result<String, String> {
1128    let bearer = auth_bearer_token()?;
1129    let url = format!("{}/api/sync/cep", api_url());
1130    let body = serde_json::json!({ "scores": entries });
1131    let resp = ureq::post(&url)
1132        .header("Authorization", &format!("Bearer {bearer}"))
1133        .header("Content-Type", "application/json")
1134        .header("X-Device-Label", &device_label())
1135        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
1136        .map_err(|e| format!("Push failed: {e}"))?;
1137    let resp_body = resp
1138        .into_body()
1139        .read_to_string()
1140        .map_err(|e| format!("Failed to read response: {e}"))?;
1141    let json: serde_json::Value =
1142        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1143    Ok(format!(
1144        "{} sessions synced",
1145        json["synced"].as_i64().unwrap_or(0)
1146    ))
1147}
1148
1149pub fn push_gain(entries: &[serde_json::Value]) -> Result<String, String> {
1150    let bearer = auth_bearer_token()?;
1151    let url = format!("{}/api/sync/gain", api_url());
1152    let body = serde_json::json!({ "scores": entries });
1153    let resp = ureq::post(&url)
1154        .header("Authorization", &format!("Bearer {bearer}"))
1155        .header("Content-Type", "application/json")
1156        .header("X-Device-Label", &device_label())
1157        .send(&serde_json::to_vec(&body).map_err(|e| format!("JSON error: {e}"))?)
1158        .map_err(|e| format!("Push failed: {e}"))?;
1159    let resp_body = resp
1160        .into_body()
1161        .read_to_string()
1162        .map_err(|e| format!("Failed to read response: {e}"))?;
1163    let json: serde_json::Value =
1164        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1165    Ok(format!(
1166        "{} gain scores synced",
1167        json["synced"].as_i64().unwrap_or(0)
1168    ))
1169}
1170
1171/// Push gotchas as a zero-knowledge vault (GL #467 follow-up): sealed
1172/// client-side under the `gotcha-vault-v1` HKDF domain — the backend stores
1173/// ciphertext only and purges the account's legacy plaintext rows on the
1174/// first vault push.
1175pub fn push_gotchas(entries: &[serde_json::Value]) -> Result<String, String> {
1176    let bearer = auth_bearer_token()?;
1177    let key = gotcha_vault_key()?;
1178    let blob = crate::core::knowledge_vault::seal(entries, &key).map_err(|e| e.to_string())?;
1179    let url = format!("{}/api/sync/gotchas", api_url());
1180
1181    let resp = ureq::post(&url)
1182        .header("Authorization", &format!("Bearer {bearer}"))
1183        .header("Content-Type", "application/octet-stream")
1184        .header("X-Entry-Count", &entries.len().to_string())
1185        .header("X-Device-Label", &device_label())
1186        .send(blob.as_slice())
1187        .map_err(|e| format!("Push failed: {e}"))?;
1188    let resp_body = resp
1189        .into_body()
1190        .read_to_string()
1191        .map_err(|e| format!("Failed to read response: {e}"))?;
1192    let json: serde_json::Value =
1193        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1194    Ok(format!(
1195        "{} gotchas synced (end-to-end encrypted)",
1196        json["entry_count"].as_i64().unwrap_or(entries.len() as i64)
1197    ))
1198}
1199
1200/// The account's gotcha-vault key — own HKDF domain (`gotcha-vault-v1`),
1201/// derivation rule identical to [`knowledge_vault_key`].
1202fn gotcha_vault_key() -> Result<[u8; 32], String> {
1203    let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
1204    if api_key.trim().is_empty() {
1205        return Err("Not logged in. Run: lean-ctx login".into());
1206    }
1207    Ok(crate::core::knowledge_vault::derive_gotcha_vault_key(
1208        &api_key,
1209    ))
1210}
1211
1212pub fn push_buddy(data: &serde_json::Value) -> Result<String, String> {
1213    let bearer = auth_bearer_token()?;
1214    let url = format!("{}/api/sync/buddy", api_url());
1215    let resp = ureq::post(&url)
1216        .header("Authorization", &format!("Bearer {bearer}"))
1217        .header("Content-Type", "application/json")
1218        .header("X-Device-Label", &device_label())
1219        .send(&serde_json::to_vec(data).map_err(|e| format!("JSON error: {e}"))?)
1220        .map_err(|e| format!("Push failed: {e}"))?;
1221    let resp_body = resp
1222        .into_body()
1223        .read_to_string()
1224        .map_err(|e| format!("Failed to read response: {e}"))?;
1225    let _json: serde_json::Value =
1226        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1227    Ok("Buddy synced".to_string())
1228}
1229
1230pub fn push_feedback(entries: &[serde_json::Value]) -> Result<String, String> {
1231    let bearer = auth_bearer_token()?;
1232    let url = format!("{}/api/sync/feedback", api_url());
1233    let resp = ureq::post(&url)
1234        .header("Authorization", &format!("Bearer {bearer}"))
1235        .header("Content-Type", "application/json")
1236        .header("X-Device-Label", &device_label())
1237        .send(&serde_json::to_vec(entries).map_err(|e| format!("JSON error: {e}"))?)
1238        .map_err(|e| format!("Push failed: {e}"))?;
1239    let resp_body = resp
1240        .into_body()
1241        .read_to_string()
1242        .map_err(|e| format!("Failed to read response: {e}"))?;
1243    let json: serde_json::Value =
1244        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1245    Ok(format!(
1246        "{} thresholds synced",
1247        json["synced"].as_i64().unwrap_or(0)
1248    ))
1249}
1250
1251/// The signed-in account's email, for status displays.
1252pub fn account_email() -> Option<String> {
1253    load_credentials().map(|c| c.email)
1254}
1255
1256/// `GET /api/account/cloud` — the Personal Cloud dashboard payload (entitlement
1257/// gate, per-bucket sync footprint, buddy, usage totals). Powers
1258/// `lean-ctx cloud status`, mirroring what leanctx.com/account/cloud shows.
1259pub fn fetch_account_cloud() -> Result<serde_json::Value, String> {
1260    let bearer = auth_bearer_token()?;
1261    let url = format!("{}/api/account/cloud", api_url());
1262
1263    let resp = ureq::get(&url)
1264        .header("Authorization", &format!("Bearer {bearer}"))
1265        .call()
1266        .map_err(|e| format!("Status fetch failed: {e}"))?;
1267
1268    let resp_body = resp
1269        .into_body()
1270        .read_to_string()
1271        .map_err(|e| format!("Failed to read response: {e}"))?;
1272
1273    serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))
1274}
1275
1276/// Pull the knowledge store: vault-first (encrypted blob, decrypted locally),
1277/// with a legacy plaintext fallback for accounts that never pushed a vault.
1278pub fn pull_knowledge() -> Result<Vec<serde_json::Value>, String> {
1279    let bearer = auth_bearer_token()?;
1280    let url = format!("{}/api/sync/knowledge", api_url());
1281
1282    // Vault path (GL #467).
1283    match ureq::get(&url)
1284        .header("Authorization", &format!("Bearer {bearer}"))
1285        .header("Accept", "application/octet-stream")
1286        .call()
1287    {
1288        Ok(resp) => {
1289            let is_blob = resp
1290                .headers()
1291                .get("content-type")
1292                .and_then(|v| v.to_str().ok())
1293                .is_some_and(|v| v.starts_with("application/octet-stream"));
1294            if is_blob {
1295                let mut blob = Vec::new();
1296                use std::io::Read;
1297                resp.into_body()
1298                    .into_reader()
1299                    .read_to_end(&mut blob)
1300                    .map_err(|e| format!("Failed to read vault: {e}"))?;
1301                let key = knowledge_vault_key()?;
1302                return crate::core::knowledge_vault::open(&blob, &key).map_err(|e| e.to_string());
1303            }
1304            // Pre-vault server ignored the Accept header and answered with
1305            // the legacy JSON listing — parse it directly.
1306            let body = resp
1307                .into_body()
1308                .read_to_string()
1309                .map_err(|e| format!("Failed to read response: {e}"))?;
1310            return serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"));
1311        }
1312        // No vault yet → fall through to the legacy listing.
1313        Err(ureq::Error::StatusCode(404)) => {}
1314        Err(e) => return Err(format!("Pull failed: {e}")),
1315    }
1316
1317    let resp = ureq::get(&url)
1318        .header("Authorization", &format!("Bearer {bearer}"))
1319        .call()
1320        .map_err(|e| format!("Pull failed: {e}"))?;
1321
1322    let resp_body = resp
1323        .into_body()
1324        .read_to_string()
1325        .map_err(|e| format!("Failed to read response: {e}"))?;
1326
1327    let entries: Vec<serde_json::Value> =
1328        serde_json::from_str(&resp_body).map_err(|e| format!("Invalid JSON: {e}"))?;
1329
1330    Ok(entries)
1331}
1332
1333// ── Hosted Personal Index (GL #392) ──────────────────────────────────────────
1334// Contract: docs/contracts/hosted-personal-index-v1.md. Bundles are encrypted
1335// client-side (core::index_bundle); the backend only ever sees ciphertext.
1336
1337/// The account's bundle encryption key, HKDF-derived from the stable API key
1338/// (never from the rotating OAuth token — the key must be identical on every
1339/// logged-in device).
1340fn index_bundle_key() -> Result<[u8; 32], String> {
1341    let api_key = load_api_key().ok_or("Not logged in. Run: lean-ctx login")?;
1342    if api_key.trim().is_empty() {
1343        return Err("Not logged in. Run: lean-ctx login".into());
1344    }
1345    Ok(crate::core::index_bundle::derive_key(&api_key))
1346}
1347
1348/// Pack, encrypt and upload the project's index bundle.
1349/// Returns `(project_hash, encrypted_size_bytes)`.
1350pub fn push_index_bundle(project_root: &std::path::Path) -> Result<(String, u64), String> {
1351    let (container, manifest) =
1352        crate::core::index_bundle::pack(project_root).map_err(|e| e.to_string())?;
1353    let blob = crate::core::index_bundle::encrypt(&container, &index_bundle_key()?)
1354        .map_err(|e| e.to_string())?;
1355
1356    let bearer = auth_bearer_token()?;
1357    let url = format!("{}/api/sync/index/{}", api_url(), manifest.project_hash);
1358    let resp = ureq::put(&url)
1359        .header("Authorization", &format!("Bearer {bearer}"))
1360        .header("Content-Type", "application/octet-stream")
1361        .header("X-Device-Label", &device_label())
1362        .send(blob.as_slice())
1363        .map_err(|e| match e {
1364            ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1365                 Run: lean-ctx cloud upgrade --plan pro"
1366                .to_string(),
1367            ureq::Error::StatusCode(413) => {
1368                "Quota exceeded — the push was blocked (nothing is billed). \
1369                 Free space with `lean-ctx sync index status` / delete, then retry."
1370                    .to_string()
1371            }
1372            other => format!("Push failed: {other}"),
1373        })?;
1374
1375    let body = resp
1376        .into_body()
1377        .read_to_string()
1378        .map_err(|e| format!("Failed to read response: {e}"))?;
1379    let _ack: serde_json::Value =
1380        serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))?;
1381    Ok((manifest.project_hash, blob.len() as u64))
1382}
1383
1384/// Download, decrypt and unpack the hosted bundle for this project.
1385/// Returns the bundle manifest on success.
1386pub fn pull_index_bundle(
1387    project_root: &std::path::Path,
1388) -> Result<crate::core::index_bundle::BundleManifest, String> {
1389    let project_hash = crate::core::index_namespace::namespace_hash(project_root);
1390    let bearer = auth_bearer_token()?;
1391    let url = format!("{}/api/sync/index/{project_hash}", api_url());
1392
1393    let resp = ureq::get(&url)
1394        .header("Authorization", &format!("Bearer {bearer}"))
1395        .call()
1396        .map_err(|e| match e {
1397            ureq::Error::StatusCode(404) => format!(
1398                "No hosted index for this project yet ({project_hash}). \
1399                 Push one from a device with a built index: lean-ctx sync index push"
1400            ),
1401            ureq::Error::StatusCode(402) => "Hosted index requires lean-ctx Pro. \
1402                 Run: lean-ctx cloud upgrade --plan pro"
1403                .to_string(),
1404            other => format!("Pull failed: {other}"),
1405        })?;
1406
1407    let mut blob = Vec::new();
1408    use std::io::Read;
1409    resp.into_body()
1410        .into_reader()
1411        .read_to_end(&mut blob)
1412        .map_err(|e| format!("Failed to read bundle: {e}"))?;
1413
1414    let container = crate::core::index_bundle::decrypt(&blob, &index_bundle_key()?)
1415        .map_err(|e| e.to_string())?;
1416    crate::core::index_bundle::unpack(project_root, &container).map_err(|e| e.to_string())
1417}
1418
1419/// `GET /api/sync/index` — hosted-bucket listing + quota usage for the account.
1420pub fn index_bundle_status() -> Result<serde_json::Value, String> {
1421    let bearer = auth_bearer_token()?;
1422    let url = format!("{}/api/sync/index", api_url());
1423    let resp = ureq::get(&url)
1424        .header("Authorization", &format!("Bearer {bearer}"))
1425        .call()
1426        .map_err(|e| format!("Status fetch failed: {e}"))?;
1427    let body = resp
1428        .into_body()
1429        .read_to_string()
1430        .map_err(|e| format!("Failed to read response: {e}"))?;
1431    serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))
1432}
1433
1434#[cfg(test)]
1435#[path = "cloud_client/inline_tests.rs"]
1436mod tests;