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
44const 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
51const 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
58fn 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 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 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 let auth_required = resolve_auth_enabled(auth_enabled);
114
115 let allowed_hosts = Arc::new(build_allowed_hosts(&host, port));
118
119 let (requested_token, token_src) = resolve_requested_token(auth_token.as_deref());
123
124 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 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 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 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 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
274const HTTP_TOKEN_ENV: &str = "LEAN_CTX_HTTP_TOKEN";
276const SCRAPE_TOKEN_ENV: &str = "LEAN_CTX_SCRAPE_TOKEN";
279const DASHBOARD_AUTH_ENV: &str = "LEAN_CTX_DASHBOARD_AUTH";
281const ALLOWED_HOSTS_ENV: &str = "LEAN_CTX_DASHBOARD_ALLOWED_HOSTS";
285
286fn 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
295fn 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
310fn 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
339fn host_allowed(host: &str, allowed: &[String]) -> bool {
341 allowed.iter().any(|a| a.eq_ignore_ascii_case(host))
342}
343
344fn host_is_loopback(host: &str) -> bool {
358 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 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
383fn 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 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
424fn 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
498pub 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#[derive(Clone, Copy, PartialEq, Eq, Debug)]
531enum DashboardOpen {
532 Browser,
534 None,
537 Vscode,
541}
542
543fn 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
557fn open_dashboard_url(url: &str, mode: DashboardOpen) {
559 match mode {
560 DashboardOpen::Browser => open_browser(url),
561 DashboardOpen::None => {}
562 DashboardOpen::Vscode => {
563 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
599pub(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 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
665fn 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
693fn 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 let path = base_path::strip(&path, base_path.as_str()).to_string();
812
813 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 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 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 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 Err(_) => (
924 "500 Internal Server Error",
925 "application/json",
926 r#"{"error":"dashboard route panicked"}"#.to_string(),
927 ),
928 };
929 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 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;