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_REPLAY_JS: &str = include_str!("static/components/cockpit-replay.js");
37const COCKPIT_COMPONENT_LEADERBOARD_JS: &str =
38    include_str!("static/components/cockpit-leaderboard.js");
39const COCKPIT_COMPONENT_AREA_TABS_JS: &str = include_str!("static/components/cockpit-area-tabs.js");
40const COCKPIT_COMPONENT_PROTECTION_JS: &str =
41    include_str!("static/components/cockpit-protection.js");
42const COCKPIT_COMPONENT_SETTINGS_JS: &str = include_str!("static/components/cockpit-settings.js");
43
44// Vendored third-party libraries — embedded so the dashboard works fully offline
45// (no external CDN). Served as text via the standard route pipeline.
46const COCKPIT_VENDOR_CHART_JS: &str = include_str!("static/vendor/chart.umd.min.js");
47const COCKPIT_VENDOR_D3_JS: &str = include_str!("static/vendor/d3.min.js");
48const COCKPIT_FONTS_CSS: &str = include_str!("static/fonts/fonts.css");
49const COCKPIT_FAVICON_SVG: &str = include_str!("static/favicon.svg");
50
51// Self-hosted variable fonts (binary woff2). Served via a dedicated binary
52// branch in `handle_request` so the bytes are never corrupted by the
53// String-based route pipeline.
54const FONT_INTER_WOFF2: &[u8] = include_bytes!("static/fonts/inter-variable.woff2");
55const FONT_JETBRAINS_WOFF2: &[u8] = include_bytes!("static/fonts/jetbrains-mono-variable.woff2");
56const FONT_SPACE_GROTESK_WOFF2: &[u8] = include_bytes!("static/fonts/space-grotesk-variable.woff2");
57
58/// Maps a request path to an embedded binary font asset.
59fn match_font_asset(path: &str) -> Option<&'static [u8]> {
60    match path {
61        "/static/fonts/inter-variable.woff2" => Some(FONT_INTER_WOFF2),
62        "/static/fonts/jetbrains-mono-variable.woff2" => Some(FONT_JETBRAINS_WOFF2),
63        "/static/fonts/space-grotesk-variable.woff2" => Some(FONT_SPACE_GROTESK_WOFF2),
64        _ => None,
65    }
66}
67
68pub mod base_path;
69pub mod routes;
70pub(crate) mod vscode_open;
71
72pub async fn start(
73    port: Option<u16>,
74    host: Option<String>,
75    base_path: Option<String>,
76    auth_token: Option<String>,
77    open_mode: Option<String>,
78    auth_enabled: Option<bool>,
79) {
80    // How to reveal the URL once the server is up: --open= flag > env > browser.
81    let open = resolve_open_mode(open_mode.as_deref());
82    let port = port.unwrap_or_else(|| {
83        std::env::var("LEAN_CTX_PORT")
84            .ok()
85            .and_then(|p| p.parse().ok())
86            .unwrap_or(DEFAULT_PORT)
87    });
88
89    let host = host.unwrap_or_else(|| {
90        std::env::var("LEAN_CTX_HOST")
91            .ok()
92            .unwrap_or_else(|| DEFAULT_HOST.to_string())
93    });
94
95    // Reverse-proxy subpath (e.g. `/dashboard`). Normalized to "" or "/prefix".
96    // Shared across connections behind an Arc; "" means "no subpath" (#355).
97    let base_path = Arc::new(
98        base_path
99            .or_else(|| std::env::var("LEAN_CTX_DASHBOARD_BASE_PATH").ok())
100            .map(|b| base_path::normalize(&b))
101            .unwrap_or_default(),
102    );
103
104    let addr = format!("{host}:{port}");
105    let is_local = host == "127.0.0.1" || host == "localhost" || host == "::1";
106
107    // Whether the dashboard requires a Bearer token. Precedence:
108    // `--no-auth`/`--auth=` flag > LEAN_CTX_DASHBOARD_AUTH env > `dashboard_auth`
109    // config > default `true`. When disabled, no token is generated and the
110    // sensitive endpoints (`/api/*`, `/metrics`) are guarded by request-header
111    // checks (Sec-Fetch-Site / Origin / Host allowlist) instead — see
112    // `no_auth_request_ok`.
113    let auth_required = resolve_auth_enabled(auth_enabled);
114
115    // Host values accepted in no-auth mode (anti-DNS-rebinding allowlist). Built
116    // once and shared with every connection.
117    let allowed_hosts = Arc::new(build_allowed_hosts(&host, port));
118
119    // Resolve any *requested* fixed token (flag > LEAN_CTX_HTTP_TOKEN) up-front;
120    // `None` means "generate a random one". Done before the already-running check
121    // so we can warn when the requested token won't match a live instance (#377).
122    let (requested_token, token_src) = resolve_requested_token(auth_token.as_deref());
123
124    // Avoid accidental multiple dashboard instances (common source of "it hangs").
125    // Only safe to auto-detect for local dashboards without auth.
126    if is_local && dashboard_responding(&host, port) {
127        println!("\n  lean-ctx dashboard already running → http://{host}:{port}{base_path}");
128        if let Some(req) = requested_token.as_deref()
129            && load_saved_token().as_deref() != Some(req)
130        {
131            eprintln!(
132                "  \x1b[33m⚠\x1b[0m The running instance uses a different token — your {token_src} \
133                     will be rejected. Stop it (Ctrl+C) and restart to apply the new token."
134            );
135        }
136        println!("  Tip: use Ctrl+C in the existing terminal to stop it.\n");
137        if let Some(t) = load_saved_token() {
138            open_dashboard_url(
139                &format!("http://localhost:{port}{base_path}/?token={t}"),
140                open,
141            );
142        } else {
143            open_dashboard_url(&format!("http://localhost:{port}{base_path}/"), open);
144        }
145        return;
146    }
147
148    // Auth defaults on (even on loopback) to prevent cross-origin reads of /api/*
149    // from a malicious website (CORS is not a reliable boundary for localhost
150    // services). When explicitly disabled, run token-less: cross-origin/CSRF and
151    // DNS-rebinding attacks are blocked by `no_auth_request_ok` instead.
152    let token = if auth_required {
153        let t = requested_token.unwrap_or_else(generate_token);
154        Some(Arc::new(t))
155    } else {
156        if requested_token.is_some() {
157            eprintln!(
158                "  \x1b[33m⚠\x1b[0m Ignoring the pinned token ({token_src}) — auth is disabled."
159            );
160        }
161        None
162    };
163
164    // Bind BEFORE persisting the token: two racing `lean-ctx dashboard` starts
165    // both used to write their fresh token, the bind loser exited — leaving a
166    // token on disk that the surviving server never accepted. Every later
167    // "already running" browser open (and any tool reading dashboard.token)
168    // then got 401s. Binding first makes the loser exit without touching the
169    // file, so dashboard.token always belongs to the live listener.
170    let listener = match TcpListener::bind(&addr).await {
171        Ok(l) => l,
172        Err(e) => {
173            eprintln!("Failed to bind to {addr}: {e}");
174            std::process::exit(1);
175        }
176    };
177
178    if let Some(t) = token.as_ref() {
179        save_token(t);
180        let masked = if t.len() > 12 {
181            format!(
182                "{}…{}",
183                &t[..t.floor_char_boundary(8)],
184                &t[t.ceil_char_boundary(t.len().saturating_sub(4))..]
185            )
186        } else {
187            t.to_string()
188        };
189        let src = if token_src.is_empty() {
190            String::new()
191        } else {
192            format!(" (from {token_src})")
193        };
194        if is_local {
195            println!("  Auth: enabled (local){src}");
196            println!("  Browser URL:  http://localhost:{port}{base_path}/?token={t}");
197        } else {
198            eprintln!(
199                "  \x1b[33m⚠\x1b[0m Binding to {host} — authentication enabled.\n  \
200                 Bearer token{src}: \x1b[1;32m{masked}\x1b[0m\n  \
201                 Browser URL:  http://<your-ip>:{port}{base_path}/?token={t}"
202            );
203        }
204    } else if is_local {
205        // No-auth on loopback: header-based CSRF protection is the boundary.
206        println!(
207            "  Auth: \x1b[1;33mDISABLED\x1b[0m (no-auth) — CSRF protected via Sec-Fetch-Site/Origin/Host"
208        );
209        println!("  Browser URL:  http://localhost:{port}{base_path}/");
210    } else {
211        // No-auth + non-loopback bind (e.g. Docker --host=0.0.0.0). Browser
212        // cross-origin/CSRF is still blocked, but non-browser clients that can
213        // reach the address have unauthenticated access — warn loudly.
214        eprintln!(
215            "  \x1b[33m⚠\x1b[0m Auth \x1b[1;31mDISABLED\x1b[0m and binding to {host} (not loopback).\n  \
216             Browser cross-origin/CSRF stays blocked (Sec-Fetch-Site/Origin/Host),\n  \
217             but ANY non-browser client that can reach {host}:{port} has full access.\n  \
218             Docker: publish only to the host loopback → -p 127.0.0.1:{port}:{port}\n  \
219             Add reachable hostnames via LEAN_CTX_DASHBOARD_ALLOWED_HOSTS=host:port,…\n  \
220             Browser URL:  http://<your-ip>:{port}{base_path}/"
221        );
222    }
223
224    let stats_path = crate::core::data_dir::lean_ctx_data_dir().map_or_else(
225        |_| "~/.lean-ctx/stats.json".to_string(),
226        |d| d.join("stats.json").display().to_string(),
227    );
228
229    if host == "0.0.0.0" {
230        println!("\n  lean-ctx dashboard → http://0.0.0.0:{port} (all interfaces)");
231        println!("  Local access:  http://localhost:{port}");
232    } else {
233        println!("\n  lean-ctx dashboard → http://{host}:{port}");
234    }
235    println!("  Stats file: {stats_path}");
236    println!("  Press Ctrl+C to stop");
237    println!(
238        "  \x1b[2m💡 Join the public leaderboard at https://leanctx.com/metrics: lean-ctx gain --publish --leaderboard\x1b[0m\n"
239    );
240
241    if is_local {
242        if let Some(t) = token.as_ref() {
243            open_dashboard_url(
244                &format!("http://localhost:{port}{base_path}/?token={t}"),
245                open,
246            );
247        } else {
248            open_dashboard_url(&format!("http://localhost:{port}{base_path}/"), open);
249        }
250    }
251    if crate::shell::is_container() && is_local {
252        println!("  Tip (Docker): bind 0.0.0.0 + publish port:");
253        println!("    lean-ctx dashboard --host=0.0.0.0 --port={port}");
254        println!("    docker run ... -p {port}:{port} ...");
255        println!();
256    }
257
258    if crate::core::datadog_push::spawn_if_enabled() {
259        println!(
260            "  Datadog push: enabled (agentless, every LEAN_CTX_DATADOG_INTERVAL_SECS or 60s)"
261        );
262    }
263
264    loop {
265        if let Ok((stream, _)) = listener.accept().await {
266            let token_ref = token.clone();
267            let base_ref = base_path.clone();
268            let allowed_ref = allowed_hosts.clone();
269            tokio::spawn(handle_request(stream, token_ref, base_ref, allowed_ref));
270        }
271    }
272}
273
274/// Name of the env var that pins the dashboard Bearer token (#377).
275const HTTP_TOKEN_ENV: &str = "LEAN_CTX_HTTP_TOKEN";
276/// Read-only token accepted **only** for `GET /metrics` (GL #401) so
277/// monitoring agents never hold the full dashboard credential.
278const SCRAPE_TOKEN_ENV: &str = "LEAN_CTX_SCRAPE_TOKEN";
279/// Toggles dashboard Bearer-token auth. `false`/`0`/`no`/`off` disable it.
280const DASHBOARD_AUTH_ENV: &str = "LEAN_CTX_DASHBOARD_AUTH";
281/// Extra `Host` header values accepted in no-auth mode (CSV, e.g.
282/// `box.local:3333,10.0.0.5:3333`). Extends the loopback/bound-host allowlist
283/// for Docker/reverse-proxy setups reached via a custom hostname.
284const ALLOWED_HOSTS_ENV: &str = "LEAN_CTX_DASHBOARD_ALLOWED_HOSTS";
285
286/// Parse a human boolean (`true/false/1/0/yes/no/on/off`, case-insensitive).
287fn parse_human_bool(s: &str) -> Option<bool> {
288    match s.trim().to_ascii_lowercase().as_str() {
289        "true" | "1" | "yes" | "on" => Some(true),
290        "false" | "0" | "no" | "off" => Some(false),
291        _ => None,
292    }
293}
294
295/// Resolve whether the dashboard requires Bearer-token auth. Precedence:
296/// `--no-auth`/`--auth=` flag > `LEAN_CTX_DASHBOARD_AUTH` env > `dashboard_auth`
297/// config > default `true`.
298fn resolve_auth_enabled(flag: Option<bool>) -> bool {
299    if let Some(v) = flag {
300        return v;
301    }
302    if let Ok(raw) = std::env::var(DASHBOARD_AUTH_ENV)
303        && let Some(v) = parse_human_bool(&raw)
304    {
305        return v;
306    }
307    crate::core::config::Config::load().dashboard_auth
308}
309
310/// Build the `Host` header allowlist for no-auth mode (anti-DNS-rebinding).
311/// Always includes the loopback aliases for `port` (localhost is the intended
312/// audience), the actual bound `host:port`, and any `LEAN_CTX_DASHBOARD_ALLOWED_HOSTS`
313/// entries. Bare-host forms (no port) are added too so non-browser clients that
314/// omit the port aren't rejected. `0.0.0.0` is never added — browsers don't send
315/// `Host: 0.0.0.0`; operators expose reachable names via the env allowlist.
316fn build_allowed_hosts(host: &str, port: u16) -> Vec<String> {
317    let mut allowed: Vec<String> = Vec::new();
318    let mut push = |h: String| {
319        if !h.is_empty() && !allowed.iter().any(|e| e.eq_ignore_ascii_case(&h)) {
320            allowed.push(h);
321        }
322    };
323    for base in ["127.0.0.1", "localhost", "[::1]", "::1"] {
324        push(base.to_string());
325        push(format!("{base}:{port}"));
326    }
327    if host != "0.0.0.0" && host != "::" {
328        push(host.to_string());
329        push(format!("{host}:{port}"));
330    }
331    if let Ok(raw) = std::env::var(ALLOWED_HOSTS_ENV) {
332        for entry in raw.split(',') {
333            push(entry.trim().to_string());
334        }
335    }
336    allowed
337}
338
339/// Is the request `Host` header in the allowlist (case-insensitive)?
340fn host_allowed(host: &str, allowed: &[String]) -> bool {
341    allowed.iter().any(|a| a.eq_ignore_ascii_case(host))
342}
343
344/// True when the `Host` header's hostname is a loopback literal
345/// (`localhost`, `127.0.0.0/8`, or `::1`), **regardless of port**.
346///
347/// A loopback `Host` is never a DNS-rebinding vector: the browser only sends one
348/// when the user navigated to a loopback URL directly (an attacker can't make
349/// their own hostname resolve to — and report a `Host` of — `127.0.0.1`). So in
350/// no-auth mode we accept loopback on any port, not just the bound one. This is
351/// what makes a port-remapped Docker publish work out of the box — e.g. the
352/// container binds `0.0.0.0:3333`, Docker publishes it as `-p 60000:3333`, and
353/// the host browser reaches `http://127.0.0.1:60000`, so the `Host` header is
354/// `127.0.0.1:60000` (the *published* port), which the bind-port allowlist
355/// (`127.0.0.1:3333`) would otherwise reject. Cross-origin/CSRF stays blocked by
356/// the `Sec-Fetch-Site`/`Origin` checks in `no_auth_request_ok`.
357fn host_is_loopback(host: &str) -> bool {
358    // Extract the hostname, dropping any `:port`. IPv6 literals are bracketed
359    // (`[::1]` / `[::1]:port`); a bare IPv6 (`::1`) can't carry a port.
360    let hostname = if let Some(rest) = host.strip_prefix('[') {
361        match rest.split_once(']') {
362            Some((inner, _)) => inner,
363            None => return false,
364        }
365    } else if host.matches(':').count() == 1 {
366        host.rsplit_once(':').map_or(host, |(h, _)| h)
367    } else {
368        // No colon (bare host[:no-port]) or multiple colons (unbracketed IPv6).
369        host
370    };
371    if hostname.eq_ignore_ascii_case("localhost") {
372        return true;
373    }
374    if let Ok(v4) = hostname.parse::<std::net::Ipv4Addr>() {
375        return v4.is_loopback();
376    }
377    if let Ok(v6) = hostname.parse::<std::net::Ipv6Addr>() {
378        return v6.is_loopback();
379    }
380    false
381}
382
383/// Token-free request gate for no-auth dashboards. Applied to the same sensitive
384/// endpoints the Bearer token guards (`/api/*`, `/metrics`). Blocks browser
385/// cross-origin/CSRF and DNS-rebinding without a credential:
386///  * `Sec-Fetch-Site`, when sent, must be `same-origin` or `none` (the header is
387///    set by the browser and cannot be forged by page JS).
388///  * `Host` must be in `allowed_hosts` (missing `Host` is rejected).
389///  * `Origin`, when sent and not `null`, must be same-origin as `Host`.
390///
391/// Non-browser clients (curl, Prometheus) omit `Sec-Fetch-Site`/`Origin` and pass
392/// those checks — they only need to target an allowlisted `Host`.
393fn no_auth_request_ok(header_section: &str, allowed_hosts: &[String]) -> bool {
394    if let Some(sfs) = header_line_value(header_section, "Sec-Fetch-Site") {
395        let sfs = sfs.trim();
396        if !sfs.is_empty()
397            && !sfs.eq_ignore_ascii_case("same-origin")
398            && !sfs.eq_ignore_ascii_case("none")
399        {
400            return false;
401        }
402    }
403    let Some(host) = header_line_value(header_section, "Host") else {
404        return false;
405    };
406    // Accept the explicit allowlist (loopback aliases for the bound port, the
407    // bound host, and any LEAN_CTX_DASHBOARD_ALLOWED_HOSTS entries) OR any
408    // loopback host on any port. The latter covers port-remapped Docker
409    // publishes (e.g. `-p 60000:3333` reached via `127.0.0.1:60000`) without a
410    // manual allowlist entry — loopback hosts are not a rebinding vector.
411    if !host_allowed(host, allowed_hosts) && !host_is_loopback(host) {
412        return false;
413    }
414    if let Some(origin) = header_line_value(header_section, "Origin")
415        && !origin.is_empty()
416        && !origin.eq_ignore_ascii_case("null")
417        && !origin_matches_dashboard_host(origin, host)
418    {
419        return false;
420    }
421    true
422}
423
424/// Resolve the dashboard Bearer token.
425///
426/// Honors `LEAN_CTX_HTTP_TOKEN` (#377): when set to a non-empty value it is used
427/// verbatim so reverse-proxy / container deployments keep a stable token across
428/// restarts and redeploys (nginx can inject a fixed `Authorization: Bearer …`).
429/// When unset or empty, a fresh random token is generated (no behavior change).
430///
431/// Resolve a *requested* fixed token with precedence `--auth-token` flag >
432/// `LEAN_CTX_HTTP_TOKEN` (#377). The flag wins so it survives container/service
433/// environments that strip or fail to inherit the env var. Returns the trimmed,
434/// non-empty token and a human label of its source; `None` means "no fixed token
435/// requested → caller generates a random one".
436fn resolve_requested_token(flag: Option<&str>) -> (Option<String>, &'static str) {
437    if let Some(t) = flag.map(str::trim).filter(|s| !s.is_empty()) {
438        return (Some(t.to_string()), "--auth-token");
439    }
440    if let Ok(raw) = std::env::var(HTTP_TOKEN_ENV) {
441        let trimmed = raw.trim();
442        if !trimmed.is_empty() {
443            return (Some(trimmed.to_string()), HTTP_TOKEN_ENV);
444        }
445    }
446    (None, "")
447}
448
449fn generate_token() -> String {
450    let mut bytes = [0u8; 32];
451    if getrandom::fill(&mut bytes).is_err() {
452        tracing::warn!("CSPRNG unavailable — falling back to time-based token");
453        let ts = std::time::SystemTime::now()
454            .duration_since(std::time::UNIX_EPOCH)
455            .unwrap_or_default()
456            .as_nanos();
457        for (i, b) in bytes.iter_mut().enumerate() {
458            *b = ((ts >> (i % 16 * 8)) & 0xFF) as u8;
459        }
460    }
461    format!("lctx_{}", hex_lower(&bytes))
462}
463
464fn save_token(token: &str) {
465    if let Ok(dir) = crate::core::paths::state_dir() {
466        let _ = std::fs::create_dir_all(&dir);
467        let path = dir.join("dashboard.token");
468        #[cfg(unix)]
469        {
470            use std::io::Write;
471            use std::os::unix::fs::OpenOptionsExt;
472            let Ok(mut f) = std::fs::OpenOptions::new()
473                .write(true)
474                .create(true)
475                .truncate(true)
476                .mode(0o600)
477                .open(&path)
478            else {
479                return;
480            };
481            let _ = f.write_all(token.as_bytes());
482        }
483        #[cfg(not(unix))]
484        {
485            let _ = std::fs::write(&path, token);
486        }
487    }
488}
489
490fn load_saved_token() -> Option<String> {
491    let dir = crate::core::paths::state_dir().ok()?;
492    let path = dir.join("dashboard.token");
493    std::fs::read_to_string(path)
494        .ok()
495        .map(|s| s.trim().to_string())
496}
497
498/// Adds `nonce="..."` to all inline `<script>` tags (those without a `src=` attribute).
499/// External scripts (`<script src="...">`) are left untouched.
500pub fn add_nonce_to_inline_scripts(html: &str, nonce: &str) -> String {
501    let mut result = String::with_capacity(html.len() + 128);
502    let mut remaining = html;
503    while let Some(pos) = remaining.find("<script") {
504        result.push_str(&remaining[..pos]);
505        let tag_start = &remaining[pos..];
506        let tag_end = tag_start.find('>').unwrap_or(tag_start.len());
507        let tag = &tag_start[..=tag_end];
508        if tag.contains("src=") || tag.contains("nonce=") {
509            result.push_str(tag);
510        } else {
511            result.push_str(&tag.replacen("<script", &format!("<script nonce=\"{nonce}\""), 1));
512        }
513        remaining = &tag_start[tag_end + 1..];
514    }
515    result.push_str(remaining);
516    result
517}
518
519fn hex_lower(bytes: &[u8]) -> String {
520    const HEX: &[u8; 16] = b"0123456789abcdef";
521    let mut out = String::with_capacity(bytes.len() * 2);
522    for &b in bytes {
523        out.push(HEX[(b >> 4) as usize] as char);
524        out.push(HEX[(b & 0x0f) as usize] as char);
525    }
526    out
527}
528
529/// How `lean-ctx dashboard` reveals the URL after the server is up (#424).
530#[derive(Clone, Copy, PartialEq, Eq, Debug)]
531enum DashboardOpen {
532    /// Launch the system default browser (historical default).
533    Browser,
534    /// Don't auto-launch anything — just print the URL. For users who run the
535    /// dashboard inside an editor / reverse proxy and don't want a new window.
536    None,
537    /// Suppress the external browser and print the steps to open the URL in
538    /// VS Code's built-in browser. VS Code exposes no stable CLI flag to open
539    /// its Simple/Integrated Browser, so we guide rather than fake it.
540    Vscode,
541}
542
543/// Resolve the open mode from (in precedence order) the `--open=` flag, the
544/// `LEAN_CTX_DASHBOARD_OPEN` env var, else the `browser` default.
545fn resolve_open_mode(flag: Option<&str>) -> DashboardOpen {
546    let raw = flag
547        .map(str::to_string)
548        .or_else(|| std::env::var("LEAN_CTX_DASHBOARD_OPEN").ok())
549        .unwrap_or_default();
550    match raw.trim().to_ascii_lowercase().as_str() {
551        "none" | "off" | "false" | "no" => DashboardOpen::None,
552        "vscode" | "code" | "editor" => DashboardOpen::Vscode,
553        _ => DashboardOpen::Browser,
554    }
555}
556
557/// Reveal `url` to the user according to `mode`.
558fn open_dashboard_url(url: &str, mode: DashboardOpen) {
559    match mode {
560        DashboardOpen::Browser => open_browser(url),
561        DashboardOpen::None => {}
562        DashboardOpen::Vscode => {
563            // Prefer the extension's native webview tab (#466 item 3): with the
564            // lean-ctx VS Code extension installed, one command opens the
565            // dashboard as a real editor tab — no URL copy/paste. Keep the
566            // Simple Browser path as the no-extension fallback.
567            println!(
568                "  \x1b[2mNative tab: run ⇧⌘P → \"lean-ctx: Open Web Dashboard\" (needs the lean-ctx VS Code extension)\x1b[0m"
569            );
570            println!(
571                "  \x1b[2mNo extension? ⇧⌘P → \"Simple Browser: Show\" → paste the URL above\x1b[0m"
572            );
573        }
574    }
575}
576
577fn open_browser(url: &str) {
578    #[cfg(target_os = "macos")]
579    {
580        let _ = std::process::Command::new("open").arg(url).spawn();
581    }
582
583    #[cfg(target_os = "linux")]
584    {
585        let _ = std::process::Command::new("xdg-open")
586            .arg(url)
587            .stderr(std::process::Stdio::null())
588            .spawn();
589    }
590
591    #[cfg(target_os = "windows")]
592    {
593        let _ = std::process::Command::new("cmd")
594            .args(["/C", "start", url])
595            .spawn();
596    }
597}
598
599/// Probes `http://{host}:{port}/api/version` (auth-aware) and returns true only
600/// when it answers `200` with the lean-ctx dashboard's own version JSON. Single
601/// source of truth for "is *our* dashboard already live on this port": used both
602/// when opening the browser (avoids spawning a second instance) and by `doctor`'s
603/// port check, so port 3333 held by our own dashboard reads as healthy instead of
604/// a false conflict (#644). The body check is what tells our dashboard apart from
605/// an unrelated service that merely answers 200 on the same port.
606pub(crate) fn dashboard_responding(host: &str, port: u16) -> bool {
607    use std::io::{Read, Write};
608    use std::net::TcpStream;
609    use std::time::Duration;
610
611    let addr = format!("{host}:{port}");
612    let Ok(mut s) = TcpStream::connect_timeout(
613        &addr
614            .parse()
615            .unwrap_or_else(|_| std::net::SocketAddr::from(([127, 0, 0, 1], port))),
616        Duration::from_millis(150),
617    ) else {
618        return false;
619    };
620    let _ = s.set_read_timeout(Some(Duration::from_millis(150)));
621    let _ = s.set_write_timeout(Some(Duration::from_millis(150)));
622
623    let auth_header = load_saved_token()
624        .map(|t| format!("Authorization: Bearer {t}\r\n"))
625        .unwrap_or_default();
626    let req = format!(
627        "GET /api/version HTTP/1.1\r\nHost: localhost\r\n{auth_header}Connection: close\r\n\r\n"
628    );
629    if s.write_all(req.as_bytes()).is_err() {
630        return false;
631    }
632
633    // Read until the peer closes (Connection: close) so the JSON body — not just
634    // the status line — is captured, bounded so a rogue peer can't stream forever.
635    // Field markers mirror `version_check::version_info_json`.
636    let mut resp = Vec::new();
637    let mut buf = [0u8; 1024];
638    while resp.len() < 8 * 1024 {
639        match s.read(&mut buf) {
640            Ok(0) | Err(_) => break,
641            Ok(n) => resp.extend_from_slice(&buf[..n]),
642        }
643    }
644    let resp = String::from_utf8_lossy(&resp);
645    (resp.starts_with("HTTP/1.1 200") || resp.starts_with("HTTP/1.0 200"))
646        && resp.contains(r#""current":"#)
647        && resp.contains(r#""latest":"#)
648        && resp.contains(r#""update_available":"#)
649}
650
651const MAX_HTTP_MESSAGE: usize = 2 * 1024 * 1024;
652
653fn header_line_value<'a>(header_section: &'a str, name: &str) -> Option<&'a str> {
654    for line in header_section.lines() {
655        let Some((k, v)) = line.split_once(':') else {
656            continue;
657        };
658        if k.trim().eq_ignore_ascii_case(name) {
659            return Some(v.trim());
660        }
661    }
662    None
663}
664
665/// Loopback dashboards often use `localhost` vs `127.0.0.1` interchangeably in `Origin`.
666fn host_loopback_aliases(host: &str) -> Vec<String> {
667    let mut v = vec![host.to_string()];
668    if let Some(port) = host.strip_prefix("127.0.0.1:") {
669        v.push(format!("localhost:{port}"));
670    }
671    if let Some(port) = host.strip_prefix("localhost:") {
672        v.push(format!("127.0.0.1:{port}"));
673    }
674    if let Some(port) = host.strip_prefix("[::1]:") {
675        v.push(format!("127.0.0.1:{port}"));
676        v.push(format!("localhost:{port}"));
677    }
678    v
679}
680
681fn origin_matches_dashboard_host(origin: &str, host: &str) -> bool {
682    let origin = origin.trim_end_matches('/');
683    for h in host_loopback_aliases(host) {
684        if origin.eq_ignore_ascii_case(&format!("http://{h}"))
685            || origin.eq_ignore_ascii_case(&format!("https://{h}"))
686        {
687            return true;
688        }
689    }
690    false
691}
692
693/// Defense-in-depth for browser POSTs: reject cross-site `Origin` on mutating `/api/*` calls.
694/// Non-browser clients (no `Origin`) remain allowed when Bearer auth succeeds.
695fn csrf_origin_ok(header_section: &str, method: &str, path: &str) -> bool {
696    let uc = method.to_ascii_uppercase();
697    if !matches!(uc.as_str(), "POST" | "PUT" | "PATCH" | "DELETE") {
698        return true;
699    }
700    if !path.starts_with("/api/") {
701        return true;
702    }
703    let Some(origin) = header_line_value(header_section, "Origin") else {
704        return true;
705    };
706    if origin.is_empty() || origin.eq_ignore_ascii_case("null") {
707        return true;
708    }
709    let Some(host) = header_line_value(header_section, "Host") else {
710        return false;
711    };
712    origin_matches_dashboard_host(origin, host)
713}
714
715fn find_headers_end(buf: &[u8]) -> Option<usize> {
716    buf.windows(4).position(|w| w == b"\r\n\r\n")
717}
718
719fn parse_content_length_header(header_section: &[u8]) -> Option<usize> {
720    let text = String::from_utf8_lossy(header_section);
721    for line in text.lines() {
722        let Some((k, v)) = line.split_once(':') else {
723            continue;
724        };
725        if k.trim().eq_ignore_ascii_case("content-length") {
726            return v.trim().parse::<usize>().ok();
727        }
728    }
729    Some(0)
730}
731
732async fn read_http_message(stream: &mut tokio::net::TcpStream) -> Option<Vec<u8>> {
733    let mut buf = Vec::new();
734    let mut tmp = [0u8; 8192];
735    loop {
736        if let Some(end) = find_headers_end(&buf) {
737            let cl = parse_content_length_header(&buf[..end])?;
738            let total = end + 4 + cl;
739            if total > MAX_HTTP_MESSAGE {
740                return None;
741            }
742            if buf.len() >= total {
743                buf.truncate(total);
744                return Some(buf);
745            }
746        } else if buf.len() > 65_536 {
747            return None;
748        }
749
750        let n = stream.read(&mut tmp).await.ok()?;
751        if n == 0 {
752            return None;
753        }
754        buf.extend_from_slice(&tmp[..n]);
755        if buf.len() > MAX_HTTP_MESSAGE {
756            return None;
757        }
758    }
759}
760
761async fn handle_request(
762    mut stream: tokio::net::TcpStream,
763    token: Option<Arc<String>>,
764    base_path: Arc<String>,
765    allowed_hosts: Arc<Vec<String>>,
766) {
767    let is_loopback = stream.peer_addr().is_ok_and(|a| a.ip().is_loopback());
768
769    let Some(buf) = read_http_message(&mut stream).await else {
770        return;
771    };
772    let Some(header_end) = find_headers_end(&buf) else {
773        return;
774    };
775    let header_text = String::from_utf8_lossy(&buf[..header_end]).to_string();
776    let body_start = header_end + 4;
777    let Some(content_len) = parse_content_length_header(&buf[..header_end]) else {
778        return;
779    };
780    if buf.len() < body_start + content_len {
781        return;
782    }
783    let body_str = std::str::from_utf8(&buf[body_start..body_start + content_len])
784        .unwrap_or("")
785        .to_string();
786
787    let first = header_text.lines().next().unwrap_or("");
788    let mut parts = first.split_whitespace();
789    let method = parts.next().unwrap_or("GET").to_string();
790    let raw_path = parts.next().unwrap_or("/").to_string();
791
792    let (path, query_token) = if let Some(idx) = raw_path.find('?') {
793        let p = &raw_path[..idx];
794        let qs = &raw_path[idx + 1..];
795        let tok = qs
796            .split('&')
797            .find_map(|pair| pair.strip_prefix("token="))
798            .map(std::string::ToString::to_string);
799        (p.to_string(), tok)
800    } else {
801        (raw_path.clone(), None)
802    };
803
804    let query_str = raw_path
805        .find('?')
806        .map_or(String::new(), |i| raw_path[i + 1..].to_string());
807
808    // Strip the reverse-proxy subpath prefix (if any) so all downstream matching
809    // (fonts, auth, routing) works on root-relative paths whether or not the
810    // proxy already stripped it (#355).
811    let path = base_path::strip(&path, base_path.as_str()).to_string();
812
813    // Binary font assets are public (like CSS/JS) and bypass the String-based
814    // route pipeline so their bytes stay intact.
815    if let Some(bytes) = match_font_asset(&path) {
816        let header = format!(
817            "HTTP/1.1 200 OK\r\n\
818             Content-Type: font/woff2\r\n\
819             Content-Length: {}\r\n\
820             Cache-Control: public, max-age=31536000, immutable\r\n\
821             X-Content-Type-Options: nosniff\r\n\
822             Connection: close\r\n\
823             \r\n",
824            bytes.len()
825        );
826        let _ = stream.write_all(header.as_bytes()).await;
827        let _ = stream.write_all(bytes).await;
828        return;
829    }
830
831    let is_api = path.starts_with("/api/");
832    let requires_auth = is_api || path == "/metrics";
833
834    if let Some(ref expected) = token {
835        let mut has_header_auth = check_auth(&header_text, expected);
836
837        // Read-only scrape token (GL #401): lets a Prometheus/Datadog agent
838        // scrape `/metrics` without holding the full dashboard token. Valid
839        // for the metrics endpoint only — every other API stays gated on the
840        // dashboard token.
841        if !has_header_auth
842            && path == "/metrics"
843            && let Ok(scrape) = std::env::var(SCRAPE_TOKEN_ENV)
844        {
845            let scrape = scrape.trim();
846            if !scrape.is_empty() && check_auth(&header_text, scrape) {
847                has_header_auth = true;
848            }
849        }
850
851        if requires_auth && !has_header_auth {
852            let body = r#"{"error":"unauthorized"}"#;
853            let response = format!(
854                "HTTP/1.1 401 Unauthorized\r\n\
855                 Content-Type: application/json\r\n\
856                 Content-Length: {}\r\n\
857                 WWW-Authenticate: Bearer\r\n\
858                 Connection: close\r\n\
859                 \r\n\
860                 {body}",
861                body.len()
862            );
863            let _ = stream.write_all(response.as_bytes()).await;
864            return;
865        }
866
867        if !csrf_origin_ok(&header_text, method.as_str(), path.as_str()) {
868            let body = r#"{"error":"forbidden"}"#;
869            let response = format!(
870                "HTTP/1.1 403 Forbidden\r\n\
871                 Content-Type: application/json\r\n\
872                 Content-Length: {}\r\n\
873                 Connection: close\r\n\
874                 \r\n\
875                 {body}",
876                body.len()
877            );
878            let _ = stream.write_all(response.as_bytes()).await;
879            return;
880        }
881    } else if requires_auth && !no_auth_request_ok(&header_text, &allowed_hosts) {
882        // No-auth mode: the Bearer token is gone, so cross-origin/CSRF and
883        // DNS-rebinding are blocked by request-header validation instead.
884        let body = r#"{"error":"forbidden"}"#;
885        let response = format!(
886            "HTTP/1.1 403 Forbidden\r\n\
887             Content-Type: application/json\r\n\
888             Content-Length: {}\r\n\
889             Connection: close\r\n\
890             \r\n\
891             {body}",
892            body.len()
893        );
894        let _ = stream.write_all(response.as_bytes()).await;
895        return;
896    }
897
898    // Route handlers are synchronous and a few (graph/index builds) do seconds
899    // of disk work. Running them inline on an async worker thread lets one slow
900    // endpoint starve the small worker pool, so a trivial GET like
901    // `/api/settings` can wait minutes behind it (#431, Windows few-core). Run
902    // them on the blocking pool instead: the async workers stay free to serve
903    // light endpoints promptly. `spawn_blocking` also captures panics (returns
904    // a `JoinError`), so the previous `catch_unwind` is no longer needed.
905    let route_started = std::time::Instant::now();
906    let route_label = path.clone();
907    let compute = tokio::task::spawn_blocking(move || {
908        routes::route_response(
909            &path,
910            &query_str,
911            query_token.as_ref(),
912            token.as_ref(),
913            is_loopback,
914            &method,
915            &body_str,
916        )
917    })
918    .await;
919    let (status, content_type, mut body) = match compute {
920        Ok(v) => v,
921        // The blocking task panicked or was cancelled — surface a 500 rather
922        // than dropping the connection.
923        Err(_) => (
924            "500 Internal Server Error",
925            "application/json",
926            r#"{"error":"dashboard route panicked"}"#.to_string(),
927        ),
928    };
929    // Observability: a slow light endpoint is exactly the #431 symptom, so make
930    // any handler that crosses 1s visible in the logs for future diagnosis.
931    let route_elapsed = route_started.elapsed();
932    if route_elapsed >= std::time::Duration::from_secs(1) {
933        tracing::warn!(
934            target: "lean_ctx::dashboard",
935            "slow dashboard route {route_label} took {} ms",
936            route_elapsed.as_millis()
937        );
938    }
939
940    // Under a reverse-proxy subpath, rewrite root-absolute asset/API URLs in the
941    // served HTML/CSS/JS so the browser requests them under the prefix (#355).
942    if !base_path.is_empty()
943        && (content_type.contains("text/html")
944            || content_type.contains("text/css")
945            || content_type.contains("javascript"))
946    {
947        body = base_path::rewrite_asset_urls(&body, base_path.as_str());
948    }
949
950    let cache_header = if content_type.starts_with("application/json") {
951        "Cache-Control: no-cache, no-store, must-revalidate\r\nPragma: no-cache\r\n"
952    } else if content_type.starts_with("application/javascript")
953        || content_type.starts_with("text/css")
954    {
955        "Cache-Control: no-cache, must-revalidate\r\n"
956    } else {
957        ""
958    };
959
960    let nonce = {
961        let mut nb = [0u8; 16];
962        if getrandom::fill(&mut nb).is_err() {
963            nb.iter_mut().enumerate().for_each(|(i, b)| {
964                *b = (std::time::SystemTime::now()
965                    .duration_since(std::time::UNIX_EPOCH)
966                    .unwrap_or_default()
967                    .subsec_nanos()
968                    .wrapping_add(i as u32)) as u8;
969            });
970        }
971        hex_lower(&nb)
972    };
973    if content_type.contains("text/html") {
974        body = add_nonce_to_inline_scripts(&body, &nonce);
975    }
976    let security_headers = format!(
977        "X-Content-Type-Options: nosniff\r\n\
978         X-Frame-Options: DENY\r\n\
979         Referrer-Policy: no-referrer\r\n\
980         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"
981    );
982
983    let response = format!(
984        "HTTP/1.1 {status}\r\n\
985         Content-Type: {content_type}\r\n\
986         Content-Length: {}\r\n\
987         {cache_header}\
988         {security_headers}\
989         Connection: close\r\n\
990         \r\n\
991         {body}",
992        body.len()
993    );
994
995    let _ = stream.write_all(response.as_bytes()).await;
996}
997
998fn check_auth(request: &str, expected_token: &str) -> bool {
999    for line in request.lines() {
1000        let lower = line.to_lowercase();
1001        if lower.starts_with("authorization:") {
1002            let value = line["authorization:".len()..].trim();
1003            if let Some(token) = value
1004                .strip_prefix("Bearer ")
1005                .or_else(|| value.strip_prefix("bearer "))
1006            {
1007                return constant_time_eq(token.trim().as_bytes(), expected_token.as_bytes());
1008            }
1009        }
1010    }
1011    false
1012}
1013
1014fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
1015    if a.len() != b.len() {
1016        return false;
1017    }
1018    bool::from(a.ct_eq(b))
1019}
1020
1021#[cfg(test)]
1022mod tests;