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. A Claude Pro/Max subscription authenticates via OAuth against
9/// `api.anthropic.com` directly and is rejected by any custom base URL, so we must not
10/// route it through the proxy.
11pub(crate) const ANTHROPIC_OMITTED_NOTE: &str = "ANTHROPIC_BASE_URL omitted: Claude Pro/Max subscription authenticates against api.anthropic.com directly (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
28pub fn is_local_lean_ctx_url(url: &str) -> bool {
29    url.starts_with("http://127.0.0.1:") || url.starts_with("http://localhost:")
30}
31
32/// Proxy reachability timeout. Priority: env var > config.toml > 200ms default.
33pub fn proxy_timeout() -> std::time::Duration {
34    if let Ok(val) = std::env::var("LEAN_CTX_PROXY_TIMEOUT_MS")
35        && let Ok(ms) = val.parse::<u64>()
36    {
37        return std::time::Duration::from_millis(ms);
38    }
39    if let Some(ms) = crate::core::config::Config::load().proxy_timeout_ms {
40        return std::time::Duration::from_millis(ms);
41    }
42    std::time::Duration::from_millis(200)
43}
44
45pub(crate) fn is_proxy_reachable(port: u16) -> bool {
46    use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};
47    let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port);
48    TcpStream::connect_timeout(&addr, proxy_timeout()).is_ok()
49}
50
51pub fn default_port() -> u16 {
52    if let Ok(val) = std::env::var("LEAN_CTX_PROXY_PORT")
53        && let Ok(port) = val.parse::<u16>()
54    {
55        return port;
56    }
57    let cfg = crate::core::config::Config::load();
58    if let Some(port) = cfg.proxy_port {
59        return port;
60    }
61    uid_based_port()
62}
63
64/// Derives a deterministic port from the user's UID to avoid collisions
65/// on multi-user systems. uid 1000 → 4444, uid 1001 → 4445, etc.
66/// System accounts (uid < 1000) and root always get the base port 4444.
67pub(crate) fn uid_based_port() -> u16 {
68    #[cfg(unix)]
69    {
70        // SAFETY: `getuid` takes no arguments, always succeeds, and only reads
71        // the calling process's real UID — no preconditions, no UB.
72        let uid = unsafe { libc::getuid() } as u16;
73        let offset = uid.saturating_sub(1000) % 1000;
74        DEFAULT_PROXY_PORT + offset
75    }
76    #[cfg(not(unix))]
77    {
78        DEFAULT_PROXY_PORT
79    }
80}