Skip to main content

lean_ctx/proxy_setup/
util.rs

1//! Shared proxy-setup constants and helpers.
2
3pub(crate) const PROXY_ENV_START: &str = "# >>> lean-ctx proxy env >>>";
4pub(crate) const PROXY_ENV_END: &str = "# <<< lean-ctx proxy env <<<";
5pub(crate) const DEFAULT_PROXY_PORT: u16 = 4444;
6
7/// Comment written in place of the `ANTHROPIC_BASE_URL` export when no Anthropic API
8/// key is detectable. Anthropic does not permit third-party tools to route requests
9/// through a Claude Pro/Max subscription login, so we must not route it through the
10/// proxy.
11pub(crate) const ANTHROPIC_OMITTED_NOTE: &str = "ANTHROPIC_BASE_URL omitted: a Claude Pro/Max subscription login stays on api.anthropic.com (set ANTHROPIC_API_KEY to route Claude through the proxy)";
12
13/// Comment written when Grok is not routable through the proxy (no session and no API key).
14pub(crate) const GROK_OMITTED_NOTE: &str = "Grok proxy env omitted: run `grok login` (subscription) or set XAI_API_KEY to route Grok through lean-ctx";
15
16/// Comment written when Command Code is not routable through the proxy (no session and no API key).
17pub(crate) const COMMANDCODE_OMITTED_NOTE: &str =
18    "Command Code omitted (no ~/.commandcode auth — run `cmd login` or set COMMAND_CODE_API_KEY)";
19
20/// Comment written in place of the `OPENAI_BASE_URL` export when Codex is signed
21/// in with a ChatGPT subscription (#1685).
22///
23/// `api.openai.com` accepts API keys only; a subscription OAuth token sent to its
24/// `/v1` rail comes back as `401 … Missing scopes: api.responses.write`, which
25/// reads like an organization-permission problem and is not one.
26pub(crate) const OPENAI_OMITTED_NOTE: &str = "OPENAI_BASE_URL omitted: Codex is signed in with a ChatGPT subscription, whose token only authenticates against chatgpt.com (set OPENAI_API_KEY to route OpenAI through the proxy)";
27
28/// True when `url` is the lean-ctx proxy itself: a loopback base URL on a port
29/// lean-ctx owns. Callers use this to decide what lean-ctx may overwrite or
30/// remove, so "any localhost URL" is not enough — another local gateway
31/// (Omniroute, LiteLLM, a corporate relay) belongs to the user (#1972).
32pub fn is_local_lean_ctx_url(url: &str) -> bool {
33    is_owned_proxy_url(url, &owned_proxy_ports())
34}
35
36/// [`is_local_lean_ctx_url`], also owning `install_port` — the port an install
37/// pass is wiring right now, which may differ from the configured one.
38pub(crate) fn is_lean_ctx_url_on(url: &str, install_port: Option<u16>) -> bool {
39    is_local_lean_ctx_url(url) || install_port.is_some_and(|port| is_owned_proxy_url(url, &[port]))
40}
41
42/// The ports a lean-ctx proxy listens on: the configured or UID-derived port,
43/// plus the historical default that older installs wrote.
44fn owned_proxy_ports() -> [u16; 3] {
45    [default_port(), uid_based_port(), DEFAULT_PROXY_PORT]
46}
47
48/// [`is_local_lean_ctx_url`] with the owned ports passed in, so the rule is
49/// testable without reading config or the environment.
50pub(crate) fn is_owned_proxy_url(url: &str, ports: &[u16]) -> bool {
51    loopback_port(url).is_some_and(|port| ports.contains(&port))
52}
53
54/// Port of a plain-HTTP loopback URL (`127.0.0.1`, `localhost`, `[::1]`),
55/// path allowed; `None` for anything else.
56fn loopback_port(url: &str) -> Option<u16> {
57    let url = url.trim();
58    let rest = ["http://127.0.0.1:", "http://localhost:", "http://[::1]:"]
59        .iter()
60        .find_map(|prefix| url.strip_prefix(prefix))?;
61    let port = rest.split('/').next()?;
62    port.parse().ok()
63}
64
65/// Proxy reachability timeout. Priority: env var > config.toml > 200ms default.
66pub fn proxy_timeout() -> std::time::Duration {
67    if let Ok(val) = std::env::var("LEAN_CTX_PROXY_TIMEOUT_MS")
68        && let Ok(ms) = val.parse::<u64>()
69    {
70        return std::time::Duration::from_millis(ms);
71    }
72    if let Some(ms) = crate::core::config::Config::load().proxy_timeout_ms {
73        return std::time::Duration::from_millis(ms);
74    }
75    std::time::Duration::from_millis(200)
76}
77
78pub(crate) fn is_proxy_reachable(port: u16) -> bool {
79    use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};
80    let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port);
81    TcpStream::connect_timeout(&addr, proxy_timeout()).is_ok()
82}
83
84/// True when the lean-ctx proxy itself answers `GET /health` on `port`. An
85/// open port alone proves nothing: a foreign process (or another user's
86/// proxy) listening there must never count as "proxy up".
87pub fn lean_ctx_proxy_responding(port: u16) -> bool {
88    use std::io::{Read, Write};
89    use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};
90
91    let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port);
92    let Ok(mut stream) = TcpStream::connect_timeout(&addr, proxy_timeout()) else {
93        return false;
94    };
95    let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(3)));
96    let req =
97        format!("GET /health HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
98    if stream.write_all(req.as_bytes()).is_err() {
99        return false;
100    }
101    let mut buf = Vec::with_capacity(1024);
102    let _ = stream.take(8 * 1024).read_to_end(&mut buf);
103    is_lean_ctx_health_response(&String::from_utf8_lossy(&buf))
104}
105
106/// The `/health` answer of a lean-ctx proxy: HTTP 200 carrying the
107/// `"service":"lean-ctx-proxy"` marker its handler always emits.
108fn is_lean_ctx_health_response(response: &str) -> bool {
109    let status_ok = response
110        .lines()
111        .next()
112        .is_some_and(|line| line.starts_with("HTTP/1.") && line.split(' ').nth(1) == Some("200"));
113    status_ok && response.contains("\"service\":\"lean-ctx-proxy\"")
114}
115
116/// Single source of truth for "is the proxy up" across `doctor`, `status` and
117/// `gain`: the proxy must be enabled in config AND the configured endpoint must
118/// answer as a lean-ctx proxy.
119pub fn configured_proxy_live() -> bool {
120    crate::core::config::Config::load().proxy_enabled == Some(true)
121        && lean_ctx_proxy_responding(default_port())
122}
123
124pub fn default_port() -> u16 {
125    if let Ok(val) = std::env::var("LEAN_CTX_PROXY_PORT")
126        && let Ok(port) = val.parse::<u16>()
127    {
128        return port;
129    }
130    let cfg = crate::core::config::Config::load();
131    if let Some(port) = cfg.proxy_port {
132        return port;
133    }
134    uid_based_port()
135}
136
137/// Derives a deterministic port from the user's UID to avoid collisions
138/// on multi-user systems. uid 1000 → 4444, uid 1001 → 4445, etc.
139/// System accounts (uid < 1000) and root always get the base port 4444.
140pub(crate) fn uid_based_port() -> u16 {
141    #[cfg(unix)]
142    {
143        // SAFETY: `getuid` takes no arguments, always succeeds, and only reads
144        // the calling process's real UID — no preconditions, no UB.
145        let uid = unsafe { libc::getuid() } as u16;
146        let offset = uid.saturating_sub(1000) % 1000;
147        DEFAULT_PROXY_PORT + offset
148    }
149    #[cfg(not(unix))]
150    {
151        DEFAULT_PROXY_PORT
152    }
153}