Skip to main content

mj_controller/
server.rs

1//! Daemon-owned, phone-oriented control surface for Hel.
2//!
3//! The server deliberately owns no controller business logic. It publishes a
4//! redacted projection of controller state and forwards validated, typed
5//! actions through a channel supplied by the controller.
6
7use 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
67// Keep all control surfaces on the same queue vocabulary. The resume flow
68// used to define a private copy here, which made a move request impossible to
69// pass through the web and daemon boundaries without lossy conversion.
70pub use mj_core::state::ResumeQueueDisposition;
71
72/// Select the process-wide rustls provider before any TLS configuration is built.
73///
74/// Dependency feature unification can enable both rustls providers. Rustls
75/// deliberately refuses to guess in that case, so each executable that links
76/// the controller installs the ring provider at process startup. A provider
77/// installed even earlier is already sufficient and remains in place.
78pub 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;
91/// How many repositories one dirty-worktree acknowledgement may name. A bundle
92/// with more repositories than this than has bigger problems than the phone.
93const MAX_DIRTY_ACKNOWLEDGEMENTS: usize = 32;
94/// The largest draft a phone may store. A composer is for a prompt, and a
95/// prompt this size has other problems; the bound exists so one viewer cannot
96/// fill the daemon's database with text it never sent.
97const MAX_DRAFT_BYTES: usize = 64 * 1024;
98/// How many prompt-history matches one search returns. Public because the
99/// controller loop performs the search and must use the same bound the phone
100/// was promised.
101pub const MAX_HISTORY_MATCHES: usize = 40;
102/// Image prompts need far more room than any other phone request. Browser
103/// uploads are base64-encoded, so two ordinary photographs already exceed the
104/// general body limit even when each one fits it. The larger bound therefore
105/// stays scoped to the action route that carries prompts.
106const MAX_PROMPT_BODY_BYTES: usize = 32 * 1024 * 1024;
107/// A browser uploads one source image at a time. The image optimizer has its
108/// own decoded-allocation bound; this is the HTTP envelope bound before that
109/// work starts.
110const MAX_ATTACHMENT_UPLOAD_BYTES: usize = 64 * 1024 * 1024;
111/// Keep two browser uploads/transcriptions in flight. The permit is acquired
112/// before reading the request body, so an overloaded client is rejected
113/// without accepting megabytes that cannot be processed yet.
114const MAX_CONCURRENT_DICTATIONS: usize = 2;
115/// Keep this in sync with the prompt admission bound and the browser composer.
116pub const MAX_PROMPT_IMAGES: usize = MAX_IMAGES;
117const COOKIE_KEY_BYTES: usize = 32;
118const COOKIE_KEY_FILE: &str = "phone-cookie-key";
119
120/// How long stored viewer state outlives its last use.
121///
122/// It matches the session cookie's own lifetime: state keyed to an identity
123/// that can no longer authenticate has nothing left to belong to.
124pub 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
132/// Load the phone cookie signing key, creating it on first use.
133///
134/// Session cookies are stateless, so this file is the only thing that keeps a
135/// signed-in phone signed in across daemon restarts. Deleting it is
136/// therefore the explicit sign-everyone-out gesture: the next start writes a
137/// new key and every outstanding cookie stops validating. A missing file is
138/// ordinary first use; an unreadable or too-short one is replaced loudly,
139/// because refusing to start would be a worse answer than asking phones to
140/// enter the viewer code again.
141pub 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/// Options for the daemon's phone service.
162///
163/// `ServerOptions::new` generates both the six-digit viewer code and an
164/// ephemeral cookie key. A caller that wants cookies to survive server
165/// restarts installs a persisted key with `set_cookie_key`, which
166/// `load_or_create_cookie_key` reads from its private Hel data directory. The
167/// key and viewer code are intentionally omitted from `Debug` output.
168#[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    /// Dedicated bounded path for stopping one live background task. This is
181    /// deliberately separate from [`ControllerAction`]: stopping a provider
182    /// task does not occupy the controller's action admission slot.
183    background_task_stop_tx: mpsc::Sender<BackgroundTaskStopRequest>,
184    pub shutdown: CancellationToken,
185    pub session_ttl: Duration,
186    /// Keep this enabled for direct HTTPS or an HTTPS reverse proxy. It may be
187    /// disabled only for an explicitly trusted HTTP development endpoint.
188    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
197/// Typed request channels served by the authenticated HTTP surface.
198pub 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            // An empty token authenticates nothing: the daemon installs the
235            // persisted one, and a server without it serves the viewer only.
236            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    /// Serve HTTPS directly using the supplied Rustls configuration. Hel's
250    /// CLI can load its persisted certificate (including a Tailscale-issued
251    /// certificate) and pass it here without coupling this module to disk.
252    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    /// Install a persisted signing key. Rotating this value signs every phone
258    /// out without maintaining a server-side session database.
259    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    /// Install the controller's bounded background-task stop path.
269    pub fn set_background_task_stop_tx(&mut self, tx: mpsc::Sender<BackgroundTaskStopRequest>) {
270        self.background_task_stop_tx = tx;
271    }
272
273    /// Install the persisted bearer token for the `/api/v1` routes. Rotating
274    /// it revokes every client that still holds the old one.
275    pub fn set_api_token(&mut self, token: String) {
276        self.api_token = token;
277    }
278
279    /// Install the daemon-side backend the `/api/v1` routes drive sessions
280    /// through. Without it those routes answer 503.
281    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
296/// Run the phone server until its shutdown token is cancelled.
297///
298/// This binds only the requested listener. It does not daemonize, provision a
299/// target, or keep sessions alive: controller availability is required, just
300/// like MJ's explicit remote-viewer model.
301pub 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
308/// Serve a reserved socket so readiness and advertised ports reflect a real listener.
309pub 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;