Skip to main content

lean_ctx_cli/proxy_setup/
claude.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Claude Code settings proxy env wiring.
3
4use std::path::Path;
5
6use super::util::{is_local_lean_ctx_url, is_proxy_reachable, shell_anthropic_endpoint};
7
8/// Returns true when an Anthropic **API key** is available for the proxy to forward
9/// upstream.
10///
11/// The proxy never injects credentials (see `proxy/forward.rs` — only
12/// `ALLOWED_REQUEST_HEADERS` are forwarded), so it can only help Claude Code when the
13/// user runs in API-key (pay-as-you-go) mode. A Claude **Pro/Max subscription** login
14/// is reserved for direct use of Claude Code: Anthropic does not permit third-party
15/// tools to route requests through Free/Pro/Max credentials, so subscription traffic
16/// stays on `api.anthropic.com`. When this returns `false`, callers must NOT point
17/// Claude Code at the proxy.
18pub fn anthropic_api_key_available(home: &Path) -> bool {
19    // 1) Process environment — covers shells and Claude Code launched from them.
20    for var in ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"] {
21        if std::env::var(var).is_ok_and(|v| !v.trim().is_empty()) {
22            return true;
23        }
24    }
25
26    // 2) Claude Code settings.json — an explicit key, an auth token, or a dynamic
27    //    key helper all indicate API-key mode.
28    let settings_path =
29        lean_ctx::core::editor_registry::claude_state_dir(home).join("settings.json");
30    let Ok(content) = std::fs::read_to_string(&settings_path) else {
31        return false;
32    };
33    let Ok(doc) = lean_ctx::core::jsonc::parse_jsonc(&content) else {
34        return false;
35    };
36
37    if doc
38        .get("apiKeyHelper")
39        .and_then(|v| v.as_str())
40        .is_some_and(|v| !v.trim().is_empty())
41    {
42        return true;
43    }
44
45    let env = doc.get("env");
46    ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"]
47        .iter()
48        .any(|key| {
49            env.and_then(|e| e.get(*key))
50                .and_then(|v| v.as_str())
51                .is_some_and(|v| !v.trim().is_empty())
52        })
53}
54
55/// Explains why Claude Code was left pointing at `api.anthropic.com` instead of the
56/// proxy: Pro/Max subscription credentials must not be routed through third-party tools.
57fn warn_claude_subscription_skip() {
58    eprintln!("  \u{26a0} Claude Code: no ANTHROPIC_API_KEY detected (Pro/Max subscription?).");
59    eprintln!("    Anthropic does not permit third-party tools to route requests through a");
60    eprintln!("    Claude subscription login, so lean-ctx keeps it on api.anthropic.com.");
61    eprintln!("    Leaving ANTHROPIC_BASE_URL untouched so Claude Code keeps working.");
62    eprintln!("    Savings on a subscription: use the lean-ctx MCP tools (ctx_read /");
63    eprintln!("    ctx_search / ctx_shell). Pay-as-you-go? Set ANTHROPIC_API_KEY, then run:");
64    eprintln!("      lean-ctx proxy enable");
65}
66
67/// Remove a Claude redirect only when the caller supplies the exact URL it can
68/// prove lean-ctx previously wrote. Arbitrary local and remote endpoints stay.
69pub(crate) fn repair_claude_subscription_env(home: &Path, owned_url: &str) -> Result<(), String> {
70    use lean_ctx::core::config::Config;
71
72    let settings_path =
73        lean_ctx::core::editor_registry::claude_state_dir(home).join("settings.json");
74    let existing = match std::fs::read_to_string(&settings_path) {
75        Ok(content) if !content.trim().is_empty() => content,
76        Ok(_) => return Ok(()),
77        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
78        Err(error) => return Err(format!("read {}: {error}", settings_path.display())),
79    };
80    let mut doc = lean_ctx::core::jsonc::parse_jsonc(&existing)
81        .map_err(|error| format!("{} contains invalid JSON: {error}", settings_path.display()))?;
82    let current_url = doc
83        .get("env")
84        .and_then(|env| env.get("ANTHROPIC_BASE_URL"))
85        .and_then(|value| value.as_str())
86        .unwrap_or("");
87    if current_url != owned_url {
88        return Ok(());
89    }
90
91    let env = doc
92        .get_mut("env")
93        .and_then(|value| value.as_object_mut())
94        .ok_or_else(|| format!("{}.env must be a JSON object", settings_path.display()))?;
95    if let Some(upstream) = Config::load().proxy.anthropic_upstream {
96        env.insert(
97            "ANTHROPIC_BASE_URL".to_string(),
98            serde_json::Value::String(upstream),
99        );
100    } else {
101        env.remove("ANTHROPIC_BASE_URL");
102        if env.is_empty() {
103            doc.as_object_mut().map(|object| object.remove("env"));
104        }
105    }
106
107    let rendered = serde_json::to_string_pretty(&doc).map_err(|error| error.to_string())?;
108    lean_ctx::config_io::write_atomic_with_backup(&settings_path, &(rendered + "\n"))
109}
110
111pub(crate) fn uninstall_claude_env(home: &Path, quiet: bool) {
112    use lean_ctx::core::config::Config;
113
114    let settings_dir = lean_ctx::core::editor_registry::claude_state_dir(home);
115    let settings_path = settings_dir.join("settings.json");
116    let existing = match std::fs::read_to_string(&settings_path) {
117        Ok(s) if !s.trim().is_empty() => s,
118        _ => return,
119    };
120    let mut doc: serde_json::Value = match lean_ctx::core::jsonc::parse_jsonc(&existing) {
121        Ok(v) => v,
122        Err(_) => return,
123    };
124
125    let Some(env_obj) = doc.get_mut("env").and_then(|e| e.as_object_mut()) else {
126        return;
127    };
128
129    // #1972: only undo what lean-ctx wrote. Another gateway's URL — local
130    // (Omniroute on localhost:20128) or remote — is the user's and stays.
131    let owned = env_obj
132        .get("ANTHROPIC_BASE_URL")
133        .and_then(|v| v.as_str())
134        .is_some_and(is_local_lean_ctx_url);
135    if !owned {
136        return;
137    }
138
139    let cfg = Config::load();
140    if let Some(ref upstream) = cfg.proxy.anthropic_upstream {
141        env_obj.insert(
142            "ANTHROPIC_BASE_URL".to_string(),
143            serde_json::Value::String(upstream.clone()),
144        );
145        if !quiet {
146            println!("  ✓ Restored ANTHROPIC_BASE_URL → {upstream} in Claude Code settings");
147        }
148    } else {
149        env_obj.remove("ANTHROPIC_BASE_URL");
150        if env_obj.is_empty() {
151            doc.as_object_mut().map(|o| o.remove("env"));
152        }
153        if !quiet {
154            println!("  ✓ Removed ANTHROPIC_BASE_URL from Claude Code settings");
155        }
156    }
157
158    let content = serde_json::to_string_pretty(&doc).unwrap_or_default();
159    let _ = std::fs::write(&settings_path, content + "\n");
160}
161
162pub(crate) fn install_claude_env(home: &Path, port: u16, quiet: bool) {
163    install_claude_env_inner(home, port, quiet, false);
164}
165
166pub(crate) fn install_claude_env_inner(home: &Path, port: u16, quiet: bool, force: bool) {
167    use lean_ctx::core::config::{Config, normalize_url_opt};
168
169    let base = format!("http://127.0.0.1:{port}");
170
171    let settings_dir = lean_ctx::core::editor_registry::claude_state_dir(home);
172    let settings_path = settings_dir.join("settings.json");
173    let existing = std::fs::read_to_string(&settings_path).unwrap_or_default();
174    let mut doc: serde_json::Value = if existing.trim().is_empty() {
175        serde_json::json!({})
176    } else {
177        match lean_ctx::core::jsonc::parse_jsonc(&existing) {
178            Ok(v) => v,
179            Err(_) => return,
180        }
181    };
182
183    let current_url = doc
184        .get("env")
185        .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
186        .and_then(|v| v.as_str())
187        .unwrap_or("")
188        .to_string();
189
190    // SUBSCRIPTION GUARD: the proxy never injects credentials, and a Claude Pro/Max
191    // subscription login must not be routed through a third-party tool (Anthropic's
192    // OAuth terms). When no API key is detectable we must not point Claude Code at the
193    // proxy. `--force` overrides for power users whose
194    // key lives somewhere we cannot probe (e.g. a keychain or apiKeyHelper we missed).
195    if !force && !anthropic_api_key_available(home) {
196        if !quiet {
197            warn_claude_subscription_skip();
198        }
199        return;
200    }
201
202    if current_url == base {
203        if !quiet {
204            println!("  Claude Code proxy env already configured");
205        }
206        return;
207    }
208
209    // HARD GUARD: never overwrite an endpoint lean-ctx did not write unless
210    // --force. "Local" is not "ours": a gateway on another localhost port
211    // (#1972) is as much the user's as a remote one.
212    if let Some(upstream) = normalize_url_opt(&current_url)
213        && !is_local_lean_ctx_url(&upstream)
214    {
215        if Config::load_global().proxy.anthropic_upstream.is_none()
216            && let Err(e) =
217                Config::update_global(|c| c.proxy.anthropic_upstream = Some(upstream.clone()))
218        {
219            tracing::warn!("could not persist proxy upstream: {e}");
220        }
221
222        if !force {
223            if !quiet {
224                eprintln!("  \u{26a0} Custom endpoint detected: {upstream}");
225                eprintln!(
226                    "    Skipping proxy URL write. Use `lean-ctx proxy enable --force` to override."
227                );
228            }
229            return;
230        }
231        if !quiet {
232            println!("  Overriding custom endpoint (--force): {upstream}");
233        }
234    } else if current_url.trim().is_empty()
235        && let Some(upstream) = shell_anthropic_endpoint()
236    {
237        // The same guard for a gateway exported in the shell (#2280): the
238        // settings entry would shadow it and the proxy would relay the
239        // gateway's key to its default upstream.
240        if !force {
241            if !quiet {
242                eprintln!(
243                    "  \u{26a0} Custom endpoint detected in your shell environment: {upstream}"
244                );
245                eprintln!(
246                    "    Skipping proxy URL write. Use `lean-ctx proxy enable --force` to override."
247                );
248            }
249            return;
250        }
251        // Routing it through the proxy now: forward to the gateway, not to
252        // the default upstream.
253        if Config::load_global().proxy.anthropic_upstream.is_none()
254            && let Err(e) =
255                Config::update_global(|c| c.proxy.anthropic_upstream = Some(upstream.clone()))
256        {
257            tracing::warn!("could not persist proxy upstream: {e}");
258        }
259        if !quiet {
260            println!("  Overriding custom shell endpoint (--force): {upstream}");
261        }
262    }
263
264    if !is_proxy_reachable(port) {
265        if !quiet {
266            println!("  Skipping Claude Code proxy env (proxy not running on port {port})");
267        }
268        return;
269    }
270
271    if let Some(env_obj) = doc.as_object_mut().and_then(|o| {
272        o.entry("env")
273            .or_insert(serde_json::json!({}))
274            .as_object_mut()
275    }) {
276        env_obj.insert(
277            "ANTHROPIC_BASE_URL".to_string(),
278            serde_json::Value::String(base),
279        );
280    }
281
282    let _ = std::fs::create_dir_all(&settings_dir);
283    let content = serde_json::to_string_pretty(&doc).unwrap_or_default();
284    let _ = std::fs::write(&settings_path, content + "\n");
285    if !quiet {
286        println!("  Configured ANTHROPIC_BASE_URL in Claude Code settings");
287    }
288}