Skip to main content

lean_ctx/http_server/
config.rs

1use std::path::PathBuf;
2
3use anyhow::{Result, anyhow};
4use rmcp::transport::StreamableHttpServerConfig;
5
6const MAX_ID_LEN: usize = 64;
7
8pub(super) fn sanitize_id(raw: &str) -> String {
9    let trimmed = raw.trim();
10    if trimmed.is_empty() {
11        return "default".to_string();
12    }
13    let cleaned: String = trimmed
14        .chars()
15        .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_' || *c == '.')
16        .take(MAX_ID_LEN)
17        .collect();
18    if cleaned.is_empty() {
19        "default".to_string()
20    } else {
21        cleaned
22    }
23}
24
25#[derive(Clone, Debug)]
26pub struct HttpServerConfig {
27    pub host: String,
28    pub port: u16,
29    pub project_root: PathBuf,
30    pub auth_token: Option<String>,
31    pub stateful_mode: bool,
32    pub json_response: bool,
33    pub disable_host_check: bool,
34    pub allowed_hosts: Vec<String>,
35    pub max_body_bytes: usize,
36    pub max_concurrency: usize,
37    pub max_rps: u32,
38    pub rate_burst: u32,
39    pub request_timeout_ms: u64,
40}
41
42impl Default for HttpServerConfig {
43    fn default() -> Self {
44        let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
45        Self {
46            host: "127.0.0.1".to_string(),
47            port: 8080,
48            project_root,
49            auth_token: None,
50            stateful_mode: false,
51            json_response: true,
52            disable_host_check: false,
53            allowed_hosts: Vec::new(),
54            max_body_bytes: 2 * 1024 * 1024,
55            max_concurrency: 32,
56            max_rps: 50,
57            rate_burst: 100,
58            request_timeout_ms: 30_000,
59        }
60    }
61}
62
63impl HttpServerConfig {
64    pub fn validate(&self) -> Result<()> {
65        let host = self.host.trim().to_lowercase();
66        let is_loopback = host == "127.0.0.1" || host == "localhost" || host == "::1";
67        if !is_loopback && self.auth_token.as_deref().unwrap_or("").is_empty() {
68            return Err(anyhow!(
69                "Refusing to bind to host='{host}' without auth. Provide --auth-token (or bind to 127.0.0.1)."
70            ));
71        }
72        Ok(())
73    }
74
75    pub fn effective_auth_token(&self) -> Option<String> {
76        if let Some(ref token) = self.auth_token
77            && !token.is_empty()
78        {
79            return Some(token.clone());
80        }
81        let host = self.host.trim().to_lowercase();
82        let is_loopback = host == "127.0.0.1" || host == "localhost" || host == "::1";
83        if is_loopback {
84            let auto_token = crate::core::session_token::generate_token();
85            eprintln!(
86                "[lean-ctx] Auto-generated auth token for loopback: {auto_token}\n\
87                 Pass as Bearer token or set --auth-token explicitly."
88            );
89            Some(auto_token)
90        } else {
91            None
92        }
93    }
94
95    pub(super) fn mcp_http_config(&self) -> StreamableHttpServerConfig {
96        let mut cfg = StreamableHttpServerConfig::default()
97            .with_stateful_mode(self.stateful_mode)
98            .with_json_response(self.json_response);
99
100        if self.disable_host_check {
101            tracing::warn!(
102                "⚠ --disable-host-check is active: DNS rebinding protection is OFF. \
103                 Do NOT use this in production or on non-loopback interfaces."
104            );
105            cfg = cfg.disable_allowed_hosts();
106            return cfg;
107        }
108
109        if !self.allowed_hosts.is_empty() {
110            cfg = cfg.with_allowed_hosts(self.allowed_hosts.clone());
111            return cfg;
112        }
113
114        // Keep rmcp's secure loopback defaults; also allow the configured host (if it's loopback).
115        let host = self.host.trim();
116        if host == "127.0.0.1" || host == "localhost" || host == "::1" {
117            cfg.allowed_hosts.push(host.to_string());
118        }
119
120        cfg
121    }
122}