lean_ctx/proxy_setup/
util.rs1pub(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
7pub(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
13pub(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
16pub(crate) const COMMANDCODE_OMITTED_NOTE: &str =
18 "Command Code omitted (no ~/.commandcode auth — run `cmd login` or set COMMAND_CODE_API_KEY)";
19
20pub(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
28pub fn is_local_lean_ctx_url(url: &str) -> bool {
33 is_owned_proxy_url(url, &owned_proxy_ports())
34}
35
36pub(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
42fn owned_proxy_ports() -> [u16; 3] {
45 [default_port(), uid_based_port(), DEFAULT_PROXY_PORT]
46}
47
48pub(crate) fn is_owned_proxy_url(url: &str, ports: &[u16]) -> bool {
51 loopback_port(url).is_some_and(|port| ports.contains(&port))
52}
53
54fn 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
65pub 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
84pub 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
106fn 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
116pub 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
137pub(crate) fn uid_based_port() -> u16 {
141 #[cfg(unix)]
142 {
143 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}