Skip to main content

koan_server/graphql/
server.rs

1use std::path::PathBuf;
2use std::sync::Arc;
3
4use crossbeam_channel::Sender;
5use koan_core::audio::viz::VizSnapshot;
6use koan_core::auth::{self, parse_duration_secs};
7use koan_core::config::Config;
8use koan_core::player::commands::PlayerCommand;
9use koan_core::player::state::SharedPlayerState;
10
11use super::{KoanSchema, build_schema};
12use crate::auth::AuthUser;
13use crate::auth::middleware::{AuthState, auth_middleware};
14use crate::auth::routes::{AuthRouteState, auth_router};
15
16// ---------------------------------------------------------------------------
17// `koan --headless` entry point (standalone headless server)
18// ---------------------------------------------------------------------------
19
20pub fn cmd_serve(
21    port: Option<u16>,
22    bind: Option<std::net::IpAddr>,
23    subsonic_port: Option<u16>,
24    playground: bool,
25) {
26    use koan_core::player::Player;
27
28    // Validate DB is accessible before starting the server.
29    let _db = koan_core::db::connection::Database::open_default().expect("failed to open database");
30    let db_path = koan_core::config::db_path();
31
32    let (state, _timeline, _viz, cmd_tx) = Player::spawn();
33
34    run_api_blocking(ApiServerOpts {
35        state,
36        cmd_tx,
37        db_path,
38        port,
39        bind,
40        subsonic_port,
41        playground,
42        viz: None, // headless — no viz analyzer
43    });
44}
45
46// ---------------------------------------------------------------------------
47// Shared API server logic — used by both headless and TUI+API modes
48// ---------------------------------------------------------------------------
49
50/// Options for the API server — avoids too-many-arguments.
51pub struct ApiServerOpts {
52    pub state: Arc<SharedPlayerState>,
53    pub cmd_tx: Sender<PlayerCommand>,
54    pub db_path: PathBuf,
55    pub port: Option<u16>,
56    pub bind: Option<std::net::IpAddr>,
57    pub subsonic_port: Option<u16>,
58    pub playground: bool,
59    pub viz: Option<Arc<VizSnapshot>>,
60}
61
62/// Run the GraphQL (+ optional Subsonic) API server, blocking the current thread.
63/// Called from `cmd_serve` (headless) and `start_api_background` (TUI companion).
64fn run_api_blocking(opts: ApiServerOpts) {
65    let ApiServerOpts {
66        state,
67        cmd_tx,
68        db_path,
69        port,
70        bind,
71        subsonic_port,
72        playground,
73        viz,
74    } = opts;
75    use axum::routing::{get, post};
76
77    let cfg = Config::load().unwrap_or_default();
78    let port = port.unwrap_or(cfg.graphql.port);
79    let bind = bind.unwrap_or(cfg.graphql.bind);
80    let playground_enabled = playground || cfg.graphql.playground;
81    let auth_enabled = cfg.graphql.auth_enabled;
82
83    // Load or generate Ed25519 keypair for JWT signing.
84    let (private_pem, public_pem) = if auth_enabled {
85        match auth::load_keypair() {
86            Ok(kp) => kp,
87            Err(e) => {
88                panic!(
89                    "Auth enabled but keypair not found: {}. Run `koan auth setup` first. \
90                     Refusing to start with auth_enabled=true and no valid keypair.",
91                    e
92                );
93            }
94        }
95    } else {
96        // When auth is disabled, we still need dummy keys for the route state
97        // (routes exist but won't be hit by middleware). Generate if available.
98        auth::load_or_generate_keypair().unwrap_or_default()
99    };
100
101    let auth_actually_enabled = auth_enabled && !private_pem.is_empty();
102
103    let access_ttl = parse_duration_secs(&cfg.graphql.access_token_ttl).unwrap_or(900);
104    let refresh_ttl = parse_duration_secs(&cfg.graphql.refresh_token_ttl).unwrap_or(2_592_000);
105
106    // Generate a process-scoped introspection key for playground access.
107    let introspection_key = if playground_enabled && auth_actually_enabled {
108        // Use UUID v4 as a random introspection key — 122 bits of randomness, no extra deps.
109        Some(Arc::new(uuid::Uuid::now_v7().to_string()))
110    } else {
111        None
112    };
113
114    let auth_state = AuthState {
115        public_pem: Arc::new(public_pem.clone()),
116        auth_enabled: auth_actually_enabled,
117        introspection_key: introspection_key.clone(),
118    };
119
120    let auth_route_state = AuthRouteState {
121        db_path: db_path.clone(),
122        private_pem: Arc::new(private_pem),
123        public_pem: Arc::new(public_pem),
124        access_ttl_secs: access_ttl,
125        refresh_ttl_secs: refresh_ttl,
126    };
127
128    let schema = build_schema(state, cmd_tx, db_path.clone(), viz);
129
130    if auth_actually_enabled {
131        log::info!(
132            "Auth enabled (Ed25519 JWT, access TTL {}s, refresh TTL {}s)",
133            access_ttl,
134            refresh_ttl
135        );
136    } else {
137        log::info!("Auth disabled — all requests treated as admin");
138    }
139
140    let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
141    rt.block_on(async {
142        // GraphQL routes — protected by auth middleware.
143        let gql_app = axum::Router::new()
144            .route("/graphql", post(graphql_handler))
145            .route("/graphql/ws", get(graphql_ws_handler))
146            .layer(axum::middleware::from_fn_with_state(
147                auth_state.clone(),
148                auth_middleware,
149            ))
150            .layer(tower::limit::ConcurrencyLimitLayer::new(10))
151            .with_state(schema);
152
153        // Auth routes — always accessible (no auth middleware).
154        let auth_app = auth_router(auth_route_state);
155
156        // CORS — allow cross-origin requests for browser clients.
157        // With specific origins we can enable credentials (cookies); with Any we cannot per spec.
158        let cors = if cfg.graphql.cors_origins.is_empty() {
159            // Dev mode: allow all origins (no credentials support with Any).
160            tower_http::cors::CorsLayer::new()
161                .allow_origin(tower_http::cors::Any)
162                .allow_methods([
163                    axum::http::Method::GET,
164                    axum::http::Method::POST,
165                    axum::http::Method::OPTIONS,
166                ])
167                .allow_headers(tower_http::cors::Any)
168        } else {
169            // Production: specific origins with credentials for cookie auth.
170            let origins: Vec<axum::http::HeaderValue> = cfg
171                .graphql
172                .cors_origins
173                .iter()
174                .filter_map(|o| o.parse().ok())
175                .collect();
176            tower_http::cors::CorsLayer::new()
177                .allow_origin(origins)
178                .allow_methods([
179                    axum::http::Method::GET,
180                    axum::http::Method::POST,
181                    axum::http::Method::OPTIONS,
182                ])
183                .allow_headers([
184                    axum::http::header::AUTHORIZATION,
185                    axum::http::header::CONTENT_TYPE,
186                    axum::http::HeaderName::from_static("x-introspection-key"),
187                ])
188                .allow_credentials(true)
189        };
190
191        // Subsonic REST routes — always mounted on the GraphQL port when
192        // remote creds are configured. Previously only available on the
193        // dedicated `--subsonic <port>` listener, which broke `koan play
194        // --server <url>` because the remote TUI bridge builds its stream
195        // URL off the GraphQL base.
196        let subsonic_merged = crate::subsonic::subsonic_router(db_path.clone());
197        let subsonic_on_main = subsonic_merged.is_some();
198
199        let mut app = auth_app.merge(gql_app);
200        if let Some(sub) = subsonic_merged {
201            app = app.merge(sub);
202        }
203        let mut app = app.layer(cors);
204        if playground_enabled {
205            app = app.route(
206                "/graphql",
207                get(graphql_playground).with_state(introspection_key.clone()),
208            );
209        }
210
211        // Build playground URL with introspection key.
212        let playground_url = if playground_enabled {
213            if let Some(ref key) = introspection_key {
214                format!("http://{}:{}/graphql?introspection-key={}", bind, port, key)
215            } else {
216                format!("http://{}:{}/graphql", bind, port)
217            }
218        } else {
219            format!("http://{}:{}/graphql", bind, port)
220        };
221
222        let gql_addr = std::net::SocketAddr::new(bind, port);
223
224        let gql_listener = match tokio::net::TcpListener::bind(gql_addr).await {
225            Ok(l) => {
226                log::info!("GraphQL API on http://{}:{}/graphql", bind, port);
227                if subsonic_on_main {
228                    log::info!("Subsonic REST on http://{}:{}/rest/", bind, port);
229                }
230                if playground_enabled {
231                    log::info!("GraphiQL: {}", playground_url);
232                    // Open browser on macOS/Linux.
233                    #[cfg(target_os = "macos")]
234                    let _ = std::process::Command::new("open").arg(&playground_url).spawn();
235                    #[cfg(target_os = "linux")]
236                    let _ = std::process::Command::new("xdg-open").arg(&playground_url).spawn();
237                }
238                l
239            }
240            Err(e) => {
241                log::warn!(
242                    "API disabled: failed to bind GraphQL port {} — {} (another instance running?)",
243                    port,
244                    e,
245                );
246                return;
247            }
248        };
249        let gql_server =
250            axum::serve(gql_listener, app).with_graceful_shutdown(shutdown_signal());
251
252        // If `--subsonic <port>` is set AND differs from the GraphQL port,
253        // run an additional dedicated listener. This preserves the old
254        // behavior for users who want Subsonic on its own port.
255        let extra_sub_port = subsonic_port.filter(|p| *p != port);
256        if let Some(sub_port) = extra_sub_port
257            && let Some(sub_app) = crate::subsonic::subsonic_router(db_path)
258        {
259            let sub_addr = std::net::SocketAddr::new(bind, sub_port);
260            match tokio::net::TcpListener::bind(sub_addr).await {
261                Ok(sub_listener) => {
262                    log::info!(
263                        "Subsonic REST also on http://{}:{}/rest/ (dedicated port)",
264                        bind,
265                        sub_port,
266                    );
267                    let sub_server = axum::serve(sub_listener, sub_app)
268                        .with_graceful_shutdown(shutdown_signal());
269
270                    tokio::select! {
271                        r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
272                        r = sub_server => { if let Err(e) = r { log::error!("Subsonic server error: {e}"); } },
273                    }
274                    return;
275                }
276                Err(e) => {
277                    log::warn!(
278                        "Dedicated Subsonic port {} unavailable — {}. Mounted on GraphQL port only.",
279                        sub_port,
280                        e,
281                    );
282                }
283            }
284        }
285
286        if let Err(e) = gql_server.await {
287            log::error!("GraphQL server error: {e}");
288        }
289    });
290}
291
292/// Start the API server on the current thread (blocks forever).
293/// Called from a background thread when TUI mode has API enabled.
294///
295/// Accepts positional args for backward compatibility with koan-cli.
296/// Prefer `ApiServerOpts` for new call sites.
297pub fn start_api_background(
298    state: Arc<SharedPlayerState>,
299    cmd_tx: Sender<PlayerCommand>,
300    db_path: PathBuf,
301    port: Option<u16>,
302    bind: Option<std::net::IpAddr>,
303    subsonic_port: Option<u16>,
304    playground: bool,
305) {
306    run_api_blocking(ApiServerOpts {
307        state,
308        cmd_tx,
309        db_path,
310        port,
311        bind,
312        subsonic_port,
313        playground,
314        viz: None,
315    });
316}
317
318async fn shutdown_signal() {
319    tokio::signal::ctrl_c()
320        .await
321        .expect("failed to listen for ctrl+c");
322}
323
324async fn graphql_handler(
325    axum::Extension(user): axum::Extension<AuthUser>,
326    axum::extract::State(schema): axum::extract::State<KoanSchema>,
327    req: async_graphql_axum::GraphQLRequest,
328) -> async_graphql_axum::GraphQLResponse {
329    let mut request = req.into_inner();
330    // The auth middleware always injects AuthUser (anonymous_admin when auth is
331    // disabled, or a real user when auth is enabled). No fallback needed here.
332    request = request.data(user);
333    schema.execute(request).await.into()
334}
335
336async fn graphql_ws_handler(
337    axum::Extension(user): axum::Extension<AuthUser>,
338    axum::extract::State(schema): axum::extract::State<KoanSchema>,
339    protocol: async_graphql_axum::GraphQLProtocol,
340    websocket: axum::extract::WebSocketUpgrade,
341) -> axum::response::Response {
342    websocket
343        .protocols(async_graphql::http::ALL_WEBSOCKET_PROTOCOLS)
344        .on_upgrade(move |stream| {
345            let stream = async_graphql_axum::GraphQLWebSocket::new(stream, schema, protocol)
346                .on_connection_init(move |_| async move {
347                    let mut data = async_graphql::Data::default();
348                    data.insert(user);
349                    Ok(data)
350                });
351            async move {
352                stream.serve().await;
353            }
354        })
355}
356
357async fn graphql_playground(
358    axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
359    axum::extract::State(key): axum::extract::State<Option<Arc<String>>>,
360) -> axum::response::Response {
361    use axum::response::IntoResponse;
362
363    // If an introspection key exists, require it in the URL.
364    if let Some(ref expected) = key {
365        let provided = params.get("introspection-key");
366        if provided.map(|k| k.as_str()) != Some(expected.as_str()) {
367            return (
368                axum::http::StatusCode::FORBIDDEN,
369                "invalid or missing introspection-key",
370            )
371                .into_response();
372        }
373    }
374
375    // Use async-graphql's built-in GraphiQL (self-contained, no CDN).
376    // Inject the introspection key as a default header so all queries are authed.
377    let mut source = async_graphql::http::GraphiQLSource::build().endpoint("/graphql");
378    if let Some(ref k) = key {
379        source = source.header("X-Introspection-Key", k.as_str());
380    }
381
382    axum::response::Html(source.finish()).into_response()
383}
384
385/// Run the server as a background daemon (fork + detach).
386pub fn cmd_serve_daemon(
387    port: Option<u16>,
388    bind: Option<std::net::IpAddr>,
389    subsonic_port: Option<u16>,
390    playground: bool,
391) {
392    use std::fs;
393    use std::process::Command;
394
395    let cfg = Config::load().unwrap_or_default();
396    let port_val = port.unwrap_or(cfg.graphql.port);
397    let bind_val = bind.unwrap_or(cfg.graphql.bind);
398
399    let exe = std::env::current_exe().expect("failed to get current exe path");
400    let mut cmd = Command::new(exe);
401    // Use the new unified CLI: `koan --headless --port <port>`
402    cmd.arg("--headless");
403    cmd.arg("--port").arg(port_val.to_string());
404    cmd.arg("--bind").arg(bind_val.to_string());
405    if let Some(sp) = subsonic_port {
406        cmd.arg("--subsonic").arg(sp.to_string());
407    }
408    if playground || cfg.graphql.playground {
409        cmd.arg("--playground");
410    }
411
412    cmd.stdin(std::process::Stdio::null());
413    cmd.stdout(std::process::Stdio::null());
414    cmd.stderr(std::process::Stdio::null());
415
416    let mut child = cmd.spawn().expect("failed to spawn daemon process");
417    let pid = child.id();
418
419    let pid_path = koan_core::config::config_dir().join("koan-serve.pid");
420    fs::write(&pid_path, pid.to_string()).ok();
421
422    std::thread::spawn(move || {
423        let _ = child.wait();
424    });
425
426    eprintln!("koan daemon started (pid {}) on port {}", pid, port_val);
427    if let Some(sp) = subsonic_port {
428        eprintln!("  Subsonic REST on port {}", sp);
429    }
430    eprintln!("  PID file: {}", pid_path.display());
431}
432
433// ---------------------------------------------------------------------------
434// In-process execution (for MCP `graphql` tool)
435// ---------------------------------------------------------------------------
436
437/// Execute a GraphQL query in-process (no HTTP round-trip).
438/// In-process requests bypass auth — they're trusted (e.g., MCP tools).
439pub async fn execute_in_process(
440    schema: &KoanSchema,
441    query: &str,
442    variables: Option<serde_json::Value>,
443) -> serde_json::Value {
444    let mut request = async_graphql::Request::new(query);
445    // In-process = admin access (MCP/local tools).
446    request = request.data(AuthUser::anonymous_admin());
447    if let Some(serde_json::Value::Object(map)) = variables {
448        let mut gql_vars = async_graphql::Variables::default();
449        for (k, v) in map {
450            gql_vars.insert(
451                async_graphql::Name::new(&k),
452                async_graphql::Value::from_json(v).unwrap_or(async_graphql::Value::Null),
453            );
454        }
455        request = request.variables(gql_vars);
456    }
457    let response = schema.execute(request).await;
458    serde_json::to_value(&response).unwrap_or(serde_json::Value::Null)
459}