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