1use std::collections::BTreeMap;
8use std::convert::Infallible;
9use std::net::SocketAddr;
10use std::path::{Component, PathBuf};
11use std::sync::{Arc, Mutex};
12use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
13
14use anyhow::{Context, Result as AnyResult};
15use axum::body::{Body, Bytes, to_bytes};
16use axum::extract::{DefaultBodyLimit, Path, Query, Request, State};
17use axum::http::header::{
18 CACHE_CONTROL, CONTENT_SECURITY_POLICY as CONTENT_SECURITY_POLICY_HEADER, CONTENT_TYPE, COOKIE,
19 HeaderValue, LOCATION, REFERRER_POLICY, SET_COOKIE, X_CONTENT_TYPE_OPTIONS,
20};
21use axum::http::{HeaderMap, Response, StatusCode};
22use axum::middleware::Next;
23use axum::response::IntoResponse;
24use axum::response::sse::{Event, KeepAlive, Sse};
25use axum::routing::{get, post, put};
26use axum::{Json, Router};
27use base64::Engine as _;
28use hmac::{Hmac, KeyInit, Mac};
29use serde::{Deserialize, Serialize};
30use sha2::Sha256;
31use tokio::sync::Semaphore;
32use tokio::sync::{mpsc, watch};
33use tokio_stream::wrappers::ReceiverStream;
34use tokio_util::sync::CancellationToken;
35
36use mj_core::attachment::{AttachmentRef, AttachmentStore, MAX_IMAGE_BYTES, MAX_IMAGES};
37use mj_core::config::{Config, TargetTemplate, project_history_host, validate_id};
38use mj_core::elicitation::{ElicitationRequest, ElicitationResponse, MAX_ELICITATION_BYTES};
39use mj_core::path_completion::{CompletionHost, CompletionKind, PathCompletion};
40use mj_core::refusal::{Refusal, RefusalKind};
41use mj_core::state::{
42 MoveOperation, MovePhase, MovePreparation, MoveSelection, MoveSessionRequest,
43 ProjectSourceIdentity, SessionResourceAllocation, SessionState, SessionTransitionKind,
44 State as AppState,
45};
46
47use crate::targets::AdditionalMount;
48
49use crate::dictation::{
50 DictationError, DictationOperation, DictationRequest, DictationResponse, MAX_AUDIO_BYTES,
51 validate_wav,
52};
53use crate::image::optimize_image;
54
55pub mod api;
56
57pub use api::{
58 ApiFailure, ApiSession, PromptRequest, PromptResponse, SessionListResponse,
59 StartSessionRequest, StartSessionResponse, SubagentBackend, WaitOutcome, WaitRequest,
60 WaitResponse, api_token_path, load_or_create_api_token, map_stop_reason, resolve_wait,
61};
62
63pub use mj_client::web::{
64 BrowserDiffStat, BrowserTranscript, BrowserTranscriptEntry, WebListenerProcess,
65 WebViewerAccess, WebViewerRecovery,
66};
67
68pub use mj_core::state::ResumeQueueDisposition;
72
73pub fn install_rustls_crypto_provider() {
80 let _ = rustls::crypto::ring::default_provider().install_default();
81}
82
83pub const COOKIE_NAME: &str = "hel_viewer_session";
84const DEFAULT_SESSION_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);
85const EPHEMERAL_SESSION_TTL: Duration = Duration::from_secs(24 * 60 * 60);
86const MAX_BODY_BYTES: usize = 128 * 1024;
87const MAX_CODE_FAILURES: u32 = 5;
88const CODE_LOCKOUT_BASE: Duration = Duration::from_secs(30);
89const CODE_LOCKOUT_CAP: Duration = Duration::from_secs(60 * 60);
90const MAX_TITLE_CHARS: usize = 120;
91const MAX_PROMPT_CHARS: usize = 64 * 1024;
92const MAX_DIRTY_ACKNOWLEDGEMENTS: usize = 32;
95const MAX_DRAFT_BYTES: usize = 64 * 1024;
99pub const MAX_HISTORY_MATCHES: usize = 40;
103const MAX_PROMPT_BODY_BYTES: usize = 32 * 1024 * 1024;
108const MAX_ATTACHMENT_UPLOAD_BYTES: usize = 64 * 1024 * 1024;
112const MAX_CONCURRENT_DICTATIONS: usize = 2;
116pub const MAX_PROMPT_IMAGES: usize = MAX_IMAGES;
118const COOKIE_KEY_BYTES: usize = 32;
119const COOKIE_KEY_FILE: &str = "phone-cookie-key";
120
121pub const fn default_session_ttl() -> Duration {
126 DEFAULT_SESSION_TTL
127}
128
129pub fn cookie_key_path() -> PathBuf {
130 mj_core::config::data_dir().join(COOKIE_KEY_FILE)
131}
132
133pub fn load_or_create_cookie_key(path: &std::path::Path) -> AnyResult<Vec<u8>> {
143 match std::fs::read(path) {
144 Ok(key) if key.len() >= COOKIE_KEY_BYTES => return Ok(key),
145 Ok(key) => tracing::warn!(
146 path = %path.display(),
147 bytes = key.len(),
148 "phone cookie key is shorter than {COOKIE_KEY_BYTES} bytes; generating a new key signs every phone out"
149 ),
150 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
151 Err(error) => tracing::warn!(
152 path = %path.display(),
153 "could not read the phone cookie key ({error}); generating a new key signs every phone out"
154 ),
155 }
156 let key = generate_cookie_key()?;
157 mj_core::config::atomic_write(path, &key)
158 .with_context(|| format!("persist Mjolnir phone cookie key {}", path.display()))?;
159 Ok(key.to_vec())
160}
161
162#[derive(Clone)]
170pub struct ServerOptions {
171 pub bind: SocketAddr,
172 pub snapshot_rx: watch::Receiver<ViewerSnapshot>,
173 pub conversation_rx: watch::Receiver<BTreeMap<String, BrowserTranscript>>,
174 pub action_tx: mpsc::Sender<ControllerRequest>,
175 pub bundle_tx: mpsc::Sender<BundleRequest>,
176 pub receipt_tx: mpsc::Sender<ReadReceiptRequest>,
177 pub preflight_tx: mpsc::Sender<PreflightRequest>,
178 pub move_preparation_tx: mpsc::Sender<MovePreparationRequest>,
179 pub client_state_tx: mpsc::Sender<ClientStateRequest>,
180 pub dictation_tx: mpsc::Sender<DictationRequest>,
181 background_task_stop_tx: mpsc::Sender<BackgroundTaskStopRequest>,
185 pub shutdown: CancellationToken,
186 pub session_ttl: Duration,
187 pub secure_cookie: bool,
190 tls_config: Option<axum_server::tls_rustls::RustlsConfig>,
191 viewer_code: String,
192 login_token: String,
193 cookie_key: Vec<u8>,
194 viewer_revocations: Arc<ViewerRevocations>,
195 api_token: String,
196 subagent: Option<Arc<dyn api::SubagentBackend>>,
197 preferences_path: PathBuf,
202}
203
204pub struct ServerRequests {
206 pub action_tx: mpsc::Sender<ControllerRequest>,
207 pub bundle_tx: mpsc::Sender<BundleRequest>,
208 pub receipt_tx: mpsc::Sender<ReadReceiptRequest>,
209 pub preflight_tx: mpsc::Sender<PreflightRequest>,
210 pub move_preparation_tx: mpsc::Sender<MovePreparationRequest>,
211 pub client_state_tx: mpsc::Sender<ClientStateRequest>,
212 pub dictation_tx: mpsc::Sender<DictationRequest>,
213}
214
215impl ServerOptions {
216 pub fn new(
217 bind: SocketAddr,
218 snapshot_rx: watch::Receiver<ViewerSnapshot>,
219 conversation_rx: watch::Receiver<BTreeMap<String, BrowserTranscript>>,
220 requests: ServerRequests,
221 ) -> AnyResult<Self> {
222 let cookie_key = generate_cookie_key()?.to_vec();
223 Ok(Self {
224 bind,
225 snapshot_rx,
226 conversation_rx,
227 action_tx: requests.action_tx,
228 bundle_tx: requests.bundle_tx,
229 receipt_tx: requests.receipt_tx,
230 preflight_tx: requests.preflight_tx,
231 move_preparation_tx: requests.move_preparation_tx,
232 client_state_tx: requests.client_state_tx,
233 dictation_tx: requests.dictation_tx,
234 background_task_stop_tx: mpsc::channel(1).0,
235 shutdown: CancellationToken::new(),
236 session_ttl: DEFAULT_SESSION_TTL,
237 secure_cookie: true,
238 tls_config: None,
239 viewer_code: generate_viewer_code()?,
240 login_token: derive_login_token(&cookie_key),
241 cookie_key,
242 viewer_revocations: Arc::new(ViewerRevocations::default()),
243 api_token: String::new(),
246 subagent: None,
247 preferences_path: mj_core::go::GoPreferences::path(),
248 })
249 }
250
251 pub fn viewer_code(&self) -> &str {
252 &self.viewer_code
253 }
254
255 pub fn login_token(&self) -> &str {
256 &self.login_token
257 }
258
259 pub fn set_tls_config(&mut self, config: axum_server::tls_rustls::RustlsConfig) {
263 self.tls_config = Some(config);
264 self.secure_cookie = true;
265 }
266
267 pub fn set_cookie_key(&mut self, key: Vec<u8>) -> AnyResult<()> {
271 anyhow::ensure!(
272 key.len() >= COOKIE_KEY_BYTES,
273 "cookie signing key must be at least {COOKIE_KEY_BYTES} bytes"
274 );
275 self.login_token = derive_login_token(&key);
276 self.cookie_key = key;
277 Ok(())
278 }
279
280 pub async fn load_cookie_credentials(&mut self, path: PathBuf) -> AnyResult<()> {
282 let (key, revocations) = tokio::task::spawn_blocking(move || {
283 let key = load_or_create_cookie_key(&path)?;
284 let revocations =
285 ViewerRevocations::load(path.with_file_name("phone-cookie-revocations.json"))?;
286 Ok::<_, anyhow::Error>((key, revocations))
287 })
288 .await
289 .context("load viewer credentials task")??;
290 self.set_cookie_key(key)?;
291 self.viewer_revocations = Arc::new(revocations);
292 Ok(())
293 }
294
295 pub fn set_background_task_stop_tx(&mut self, tx: mpsc::Sender<BackgroundTaskStopRequest>) {
297 self.background_task_stop_tx = tx;
298 }
299
300 pub fn set_api_token(&mut self, token: String) {
303 self.api_token = token;
304 }
305
306 pub fn set_subagent_backend(&mut self, backend: Arc<dyn api::SubagentBackend>) {
309 self.subagent = Some(backend);
310 }
311
312 pub fn set_preferences_path(&mut self, path: PathBuf) {
315 self.preferences_path = path;
316 }
317
318 #[cfg(test)]
319 fn with_test_credentials(mut self, code: &str, key: &[u8]) -> Self {
320 self.viewer_code = code.to_string();
321 self.login_token = "test-login-token".into();
322 self.cookie_key = key.to_vec();
323 self.secure_cookie = false;
324 self.api_token = "test-api-token".into();
325 self
326 }
327}
328
329pub async fn run_server(options: ServerOptions) -> AnyResult<()> {
335 let listener = tokio::net::TcpListener::bind(options.bind)
336 .await
337 .with_context(|| format!("bind web viewer to {}", options.bind))?;
338 run_server_on_listener(options, listener).await
339}
340
341pub async fn run_server_on_listener(
343 options: ServerOptions,
344 listener: tokio::net::TcpListener,
345) -> AnyResult<()> {
346 let mut options = options;
347 let bind = listener.local_addr().context("read web viewer address")?;
348 let shutdown = options.shutdown.clone();
349 let viewer_code = options.viewer_code.clone();
350 let tls_config = options.tls_config.take();
351 let app = router(options);
352 println!("Mjolnir viewer code: {viewer_code}");
353 let listener = listener.into_std().context("prepare web viewer listener")?;
354 let handle = axum_server::Handle::new();
355 let shutdown_handle = handle.clone();
356 let serve = async move {
357 if let Some(tls_config) = tls_config {
358 axum_server::from_tcp_rustls(listener, tls_config)
359 .handle(handle)
360 .serve(app.into_make_service())
361 .await
362 } else {
363 axum_server::from_tcp(listener)
364 .handle(handle)
365 .serve(app.into_make_service())
366 .await
367 }
368 };
369 tokio::pin!(serve);
370 tokio::select! {
371 result = &mut serve => result,
372 _ = shutdown.cancelled() => {
373 shutdown_handle.graceful_shutdown(Some(Duration::from_secs(2)));
374 serve.await
375 }
376 }
377 .with_context(|| format!("serve web viewer on {bind}"))
378}
379
380mod viewer_types;
381pub use viewer_types::*;
382mod actions;
383pub use actions::*;
384mod routes;
385use routes::*;
386mod handlers;
387use handlers::*;
388mod validation;
389use validation::*;
390mod errors;
391use errors::*;
392mod auth;
393pub use auth::*;
394mod assets;
395use assets::*;
396mod config_view;
397pub use config_view::*;
398
399#[cfg(test)]
400mod tests;