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::refusal::{Refusal, RefusalKind};
40use mj_core::state::{
41 MoveOperation, MovePhase, MovePreparation, MoveSelection, MoveSessionRequest,
42 ProjectSourceIdentity, SessionResourceAllocation, SessionState, SessionTransitionKind,
43 State as AppState,
44};
45
46use crate::targets::AdditionalMount;
47
48use crate::dictation::{
49 DictationError, DictationOperation, DictationRequest, DictationResponse, MAX_AUDIO_BYTES,
50 validate_wav,
51};
52use crate::image::optimize_image;
53
54pub mod api;
55
56pub use api::{
57 ApiFailure, ApiSession, PromptRequest, PromptResponse, SessionListResponse,
58 StartSessionRequest, StartSessionResponse, SubagentBackend, WaitOutcome, WaitRequest,
59 WaitResponse, api_token_path, load_or_create_api_token, map_stop_reason, resolve_wait,
60};
61
62pub use mj_client::web::{
63 BrowserDiffStat, BrowserTranscript, BrowserTranscriptEntry, WebListenerProcess,
64 WebViewerAccess, WebViewerRecovery,
65};
66
67pub use mj_core::state::ResumeQueueDisposition;
71
72pub fn install_rustls_crypto_provider() {
79 let _ = rustls::crypto::ring::default_provider().install_default();
80}
81
82pub const COOKIE_NAME: &str = "hel_viewer_session";
83const DEFAULT_SESSION_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);
84const EPHEMERAL_SESSION_TTL: Duration = Duration::from_secs(24 * 60 * 60);
85const MAX_BODY_BYTES: usize = 128 * 1024;
86const MAX_CODE_FAILURES: u32 = 5;
87const CODE_LOCKOUT_BASE: Duration = Duration::from_secs(30);
88const CODE_LOCKOUT_CAP: Duration = Duration::from_secs(60 * 60);
89const MAX_TITLE_CHARS: usize = 120;
90const MAX_PROMPT_CHARS: usize = 64 * 1024;
91const MAX_DIRTY_ACKNOWLEDGEMENTS: usize = 32;
94const MAX_DRAFT_BYTES: usize = 64 * 1024;
98pub const MAX_HISTORY_MATCHES: usize = 40;
102const MAX_PROMPT_BODY_BYTES: usize = 32 * 1024 * 1024;
107const MAX_ATTACHMENT_UPLOAD_BYTES: usize = 64 * 1024 * 1024;
111const MAX_CONCURRENT_DICTATIONS: usize = 2;
115pub const MAX_PROMPT_IMAGES: usize = MAX_IMAGES;
117const COOKIE_KEY_BYTES: usize = 32;
118const COOKIE_KEY_FILE: &str = "phone-cookie-key";
119
120pub const fn default_session_ttl() -> Duration {
125 DEFAULT_SESSION_TTL
126}
127
128pub fn cookie_key_path() -> PathBuf {
129 mj_core::config::data_dir().join(COOKIE_KEY_FILE)
130}
131
132pub fn load_or_create_cookie_key(path: &std::path::Path) -> AnyResult<Vec<u8>> {
142 match std::fs::read(path) {
143 Ok(key) if key.len() >= COOKIE_KEY_BYTES => return Ok(key),
144 Ok(key) => tracing::warn!(
145 path = %path.display(),
146 bytes = key.len(),
147 "phone cookie key is shorter than {COOKIE_KEY_BYTES} bytes; generating a new key signs every phone out"
148 ),
149 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
150 Err(error) => tracing::warn!(
151 path = %path.display(),
152 "could not read the phone cookie key ({error}); generating a new key signs every phone out"
153 ),
154 }
155 let key = generate_cookie_key()?;
156 mj_core::config::atomic_write(path, &key)
157 .with_context(|| format!("persist Mjolnir phone cookie key {}", path.display()))?;
158 Ok(key.to_vec())
159}
160
161#[derive(Clone)]
169pub struct ServerOptions {
170 pub bind: SocketAddr,
171 pub snapshot_rx: watch::Receiver<ViewerSnapshot>,
172 pub conversation_rx: watch::Receiver<BTreeMap<String, BrowserTranscript>>,
173 pub action_tx: mpsc::Sender<ControllerRequest>,
174 pub bundle_tx: mpsc::Sender<BundleRequest>,
175 pub receipt_tx: mpsc::Sender<ReadReceiptRequest>,
176 pub preflight_tx: mpsc::Sender<PreflightRequest>,
177 pub move_preparation_tx: mpsc::Sender<MovePreparationRequest>,
178 pub client_state_tx: mpsc::Sender<ClientStateRequest>,
179 pub dictation_tx: mpsc::Sender<DictationRequest>,
180 background_task_stop_tx: mpsc::Sender<BackgroundTaskStopRequest>,
184 pub shutdown: CancellationToken,
185 pub session_ttl: Duration,
186 pub secure_cookie: bool,
189 tls_config: Option<axum_server::tls_rustls::RustlsConfig>,
190 viewer_code: String,
191 login_token: String,
192 cookie_key: Vec<u8>,
193 api_token: String,
194 subagent: Option<Arc<dyn api::SubagentBackend>>,
195}
196
197pub struct ServerRequests {
199 pub action_tx: mpsc::Sender<ControllerRequest>,
200 pub bundle_tx: mpsc::Sender<BundleRequest>,
201 pub receipt_tx: mpsc::Sender<ReadReceiptRequest>,
202 pub preflight_tx: mpsc::Sender<PreflightRequest>,
203 pub move_preparation_tx: mpsc::Sender<MovePreparationRequest>,
204 pub client_state_tx: mpsc::Sender<ClientStateRequest>,
205 pub dictation_tx: mpsc::Sender<DictationRequest>,
206}
207
208impl ServerOptions {
209 pub fn new(
210 bind: SocketAddr,
211 snapshot_rx: watch::Receiver<ViewerSnapshot>,
212 conversation_rx: watch::Receiver<BTreeMap<String, BrowserTranscript>>,
213 requests: ServerRequests,
214 ) -> AnyResult<Self> {
215 Ok(Self {
216 bind,
217 snapshot_rx,
218 conversation_rx,
219 action_tx: requests.action_tx,
220 bundle_tx: requests.bundle_tx,
221 receipt_tx: requests.receipt_tx,
222 preflight_tx: requests.preflight_tx,
223 move_preparation_tx: requests.move_preparation_tx,
224 client_state_tx: requests.client_state_tx,
225 dictation_tx: requests.dictation_tx,
226 background_task_stop_tx: mpsc::channel(1).0,
227 shutdown: CancellationToken::new(),
228 session_ttl: DEFAULT_SESSION_TTL,
229 secure_cookie: true,
230 tls_config: None,
231 viewer_code: generate_viewer_code()?,
232 login_token: generate_login_token()?,
233 cookie_key: generate_cookie_key()?.to_vec(),
234 api_token: String::new(),
237 subagent: None,
238 })
239 }
240
241 pub fn viewer_code(&self) -> &str {
242 &self.viewer_code
243 }
244
245 pub fn login_token(&self) -> &str {
246 &self.login_token
247 }
248
249 pub fn set_tls_config(&mut self, config: axum_server::tls_rustls::RustlsConfig) {
253 self.tls_config = Some(config);
254 self.secure_cookie = true;
255 }
256
257 pub fn set_cookie_key(&mut self, key: Vec<u8>) -> AnyResult<()> {
260 anyhow::ensure!(
261 key.len() >= COOKIE_KEY_BYTES,
262 "cookie signing key must be at least {COOKIE_KEY_BYTES} bytes"
263 );
264 self.cookie_key = key;
265 Ok(())
266 }
267
268 pub fn set_background_task_stop_tx(&mut self, tx: mpsc::Sender<BackgroundTaskStopRequest>) {
270 self.background_task_stop_tx = tx;
271 }
272
273 pub fn set_api_token(&mut self, token: String) {
276 self.api_token = token;
277 }
278
279 pub fn set_subagent_backend(&mut self, backend: Arc<dyn api::SubagentBackend>) {
282 self.subagent = Some(backend);
283 }
284
285 #[cfg(test)]
286 fn with_test_credentials(mut self, code: &str, key: &[u8]) -> Self {
287 self.viewer_code = code.to_string();
288 self.login_token = "test-login-token".into();
289 self.cookie_key = key.to_vec();
290 self.secure_cookie = false;
291 self.api_token = "test-api-token".into();
292 self
293 }
294}
295
296pub async fn run_server(options: ServerOptions) -> AnyResult<()> {
302 let listener = tokio::net::TcpListener::bind(options.bind)
303 .await
304 .with_context(|| format!("bind web viewer to {}", options.bind))?;
305 run_server_on_listener(options, listener).await
306}
307
308pub async fn run_server_on_listener(
310 options: ServerOptions,
311 listener: tokio::net::TcpListener,
312) -> AnyResult<()> {
313 let mut options = options;
314 let bind = listener.local_addr().context("read web viewer address")?;
315 let shutdown = options.shutdown.clone();
316 let viewer_code = options.viewer_code.clone();
317 let tls_config = options.tls_config.take();
318 let app = router(options);
319 println!("Mjolnir viewer code: {viewer_code}");
320 let listener = listener.into_std().context("prepare web viewer listener")?;
321 let handle = axum_server::Handle::new();
322 let shutdown_handle = handle.clone();
323 let serve = async move {
324 if let Some(tls_config) = tls_config {
325 axum_server::from_tcp_rustls(listener, tls_config)
326 .handle(handle)
327 .serve(app.into_make_service())
328 .await
329 } else {
330 axum_server::from_tcp(listener)
331 .handle(handle)
332 .serve(app.into_make_service())
333 .await
334 }
335 };
336 tokio::pin!(serve);
337 tokio::select! {
338 result = &mut serve => result,
339 _ = shutdown.cancelled() => {
340 shutdown_handle.graceful_shutdown(Some(Duration::from_secs(2)));
341 serve.await
342 }
343 }
344 .with_context(|| format!("serve web viewer on {bind}"))
345}
346
347mod viewer_types;
348pub use viewer_types::*;
349mod actions;
350pub use actions::*;
351mod routes;
352use routes::*;
353mod handlers;
354use handlers::*;
355mod validation;
356use validation::*;
357mod errors;
358use errors::*;
359mod auth;
360pub use auth::*;
361mod assets;
362use assets::*;
363mod config_view;
364pub use config_view::*;
365
366#[cfg(test)]
367mod tests;