interplane.Get Omega
Read in your language

sovereign-intelligence

Front door to Drake Stapleton's sovereign stack.

Brought by drakestapleton

branch main Branches Tags History

sovereign-intelligence / docs / archive / drakestapleton.com-old / crates / site-server / src / state.rs

126 lines · 5428 bytes Raw Blame History
1use crate::telemetry::TelemetryPacket;
2use axum::body::Bytes;
3use regex::Regex;
4use std::collections::HashMap;
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8use std::time::Instant;
9use tokio::sync::{broadcast, RwLock, Semaphore};
10
11#[derive(Clone)]
12pub struct AppState {
13 pub routes: Arc<HashMap<String, Bytes>>,
14 #[allow(dead_code)]
15 pub static_dir: PathBuf,
16 pub start_time: Instant,
17 pub latest_telemetry: Arc<RwLock<TelemetryPacket>>,
18 pub telemetry_tx: broadcast::Sender<TelemetryPacket>,
19 pub redactor_patterns: Arc<Vec<(Regex, &'static str)>>,
20 pub http_client: reqwest::Client,
21 pub chat_semaphore: Arc<Semaphore>,
22}
23
24fn build_redactor_patterns() -> Vec<(Regex, &'static str)> {
25 vec![
26 (Regex::new(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----").unwrap(), "[REDACTED_PRIVATE_KEY]"),
27 (Regex::new(r"\b(ey[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})\b").unwrap(), "[REDACTED_JWT_TOKEN]"),
28 (Regex::new(r"(?i)\b(bearer\s+)([a-zA-Z0-9_\-\.]{12,})").unwrap(), "[REDACTED_BEARER_TOKEN]"),
29 (Regex::new(r"(?i)(api[_-]?key|secret|password|passwd|token)\s*[:=]\s*([^\s,;]{8,})").unwrap(), "=[REDACTED_SECRET]"),
30 (Regex::new(r"\b(sk-[a-zA-Z0-9_-]{20,})\b").unwrap(), "[REDACTED_OPENAI_KEY]"),
31 (Regex::new(r"\b(sk-ant-[a-zA-Z0-9_-]{20,})\b").unwrap(), "[REDACTED_ANTHROPIC_KEY]"),
32 (Regex::new(r"\b(hf_[a-zA-Z0-9]{20,})\b").unwrap(), "[REDACTED_HUGGINGFACE_TOKEN]"),
33 ]
34}
35
36impl AppState {
37 pub fn new(dist_dir: &Path) -> Result<Self, String> {
38 let route_mappings = vec![
39 ("/", "index.html"),
40 ("/aien", "aien/index.html"),
41 ("/research", "research/index.html"),
42 ("/atlas", "atlas/index.html"),
43 ("/aegis", "aegis/index.html"),
44 ("/software", "software/index.html"),
45 ("/path", "path/index.html"),
46 ("/evidence", "evidence/index.html"),
47 ("/what-i-learned", "what-i-learned/index.html"),
48 ("/interest", "interest/index.html"),
49 ("/symphony", "symphony/index.html"),
50 ("/symphony/first", "symphony/first/index.html"),
51 ("/symphony/workflow", "symphony/workflow/index.html"),
52 ("/symphony/map", "symphony/map/index.html"),
53 ("/works", "works/index.html"),
54 ("/works/atlas-symphony", "works/atlas-symphony/index.html"),
55 ("/works/atlas-harness", "works/atlas-harness/index.html"),
56 ("/works/mobdev-panel-arena", "works/mobdev-panel-arena/index.html"),
57 ("/works/defiantmob", "works/defiantmob/index.html"),
58 ("/works/beltbrain", "works/beltbrain/index.html"),
59 ("/works/dhg-hive", "works/dhg-hive/index.html"),
60 ("/works/foundations-2025", "works/foundations-2025/index.html"),
61 ("/works/aien", "works/aien/index.html"),
62 ("/works/aegis", "works/aegis/index.html"),
63 ("/works/research", "works/research/index.html"),
64 ("/404", "404.html"),
65 ];
66
67 let mut routes = HashMap::new();
68 let ticker_script = "<script defer src=\"/js/live-ticker.js\"></script>";
69
70 for (route, file_rel) in route_mappings {
71 let file_path = dist_dir.join(file_rel);
72 if !file_path.exists() {
73 return Err(format!("Missing required route file: {}", file_path.display()));
74 }
75
76 let raw = fs::read_to_string(&file_path)
77 .map_err(|e| format!("Failed to read {}: {}", file_path.display(), e))?;
78
79 // Assert unslop invariants
80 if raw.contains('\u{2014}') {
81 return Err(format!("Forbidden em dash in {}", file_path.display()));
82 }
83 if raw.contains('\u{2013}') {
84 return Err(format!("Forbidden en dash in {}", file_path.display()));
85 }
86
87 // Inject live ticker script before </head> if present
88 let injected = if raw.contains("</head>") && !raw.contains("/js/live-ticker.js") {
89 raw.replace("</head>", &format!(" {}\n</head>", ticker_script))
90 } else {
91 raw
92 };
93
94 routes.insert(route.to_string(), Bytes::from(injected));
95 }
96
97 let (telemetry_tx, _) = broadcast::channel(64);
98 let initial_telemetry = TelemetryPacket::default();
99 let http_client = reqwest::Client::builder()
100 .timeout(std::time::Duration::from_secs(120))
101 .build()
102 .map_err(|e| format!("Failed to build reqwest client: {}", e))?;
103
104 // Maximum 2 concurrent visitor chat requests to protect GPU compute
105 let chat_semaphore = Arc::new(Semaphore::new(2));
106
107 Ok(Self {
108 routes: Arc::new(routes),
109 static_dir: dist_dir.to_path_buf(),
110 start_time: Instant::now(),
111 latest_telemetry: Arc::new(RwLock::new(initial_telemetry)),
112 telemetry_tx,
113 redactor_patterns: Arc::new(build_redactor_patterns()),
114 http_client,
115 chat_semaphore,
116 })
117 }
118
119 pub fn redact(&self, input: &str) -> String {
120 let mut result = input.to_string();
121 for (pattern, replacement) in self.redactor_patterns.iter() {
122 result = pattern.replace_all(&result, *replacement).to_string();
123 }
124 result
125 }
126}