Skip to main content

lean_ctx/dashboard/
mod.rs

1use std::sync::Arc;
2use subtle::ConstantTimeEq;
3use tokio::io::{AsyncReadExt, AsyncWriteExt};
4use tokio::net::TcpListener;
5
6const DEFAULT_PORT: u16 = 3333;
7const DEFAULT_HOST: &str = "127.0.0.1";
8const COCKPIT_INDEX_HTML: &str = include_str!("static/index.html");
9const COCKPIT_STYLE_CSS: &str = include_str!("static/style.css");
10const COCKPIT_LIB_API_JS: &str = include_str!("static/lib/api.js");
11const COCKPIT_LIB_FORMAT_JS: &str = include_str!("static/lib/format.js");
12const COCKPIT_LIB_ROUTER_JS: &str = include_str!("static/lib/router.js");
13const COCKPIT_LIB_CHARTS_JS: &str = include_str!("static/lib/charts.js");
14const COCKPIT_LIB_SHARED_JS: &str = include_str!("static/lib/shared.js");
15const COCKPIT_LIB_DOCTOR_JS: &str = include_str!("static/lib/doctor.js");
16const COCKPIT_COMPONENT_NAV_JS: &str = include_str!("static/components/cockpit-nav.js");
17const COCKPIT_COMPONENT_CONTEXT_JS: &str = include_str!("static/components/cockpit-context.js");
18const COCKPIT_COMPONENT_OVERVIEW_JS: &str = include_str!("static/components/cockpit-overview.js");
19const COCKPIT_COMPONENT_LIVE_JS: &str = include_str!("static/components/cockpit-live.js");
20const COCKPIT_COMPONENT_KNOWLEDGE_JS: &str = include_str!("static/components/cockpit-knowledge.js");
21const COCKPIT_COMPONENT_AGENTS_JS: &str = include_str!("static/components/cockpit-agents.js");
22const COCKPIT_COMPONENT_MEMORY_JS: &str = include_str!("static/components/cockpit-memory.js");
23const COCKPIT_COMPONENT_SEARCH_JS: &str = include_str!("static/components/cockpit-search.js");
24const COCKPIT_COMPONENT_COMPRESSION_JS: &str =
25    include_str!("static/components/cockpit-compression.js");
26const COCKPIT_COMPONENT_TOUR_JS: &str = include_str!("static/components/cockpit-tour.js");
27const COCKPIT_COMPONENT_GRAPH_JS: &str = include_str!("static/components/cockpit-graph.js");
28const COCKPIT_COMPONENT_ARCHITECTURE_JS: &str =
29    include_str!("static/components/cockpit-architecture.js");
30const COCKPIT_COMPONENT_EXPLORER_JS: &str = include_str!("static/components/cockpit-explorer.js");
31const COCKPIT_COMPONENT_HEALTH_JS: &str = include_str!("static/components/cockpit-health.js");
32const COCKPIT_COMPONENT_REMAINING_JS: &str = include_str!("static/components/cockpit-remaining.js");
33const COCKPIT_COMPONENT_COMMANDER_JS: &str = include_str!("static/components/cockpit-commander.js");
34const COCKPIT_COMPONENT_PALETTE_JS: &str = include_str!("static/components/cockpit-palette.js");
35const COCKPIT_COMPONENT_ROI_JS: &str = include_str!("static/components/cockpit-roi.js");
36const COCKPIT_COMPONENT_LEADERBOARD_JS: &str =
37    include_str!("static/components/cockpit-leaderboard.js");
38const COCKPIT_COMPONENT_AREA_TABS_JS: &str = include_str!("static/components/cockpit-area-tabs.js");
39const COCKPIT_COMPONENT_PROTECTION_JS: &str =
40    include_str!("static/components/cockpit-protection.js");
41const COCKPIT_COMPONENT_SETTINGS_JS: &str = include_str!("static/components/cockpit-settings.js");
42
43// Vendored third-party libraries — embedded so the dashboard works fully offline
44// (no external CDN). Served as text via the standard route pipeline.
45const COCKPIT_VENDOR_CHART_JS: &str = include_str!("static/vendor/chart.umd.min.js");
46const COCKPIT_VENDOR_D3_JS: &str = include_str!("static/vendor/d3.min.js");
47const COCKPIT_FONTS_CSS: &str = include_str!("static/fonts/fonts.css");
48const COCKPIT_FAVICON_SVG: &str = include_str!("static/favicon.svg");
49
50// Self-hosted variable fonts (binary woff2). Served via a dedicated binary
51// branch in `handle_request` so the bytes are never corrupted by the
52// String-based route pipeline.
53const FONT_INTER_WOFF2: &[u8] = include_bytes!("static/fonts/inter-variable.woff2");
54const FONT_JETBRAINS_WOFF2: &[u8] = include_bytes!("static/fonts/jetbrains-mono-variable.woff2");
55const FONT_SPACE_GROTESK_WOFF2: &[u8] = include_bytes!("static/fonts/space-grotesk-variable.woff2");
56
57/// Maps a request path to an embedded binary font asset.
58fn match_font_asset(path: &str) -> Option<&'static [u8]> {
59    match path {
60        "/static/fonts/inter-variable.woff2" => Some(FONT_INTER_WOFF2),
61        "/static/fonts/jetbrains-mono-variable.woff2" => Some(FONT_JETBRAINS_WOFF2),
62        "/static/fonts/space-grotesk-variable.woff2" => Some(FONT_SPACE_GROTESK_WOFF2),
63        _ => None,
64    }
65}
66
67pub mod base_path;
68pub mod routes;
69
70pub async fn start(
71    port: Option<u16>,
72    host: Option<String>,
73    base_path: Option<String>,
74    auth_token: Option<String>,
75    open_mode: Option<String>,
76) {
77    // How to reveal the URL once the server is up: --open= flag > env > browser.
78    let open = resolve_open_mode(open_mode.as_deref());
79    let port = port.unwrap_or_else(|| {
80        std::env::var("LEAN_CTX_PORT")
81            .ok()
82            .and_then(|p| p.parse().ok())
83            .unwrap_or(DEFAULT_PORT)
84    });
85
86    let host = host.unwrap_or_else(|| {
87        std::env::var("LEAN_CTX_HOST")
88            .ok()
89            .unwrap_or_else(|| DEFAULT_HOST.to_string())
90    });
91
92    // Reverse-proxy subpath (e.g. `/dashboard`). Normalized to "" or "/prefix".
93    // Shared across connections behind an Arc; "" means "no subpath" (#355).
94    let base_path = Arc::new(
95        base_path
96            .or_else(|| std::env::var("LEAN_CTX_DASHBOARD_BASE_PATH").ok())
97            .map(|b| base_path::normalize(&b))
98            .unwrap_or_default(),
99    );
100
101    let addr = format!("{host}:{port}");
102    let is_local = host == "127.0.0.1" || host == "localhost" || host == "::1";
103
104    // Resolve any *requested* fixed token (flag > LEAN_CTX_HTTP_TOKEN) up-front;
105    // `None` means "generate a random one". Done before the already-running check
106    // so we can warn when the requested token won't match a live instance (#377).
107    let (requested_token, token_src) = resolve_requested_token(auth_token.as_deref());
108
109    // Avoid accidental multiple dashboard instances (common source of "it hangs").
110    // Only safe to auto-detect for local dashboards without auth.
111    if is_local && dashboard_responding(&host, port) {
112        println!("\n  lean-ctx dashboard already running → http://{host}:{port}{base_path}");
113        if let Some(req) = requested_token.as_deref()
114            && load_saved_token().as_deref() != Some(req)
115        {
116            eprintln!(
117                "  \x1b[33m⚠\x1b[0m The running instance uses a different token — your {token_src} \
118                     will be rejected. Stop it (Ctrl+C) and restart to apply the new token."
119            );
120        }
121        println!("  Tip: use Ctrl+C in the existing terminal to stop it.\n");
122        if let Some(t) = load_saved_token() {
123            open_dashboard_url(
124                &format!("http://localhost:{port}{base_path}/?token={t}"),
125                open,
126            );
127        } else {
128            open_dashboard_url(&format!("http://localhost:{port}{base_path}/"), open);
129        }
130        return;
131    }
132
133    // Always enable auth (even on loopback) to prevent cross-origin reads of /api/*
134    // from a malicious website (CORS is not a reliable boundary for localhost services).
135    let t = requested_token.unwrap_or_else(generate_token);
136    let token = Some(Arc::new(t));
137
138    // Bind BEFORE persisting the token: two racing `lean-ctx dashboard` starts
139    // both used to write their fresh token, the bind loser exited — leaving a
140    // token on disk that the surviving server never accepted. Every later
141    // "already running" browser open (and any tool reading dashboard.token)
142    // then got 401s. Binding first makes the loser exit without touching the
143    // file, so dashboard.token always belongs to the live listener.
144    let listener = match TcpListener::bind(&addr).await {
145        Ok(l) => l,
146        Err(e) => {
147            eprintln!("Failed to bind to {addr}: {e}");
148            std::process::exit(1);
149        }
150    };
151
152    if let Some(t) = token.as_ref() {
153        save_token(t);
154        let masked = if t.len() > 12 {
155            format!(
156                "{}…{}",
157                &t[..t.floor_char_boundary(8)],
158                &t[t.ceil_char_boundary(t.len().saturating_sub(4))..]
159            )
160        } else {
161            t.to_string()
162        };
163        let src = if token_src.is_empty() {
164            String::new()
165        } else {
166            format!(" (from {token_src})")
167        };
168        if is_local {
169            println!("  Auth: enabled (local){src}");
170            println!("  Browser URL:  http://localhost:{port}{base_path}/?token={t}");
171        } else {
172            eprintln!(
173                "  \x1b[33m⚠\x1b[0m Binding to {host} — authentication enabled.\n  \
174                 Bearer token{src}: \x1b[1;32m{masked}\x1b[0m\n  \
175                 Browser URL:  http://<your-ip>:{port}{base_path}/?token={t}"
176            );
177        }
178    }
179
180    let stats_path = crate::core::data_dir::lean_ctx_data_dir().map_or_else(
181        |_| "~/.lean-ctx/stats.json".to_string(),
182        |d| d.join("stats.json").display().to_string(),
183    );
184
185    if host == "0.0.0.0" {
186        println!("\n  lean-ctx dashboard → http://0.0.0.0:{port} (all interfaces)");
187        println!("  Local access:  http://localhost:{port}");
188    } else {
189        println!("\n  lean-ctx dashboard → http://{host}:{port}");
190    }
191    println!("  Stats file: {stats_path}");
192    println!("  Press Ctrl+C to stop");
193    println!(
194        "  \x1b[2m💡 Join the public leaderboard at https://leanctx.com/metrics: lean-ctx gain --publish --leaderboard\x1b[0m\n"
195    );
196
197    if is_local {
198        if let Some(t) = token.as_ref() {
199            open_dashboard_url(
200                &format!("http://localhost:{port}{base_path}/?token={t}"),
201                open,
202            );
203        } else {
204            open_dashboard_url(&format!("http://localhost:{port}{base_path}/"), open);
205        }
206    }
207    if crate::shell::is_container() && is_local {
208        println!("  Tip (Docker): bind 0.0.0.0 + publish port:");
209        println!("    lean-ctx dashboard --host=0.0.0.0 --port={port}");
210        println!("    docker run ... -p {port}:{port} ...");
211        println!();
212    }
213
214    if crate::core::datadog_push::spawn_if_enabled() {
215        println!(
216            "  Datadog push: enabled (agentless, every LEAN_CTX_DATADOG_INTERVAL_SECS or 60s)"
217        );
218    }
219
220    loop {
221        if let Ok((stream, _)) = listener.accept().await {
222            let token_ref = token.clone();
223            let base_ref = base_path.clone();
224            tokio::spawn(handle_request(stream, token_ref, base_ref));
225        }
226    }
227}
228
229/// Name of the env var that pins the dashboard Bearer token (#377).
230const HTTP_TOKEN_ENV: &str = "LEAN_CTX_HTTP_TOKEN";
231/// Read-only token accepted **only** for `GET /metrics` (GL #401) so
232/// monitoring agents never hold the full dashboard credential.
233const SCRAPE_TOKEN_ENV: &str = "LEAN_CTX_SCRAPE_TOKEN";
234
235/// Resolve the dashboard Bearer token.
236///
237/// Honors `LEAN_CTX_HTTP_TOKEN` (#377): when set to a non-empty value it is used
238/// verbatim so reverse-proxy / container deployments keep a stable token across
239/// restarts and redeploys (nginx can inject a fixed `Authorization: Bearer …`).
240/// When unset or empty, a fresh random token is generated (no behavior change).
241///
242/// Resolve a *requested* fixed token with precedence `--auth-token` flag >
243/// `LEAN_CTX_HTTP_TOKEN` (#377). The flag wins so it survives container/service
244/// environments that strip or fail to inherit the env var. Returns the trimmed,
245/// non-empty token and a human label of its source; `None` means "no fixed token
246/// requested → caller generates a random one".
247fn resolve_requested_token(flag: Option<&str>) -> (Option<String>, &'static str) {
248    if let Some(t) = flag.map(str::trim).filter(|s| !s.is_empty()) {
249        return (Some(t.to_string()), "--auth-token");
250    }
251    if let Ok(raw) = std::env::var(HTTP_TOKEN_ENV) {
252        let trimmed = raw.trim();
253        if !trimmed.is_empty() {
254            return (Some(trimmed.to_string()), HTTP_TOKEN_ENV);
255        }
256    }
257    (None, "")
258}
259
260fn generate_token() -> String {
261    let mut bytes = [0u8; 32];
262    if getrandom::fill(&mut bytes).is_err() {
263        tracing::warn!("CSPRNG unavailable — falling back to time-based token");
264        let ts = std::time::SystemTime::now()
265            .duration_since(std::time::UNIX_EPOCH)
266            .unwrap_or_default()
267            .as_nanos();
268        for (i, b) in bytes.iter_mut().enumerate() {
269            *b = ((ts >> (i % 16 * 8)) & 0xFF) as u8;
270        }
271    }
272    format!("lctx_{}", hex_lower(&bytes))
273}
274
275fn save_token(token: &str) {
276    if let Ok(dir) = crate::core::paths::state_dir() {
277        let _ = std::fs::create_dir_all(&dir);
278        let path = dir.join("dashboard.token");
279        #[cfg(unix)]
280        {
281            use std::io::Write;
282            use std::os::unix::fs::OpenOptionsExt;
283            let Ok(mut f) = std::fs::OpenOptions::new()
284                .write(true)
285                .create(true)
286                .truncate(true)
287                .mode(0o600)
288                .open(&path)
289            else {
290                return;
291            };
292            let _ = f.write_all(token.as_bytes());
293        }
294        #[cfg(not(unix))]
295        {
296            let _ = std::fs::write(&path, token);
297        }
298    }
299}
300
301fn load_saved_token() -> Option<String> {
302    let dir = crate::core::paths::state_dir().ok()?;
303    let path = dir.join("dashboard.token");
304    std::fs::read_to_string(path)
305        .ok()
306        .map(|s| s.trim().to_string())
307}
308
309/// Adds `nonce="..."` to all inline `<script>` tags (those without a `src=` attribute).
310/// External scripts (`<script src="...">`) are left untouched.
311pub fn add_nonce_to_inline_scripts(html: &str, nonce: &str) -> String {
312    let mut result = String::with_capacity(html.len() + 128);
313    let mut remaining = html;
314    while let Some(pos) = remaining.find("<script") {
315        result.push_str(&remaining[..pos]);
316        let tag_start = &remaining[pos..];
317        let tag_end = tag_start.find('>').unwrap_or(tag_start.len());
318        let tag = &tag_start[..=tag_end];
319        if tag.contains("src=") || tag.contains("nonce=") {
320            result.push_str(tag);
321        } else {
322            result.push_str(&tag.replacen("<script", &format!("<script nonce=\"{nonce}\""), 1));
323        }
324        remaining = &tag_start[tag_end + 1..];
325    }
326    result.push_str(remaining);
327    result
328}
329
330fn hex_lower(bytes: &[u8]) -> String {
331    const HEX: &[u8; 16] = b"0123456789abcdef";
332    let mut out = String::with_capacity(bytes.len() * 2);
333    for &b in bytes {
334        out.push(HEX[(b >> 4) as usize] as char);
335        out.push(HEX[(b & 0x0f) as usize] as char);
336    }
337    out
338}
339
340/// How `lean-ctx dashboard` reveals the URL after the server is up (#424).
341#[derive(Clone, Copy, PartialEq, Eq, Debug)]
342enum DashboardOpen {
343    /// Launch the system default browser (historical default).
344    Browser,
345    /// Don't auto-launch anything — just print the URL. For users who run the
346    /// dashboard inside an editor / reverse proxy and don't want a new window.
347    None,
348    /// Suppress the external browser and print the steps to open the URL in
349    /// VS Code's built-in browser. VS Code exposes no stable CLI flag to open
350    /// its Simple/Integrated Browser, so we guide rather than fake it.
351    Vscode,
352}
353
354/// Resolve the open mode from (in precedence order) the `--open=` flag, the
355/// `LEAN_CTX_DASHBOARD_OPEN` env var, else the `browser` default.
356fn resolve_open_mode(flag: Option<&str>) -> DashboardOpen {
357    let raw = flag
358        .map(str::to_string)
359        .or_else(|| std::env::var("LEAN_CTX_DASHBOARD_OPEN").ok())
360        .unwrap_or_default();
361    match raw.trim().to_ascii_lowercase().as_str() {
362        "none" | "off" | "false" | "no" => DashboardOpen::None,
363        "vscode" | "code" | "editor" => DashboardOpen::Vscode,
364        _ => DashboardOpen::Browser,
365    }
366}
367
368/// Reveal `url` to the user according to `mode`.
369fn open_dashboard_url(url: &str, mode: DashboardOpen) {
370    match mode {
371        DashboardOpen::Browser => open_browser(url),
372        DashboardOpen::None => {}
373        DashboardOpen::Vscode => {
374            // Prefer the extension's native webview tab (#466 item 3): with the
375            // lean-ctx VS Code extension installed, one command opens the
376            // dashboard as a real editor tab — no URL copy/paste. Keep the
377            // Simple Browser path as the no-extension fallback.
378            println!(
379                "  \x1b[2mNative tab: run ⇧⌘P → \"lean-ctx: Open Web Dashboard\" (needs the lean-ctx VS Code extension)\x1b[0m"
380            );
381            println!(
382                "  \x1b[2mNo extension? ⇧⌘P → \"Simple Browser: Show\" → paste the URL above\x1b[0m"
383            );
384        }
385    }
386}
387
388fn open_browser(url: &str) {
389    #[cfg(target_os = "macos")]
390    {
391        let _ = std::process::Command::new("open").arg(url).spawn();
392    }
393
394    #[cfg(target_os = "linux")]
395    {
396        let _ = std::process::Command::new("xdg-open")
397            .arg(url)
398            .stderr(std::process::Stdio::null())
399            .spawn();
400    }
401
402    #[cfg(target_os = "windows")]
403    {
404        let _ = std::process::Command::new("cmd")
405            .args(["/C", "start", url])
406            .spawn();
407    }
408}
409
410fn dashboard_responding(host: &str, port: u16) -> bool {
411    use std::io::{Read, Write};
412    use std::net::TcpStream;
413    use std::time::Duration;
414
415    let addr = format!("{host}:{port}");
416    let Ok(mut s) = TcpStream::connect_timeout(
417        &addr
418            .parse()
419            .unwrap_or_else(|_| std::net::SocketAddr::from(([127, 0, 0, 1], port))),
420        Duration::from_millis(150),
421    ) else {
422        return false;
423    };
424    let _ = s.set_read_timeout(Some(Duration::from_millis(150)));
425    let _ = s.set_write_timeout(Some(Duration::from_millis(150)));
426
427    let auth_header = load_saved_token()
428        .map(|t| format!("Authorization: Bearer {t}\r\n"))
429        .unwrap_or_default();
430
431    let req = format!(
432        "GET /api/version HTTP/1.1\r\nHost: localhost\r\n{auth_header}Connection: close\r\n\r\n"
433    );
434    if s.write_all(req.as_bytes()).is_err() {
435        return false;
436    }
437    let mut buf = [0u8; 256];
438    let Ok(n) = s.read(&mut buf) else {
439        return false;
440    };
441    let head = String::from_utf8_lossy(&buf[..n]);
442    head.starts_with("HTTP/1.1 200") || head.starts_with("HTTP/1.0 200")
443}
444
445const MAX_HTTP_MESSAGE: usize = 2 * 1024 * 1024;
446
447fn header_line_value<'a>(header_section: &'a str, name: &str) -> Option<&'a str> {
448    for line in header_section.lines() {
449        let Some((k, v)) = line.split_once(':') else {
450            continue;
451        };
452        if k.trim().eq_ignore_ascii_case(name) {
453            return Some(v.trim());
454        }
455    }
456    None
457}
458
459/// Loopback dashboards often use `localhost` vs `127.0.0.1` interchangeably in `Origin`.
460fn host_loopback_aliases(host: &str) -> Vec<String> {
461    let mut v = vec![host.to_string()];
462    if let Some(port) = host.strip_prefix("127.0.0.1:") {
463        v.push(format!("localhost:{port}"));
464    }
465    if let Some(port) = host.strip_prefix("localhost:") {
466        v.push(format!("127.0.0.1:{port}"));
467    }
468    if let Some(port) = host.strip_prefix("[::1]:") {
469        v.push(format!("127.0.0.1:{port}"));
470        v.push(format!("localhost:{port}"));
471    }
472    v
473}
474
475fn origin_matches_dashboard_host(origin: &str, host: &str) -> bool {
476    let origin = origin.trim_end_matches('/');
477    for h in host_loopback_aliases(host) {
478        if origin.eq_ignore_ascii_case(&format!("http://{h}"))
479            || origin.eq_ignore_ascii_case(&format!("https://{h}"))
480        {
481            return true;
482        }
483    }
484    false
485}
486
487/// Defense-in-depth for browser POSTs: reject cross-site `Origin` on mutating `/api/*` calls.
488/// Non-browser clients (no `Origin`) remain allowed when Bearer auth succeeds.
489fn csrf_origin_ok(header_section: &str, method: &str, path: &str) -> bool {
490    let uc = method.to_ascii_uppercase();
491    if !matches!(uc.as_str(), "POST" | "PUT" | "PATCH" | "DELETE") {
492        return true;
493    }
494    if !path.starts_with("/api/") {
495        return true;
496    }
497    let Some(origin) = header_line_value(header_section, "Origin") else {
498        return true;
499    };
500    if origin.is_empty() || origin.eq_ignore_ascii_case("null") {
501        return true;
502    }
503    let Some(host) = header_line_value(header_section, "Host") else {
504        return false;
505    };
506    origin_matches_dashboard_host(origin, host)
507}
508
509fn find_headers_end(buf: &[u8]) -> Option<usize> {
510    buf.windows(4).position(|w| w == b"\r\n\r\n")
511}
512
513fn parse_content_length_header(header_section: &[u8]) -> Option<usize> {
514    let text = String::from_utf8_lossy(header_section);
515    for line in text.lines() {
516        let Some((k, v)) = line.split_once(':') else {
517            continue;
518        };
519        if k.trim().eq_ignore_ascii_case("content-length") {
520            return v.trim().parse::<usize>().ok();
521        }
522    }
523    Some(0)
524}
525
526async fn read_http_message(stream: &mut tokio::net::TcpStream) -> Option<Vec<u8>> {
527    let mut buf = Vec::new();
528    let mut tmp = [0u8; 8192];
529    loop {
530        if let Some(end) = find_headers_end(&buf) {
531            let cl = parse_content_length_header(&buf[..end])?;
532            let total = end + 4 + cl;
533            if total > MAX_HTTP_MESSAGE {
534                return None;
535            }
536            if buf.len() >= total {
537                buf.truncate(total);
538                return Some(buf);
539            }
540        } else if buf.len() > 65_536 {
541            return None;
542        }
543
544        let n = stream.read(&mut tmp).await.ok()?;
545        if n == 0 {
546            return None;
547        }
548        buf.extend_from_slice(&tmp[..n]);
549        if buf.len() > MAX_HTTP_MESSAGE {
550            return None;
551        }
552    }
553}
554
555async fn handle_request(
556    mut stream: tokio::net::TcpStream,
557    token: Option<Arc<String>>,
558    base_path: Arc<String>,
559) {
560    let is_loopback = stream.peer_addr().is_ok_and(|a| a.ip().is_loopback());
561
562    let Some(buf) = read_http_message(&mut stream).await else {
563        return;
564    };
565    let Some(header_end) = find_headers_end(&buf) else {
566        return;
567    };
568    let header_text = String::from_utf8_lossy(&buf[..header_end]).to_string();
569    let body_start = header_end + 4;
570    let Some(content_len) = parse_content_length_header(&buf[..header_end]) else {
571        return;
572    };
573    if buf.len() < body_start + content_len {
574        return;
575    }
576    let body_str = std::str::from_utf8(&buf[body_start..body_start + content_len])
577        .unwrap_or("")
578        .to_string();
579
580    let first = header_text.lines().next().unwrap_or("");
581    let mut parts = first.split_whitespace();
582    let method = parts.next().unwrap_or("GET").to_string();
583    let raw_path = parts.next().unwrap_or("/").to_string();
584
585    let (path, query_token) = if let Some(idx) = raw_path.find('?') {
586        let p = &raw_path[..idx];
587        let qs = &raw_path[idx + 1..];
588        let tok = qs
589            .split('&')
590            .find_map(|pair| pair.strip_prefix("token="))
591            .map(std::string::ToString::to_string);
592        (p.to_string(), tok)
593    } else {
594        (raw_path.clone(), None)
595    };
596
597    let query_str = raw_path
598        .find('?')
599        .map_or(String::new(), |i| raw_path[i + 1..].to_string());
600
601    // Strip the reverse-proxy subpath prefix (if any) so all downstream matching
602    // (fonts, auth, routing) works on root-relative paths whether or not the
603    // proxy already stripped it (#355).
604    let path = base_path::strip(&path, base_path.as_str()).to_string();
605
606    // Binary font assets are public (like CSS/JS) and bypass the String-based
607    // route pipeline so their bytes stay intact.
608    if let Some(bytes) = match_font_asset(&path) {
609        let header = format!(
610            "HTTP/1.1 200 OK\r\n\
611             Content-Type: font/woff2\r\n\
612             Content-Length: {}\r\n\
613             Cache-Control: public, max-age=31536000, immutable\r\n\
614             X-Content-Type-Options: nosniff\r\n\
615             Connection: close\r\n\
616             \r\n",
617            bytes.len()
618        );
619        let _ = stream.write_all(header.as_bytes()).await;
620        let _ = stream.write_all(bytes).await;
621        return;
622    }
623
624    let is_api = path.starts_with("/api/");
625    let requires_auth = is_api || path == "/metrics";
626
627    if let Some(ref expected) = token {
628        let mut has_header_auth = check_auth(&header_text, expected);
629
630        // Read-only scrape token (GL #401): lets a Prometheus/Datadog agent
631        // scrape `/metrics` without holding the full dashboard token. Valid
632        // for the metrics endpoint only — every other API stays gated on the
633        // dashboard token.
634        if !has_header_auth
635            && path == "/metrics"
636            && let Ok(scrape) = std::env::var(SCRAPE_TOKEN_ENV)
637        {
638            let scrape = scrape.trim();
639            if !scrape.is_empty() && check_auth(&header_text, scrape) {
640                has_header_auth = true;
641            }
642        }
643
644        if requires_auth && !has_header_auth {
645            let body = r#"{"error":"unauthorized"}"#;
646            let response = format!(
647                "HTTP/1.1 401 Unauthorized\r\n\
648                 Content-Type: application/json\r\n\
649                 Content-Length: {}\r\n\
650                 WWW-Authenticate: Bearer\r\n\
651                 Connection: close\r\n\
652                 \r\n\
653                 {body}",
654                body.len()
655            );
656            let _ = stream.write_all(response.as_bytes()).await;
657            return;
658        }
659
660        if !csrf_origin_ok(&header_text, method.as_str(), path.as_str()) {
661            let body = r#"{"error":"forbidden"}"#;
662            let response = format!(
663                "HTTP/1.1 403 Forbidden\r\n\
664                 Content-Type: application/json\r\n\
665                 Content-Length: {}\r\n\
666                 Connection: close\r\n\
667                 \r\n\
668                 {body}",
669                body.len()
670            );
671            let _ = stream.write_all(response.as_bytes()).await;
672            return;
673        }
674    }
675
676    // Route handlers are synchronous and a few (graph/index builds) do seconds
677    // of disk work. Running them inline on an async worker thread lets one slow
678    // endpoint starve the small worker pool, so a trivial GET like
679    // `/api/settings` can wait minutes behind it (#431, Windows few-core). Run
680    // them on the blocking pool instead: the async workers stay free to serve
681    // light endpoints promptly. `spawn_blocking` also captures panics (returns
682    // a `JoinError`), so the previous `catch_unwind` is no longer needed.
683    let route_started = std::time::Instant::now();
684    let route_label = path.clone();
685    let compute = tokio::task::spawn_blocking(move || {
686        routes::route_response(
687            &path,
688            &query_str,
689            query_token.as_ref(),
690            token.as_ref(),
691            is_loopback,
692            &method,
693            &body_str,
694        )
695    })
696    .await;
697    let (status, content_type, mut body) = match compute {
698        Ok(v) => v,
699        // The blocking task panicked or was cancelled — surface a 500 rather
700        // than dropping the connection.
701        Err(_) => (
702            "500 Internal Server Error",
703            "application/json",
704            r#"{"error":"dashboard route panicked"}"#.to_string(),
705        ),
706    };
707    // Observability: a slow light endpoint is exactly the #431 symptom, so make
708    // any handler that crosses 1s visible in the logs for future diagnosis.
709    let route_elapsed = route_started.elapsed();
710    if route_elapsed >= std::time::Duration::from_secs(1) {
711        tracing::warn!(
712            target: "lean_ctx::dashboard",
713            "slow dashboard route {route_label} took {} ms",
714            route_elapsed.as_millis()
715        );
716    }
717
718    // Under a reverse-proxy subpath, rewrite root-absolute asset/API URLs in the
719    // served HTML/CSS/JS so the browser requests them under the prefix (#355).
720    if !base_path.is_empty()
721        && (content_type.contains("text/html")
722            || content_type.contains("text/css")
723            || content_type.contains("javascript"))
724    {
725        body = base_path::rewrite_asset_urls(&body, base_path.as_str());
726    }
727
728    let cache_header = if content_type.starts_with("application/json") {
729        "Cache-Control: no-cache, no-store, must-revalidate\r\nPragma: no-cache\r\n"
730    } else if content_type.starts_with("application/javascript")
731        || content_type.starts_with("text/css")
732    {
733        "Cache-Control: no-cache, must-revalidate\r\n"
734    } else {
735        ""
736    };
737
738    let nonce = {
739        let mut nb = [0u8; 16];
740        if getrandom::fill(&mut nb).is_err() {
741            nb.iter_mut().enumerate().for_each(|(i, b)| {
742                *b = (std::time::SystemTime::now()
743                    .duration_since(std::time::UNIX_EPOCH)
744                    .unwrap_or_default()
745                    .subsec_nanos()
746                    .wrapping_add(i as u32)) as u8;
747            });
748        }
749        hex_lower(&nb)
750    };
751    if content_type.contains("text/html") {
752        body = add_nonce_to_inline_scripts(&body, &nonce);
753    }
754    let security_headers = format!(
755        "X-Content-Type-Options: nosniff\r\n\
756         X-Frame-Options: DENY\r\n\
757         Referrer-Policy: no-referrer\r\n\
758         Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{nonce}'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; connect-src 'self'\r\n"
759    );
760
761    let response = format!(
762        "HTTP/1.1 {status}\r\n\
763         Content-Type: {content_type}\r\n\
764         Content-Length: {}\r\n\
765         {cache_header}\
766         {security_headers}\
767         Connection: close\r\n\
768         \r\n\
769         {body}",
770        body.len()
771    );
772
773    let _ = stream.write_all(response.as_bytes()).await;
774}
775
776fn check_auth(request: &str, expected_token: &str) -> bool {
777    for line in request.lines() {
778        let lower = line.to_lowercase();
779        if lower.starts_with("authorization:") {
780            let value = line["authorization:".len()..].trim();
781            if let Some(token) = value
782                .strip_prefix("Bearer ")
783                .or_else(|| value.strip_prefix("bearer "))
784            {
785                return constant_time_eq(token.trim().as_bytes(), expected_token.as_bytes());
786            }
787        }
788    }
789    false
790}
791
792fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
793    if a.len() != b.len() {
794        return false;
795    }
796    bool::from(a.ct_eq(b))
797}
798
799#[cfg(test)]
800mod tests {
801    use super::routes::helpers::normalize_dashboard_demo_path;
802    use super::*;
803    use tempfile::tempdir;
804
805    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
806
807    #[test]
808    fn check_auth_with_valid_bearer() {
809        let req = "GET /api/stats HTTP/1.1\r\nAuthorization: Bearer lctx_abc123\r\n\r\n";
810        assert!(check_auth(req, "lctx_abc123"));
811    }
812
813    #[test]
814    fn check_auth_with_invalid_bearer() {
815        let req = "GET /api/stats HTTP/1.1\r\nAuthorization: Bearer wrong_token\r\n\r\n";
816        assert!(!check_auth(req, "lctx_abc123"));
817    }
818
819    #[test]
820    fn open_mode_flag_parses_all_variants() {
821        // Explicit flag wins and never consults the environment (#424).
822        assert_eq!(resolve_open_mode(Some("none")), DashboardOpen::None);
823        assert_eq!(resolve_open_mode(Some("off")), DashboardOpen::None);
824        assert_eq!(resolve_open_mode(Some("no")), DashboardOpen::None);
825        assert_eq!(resolve_open_mode(Some("vscode")), DashboardOpen::Vscode);
826        assert_eq!(resolve_open_mode(Some("code")), DashboardOpen::Vscode);
827        assert_eq!(resolve_open_mode(Some("editor")), DashboardOpen::Vscode);
828        assert_eq!(resolve_open_mode(Some("VSCode")), DashboardOpen::Vscode);
829        assert_eq!(resolve_open_mode(Some("browser")), DashboardOpen::Browser);
830        // Unknown values fall back to the historical default rather than erroring.
831        assert_eq!(resolve_open_mode(Some("wat")), DashboardOpen::Browser);
832    }
833
834    #[test]
835    fn open_mode_env_is_used_when_no_flag() {
836        let _guard = ENV_LOCK.lock().unwrap();
837        crate::test_env::set_var("LEAN_CTX_DASHBOARD_OPEN", "none");
838        assert_eq!(resolve_open_mode(None), DashboardOpen::None);
839        crate::test_env::set_var("LEAN_CTX_DASHBOARD_OPEN", "vscode");
840        assert_eq!(resolve_open_mode(None), DashboardOpen::Vscode);
841        // Flag still overrides the env var.
842        assert_eq!(resolve_open_mode(Some("browser")), DashboardOpen::Browser);
843        crate::test_env::remove_var("LEAN_CTX_DASHBOARD_OPEN");
844        assert_eq!(resolve_open_mode(None), DashboardOpen::Browser);
845    }
846
847    #[test]
848    fn check_auth_missing_header() {
849        let req = "GET /api/stats HTTP/1.1\r\nHost: localhost\r\n\r\n";
850        assert!(!check_auth(req, "lctx_abc123"));
851    }
852
853    #[test]
854    fn check_auth_lowercase_bearer() {
855        let req = "GET /api/stats HTTP/1.1\r\nauthorization: bearer lctx_abc123\r\n\r\n";
856        assert!(check_auth(req, "lctx_abc123"));
857    }
858
859    #[test]
860    fn query_token_parsing() {
861        let raw_path = "/index.html?token=lctx_abc123&other=val";
862        let idx = raw_path.find('?').unwrap();
863        let qs = &raw_path[idx + 1..];
864        let tok = qs.split('&').find_map(|pair| pair.strip_prefix("token="));
865        assert_eq!(tok, Some("lctx_abc123"));
866    }
867
868    #[test]
869    fn api_path_detection() {
870        assert!("/api/stats".starts_with("/api/"));
871        assert!("/api/version".starts_with("/api/"));
872        assert!(!"/".starts_with("/api/"));
873        assert!(!"/index.html".starts_with("/api/"));
874        assert!(!"/favicon.ico".starts_with("/api/"));
875    }
876
877    #[test]
878    fn normalize_dashboard_demo_path_strips_rooted_relative_windows_path() {
879        let normalized = normalize_dashboard_demo_path(r"\backend\list_tables.js");
880        assert_eq!(
881            normalized,
882            format!("backend{}list_tables.js", std::path::MAIN_SEPARATOR)
883        );
884    }
885
886    #[test]
887    fn normalize_dashboard_demo_path_preserves_absolute_windows_path() {
888        let input = r"C:\repo\backend\list_tables.js";
889        assert_eq!(normalize_dashboard_demo_path(input), input);
890    }
891
892    #[test]
893    fn normalize_dashboard_demo_path_preserves_unc_path() {
894        let input = r"\\server\share\backend\list_tables.js";
895        assert_eq!(normalize_dashboard_demo_path(input), input);
896    }
897
898    #[test]
899    fn normalize_dashboard_demo_path_strips_dot_slash_prefix() {
900        assert_eq!(
901            normalize_dashboard_demo_path("./src/main.rs"),
902            "src/main.rs"
903        );
904        assert_eq!(
905            normalize_dashboard_demo_path(r".\src\main.rs"),
906            format!("src{}main.rs", std::path::MAIN_SEPARATOR)
907        );
908    }
909
910    #[test]
911    fn api_profile_returns_json() {
912        let (_status, _ct, body) =
913            routes::route_response("/api/profile", "", None, None, false, "GET", "");
914        let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
915        assert!(v.get("active_name").is_some(), "missing active_name");
916        assert!(
917            v.pointer("/profile/profile/name")
918                .and_then(|n| n.as_str())
919                .is_some(),
920            "missing profile.profile.name"
921        );
922        assert!(v.get("available").and_then(|a| a.as_array()).is_some());
923    }
924
925    #[test]
926    fn api_billing_badge_returns_cosmetic_shape() {
927        let (status, ct, body) =
928            routes::route_response("/api/billing-badge", "", None, None, false, "GET", "");
929        assert_eq!(status, "200 OK");
930        assert_eq!(ct, "application/json");
931        let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
932        assert!(v.get("plan").and_then(|p| p.as_str()).is_some());
933        assert!(
934            v.get("supporter")
935                .and_then(serde_json::Value::as_bool)
936                .is_some()
937        );
938        assert!(
939            matches!(
940                v.get("source").and_then(|s| s.as_str()),
941                Some("live" | "cached" | "expired" | "none")
942            ),
943            "unexpected source: {body}"
944        );
945    }
946
947    #[test]
948    fn api_episodes_returns_json() {
949        let (_status, _ct, body) =
950            routes::route_response("/api/episodes", "", None, None, false, "GET", "");
951        let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
952        assert!(v.get("project_hash").is_some());
953        assert!(v.get("stats").is_some());
954        assert!(v.get("recent").and_then(|a| a.as_array()).is_some());
955    }
956
957    #[test]
958    fn api_procedures_returns_json() {
959        let (_status, _ct, body) =
960            routes::route_response("/api/procedures", "", None, None, false, "GET", "");
961        let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
962        assert!(v.get("project_hash").is_some());
963        assert!(v.get("procedures").and_then(|a| a.as_array()).is_some());
964        assert!(v.get("suggestions").and_then(|a| a.as_array()).is_some());
965    }
966
967    #[test]
968    fn api_compression_demo_heals_moved_file_paths() {
969        let _g = ENV_LOCK.lock().expect("env lock");
970        let td = tempdir().expect("tempdir");
971        let root = td.path();
972        std::fs::create_dir_all(root.join("src").join("moved")).expect("mkdir");
973        std::fs::write(
974            root.join("src").join("moved").join("foo.rs"),
975            "pub fn foo() { println!(\"hi\"); }\n",
976        )
977        .expect("write foo.rs");
978
979        let root_s = root.to_string_lossy().to_string();
980        crate::test_env::set_var("LEAN_CTX_DASHBOARD_PROJECT", &root_s);
981
982        let (_status, _ct, body) = routes::route_response(
983            "/api/compression-demo",
984            "path=src/foo.rs",
985            None,
986            None,
987            false,
988            "GET",
989            "",
990        );
991        let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
992        assert!(v.get("error").is_none(), "unexpected error: {body}");
993        assert_eq!(
994            v.get("resolved_from").and_then(|x| x.as_str()),
995            Some("src/moved/foo.rs")
996        );
997
998        crate::test_env::remove_var("LEAN_CTX_DASHBOARD_PROJECT");
999        if let Some(dir) = crate::core::graph_index::ProjectIndex::index_dir(&root_s) {
1000            let _ = std::fs::remove_dir_all(dir);
1001        }
1002    }
1003
1004    #[test]
1005    fn resolve_token_uses_env_var_verbatim() {
1006        let _g = ENV_LOCK.lock().expect("env lock");
1007        crate::test_env::set_var(HTTP_TOKEN_ENV, "lctx_mystatic");
1008        let (token, src) = resolve_requested_token(None);
1009        crate::test_env::remove_var(HTTP_TOKEN_ENV);
1010        assert_eq!(
1011            src, HTTP_TOKEN_ENV,
1012            "token should be reported as env-sourced"
1013        );
1014        assert_eq!(token.as_deref(), Some("lctx_mystatic"));
1015    }
1016
1017    #[test]
1018    fn resolve_token_trims_env_var() {
1019        let _g = ENV_LOCK.lock().expect("env lock");
1020        crate::test_env::set_var(HTTP_TOKEN_ENV, "  lctx_padded  ");
1021        let (token, src) = resolve_requested_token(None);
1022        crate::test_env::remove_var(HTTP_TOKEN_ENV);
1023        assert_eq!(src, HTTP_TOKEN_ENV);
1024        assert_eq!(token.as_deref(), Some("lctx_padded"));
1025    }
1026
1027    #[test]
1028    fn resolve_token_falls_back_to_random_when_unset() {
1029        let _g = ENV_LOCK.lock().expect("env lock");
1030        crate::test_env::remove_var(HTTP_TOKEN_ENV);
1031        let (token, src) = resolve_requested_token(None);
1032        assert!(token.is_none(), "unset env requests no fixed token");
1033        assert!(src.is_empty());
1034        // The production fallback in `start()` generates a random token.
1035        let generated = token.unwrap_or_else(generate_token);
1036        assert!(
1037            generated.starts_with("lctx_"),
1038            "generated token prefix, got {generated}"
1039        );
1040        assert!(
1041            generated.len() > 12,
1042            "generated token should be 32-byte hex"
1043        );
1044    }
1045
1046    #[test]
1047    fn resolve_token_ignores_empty_env() {
1048        let _g = ENV_LOCK.lock().expect("env lock");
1049        crate::test_env::set_var(HTTP_TOKEN_ENV, "   ");
1050        let (token, src) = resolve_requested_token(None);
1051        crate::test_env::remove_var(HTTP_TOKEN_ENV);
1052        assert!(
1053            token.is_none(),
1054            "whitespace-only env requests no fixed token"
1055        );
1056        assert!(src.is_empty());
1057    }
1058
1059    #[test]
1060    fn resolve_token_flag_overrides_env() {
1061        // #377: --auth-token must win over LEAN_CTX_HTTP_TOKEN so it survives
1062        // environments that strip/fail to inherit the env var.
1063        let _g = ENV_LOCK.lock().expect("env lock");
1064        crate::test_env::set_var(HTTP_TOKEN_ENV, "lctx_fromenv");
1065        let (token, src) = resolve_requested_token(Some("lctx_fromflag"));
1066        crate::test_env::remove_var(HTTP_TOKEN_ENV);
1067        assert_eq!(src, "--auth-token");
1068        assert_eq!(token.as_deref(), Some("lctx_fromflag"));
1069    }
1070
1071    #[test]
1072    fn resolve_token_uses_flag_when_env_unset() {
1073        let _g = ENV_LOCK.lock().expect("env lock");
1074        crate::test_env::remove_var(HTTP_TOKEN_ENV);
1075        let (token, src) = resolve_requested_token(Some("  lctx_flag_padded  "));
1076        assert_eq!(src, "--auth-token");
1077        assert_eq!(token.as_deref(), Some("lctx_flag_padded"));
1078    }
1079
1080    #[test]
1081    fn resolve_token_empty_flag_falls_back_to_env() {
1082        let _g = ENV_LOCK.lock().expect("env lock");
1083        crate::test_env::set_var(HTTP_TOKEN_ENV, "lctx_fromenv");
1084        let (token, src) = resolve_requested_token(Some("   "));
1085        crate::test_env::remove_var(HTTP_TOKEN_ENV);
1086        assert_eq!(src, HTTP_TOKEN_ENV);
1087        assert_eq!(token.as_deref(), Some("lctx_fromenv"));
1088    }
1089}