Skip to main content

qualia_core_db/services/
webizen_server.rs

1use axum::{
2    body::{Body, Bytes},
3    extract::{ws::Message, Query, State, WebSocketUpgrade},
4    http::{header, HeaderMap, HeaderName, HeaderValue, Method, StatusCode},
5    response::{IntoResponse, Response},
6    routing::{get, post},
7    Json, Router,
8};
9use futures_util::StreamExt;
10use serde::{Deserialize, Serialize};
11use serde_json::json;
12use std::net::SocketAddr;
13use std::sync::{Arc, Mutex};
14use tokio::sync::broadcast;
15use tokio_stream::wrappers::UnboundedReceiverStream;
16use tower_http::{cors::CorsLayer, services::ServeDir, set_header::SetResponseHeaderLayer};
17
18use crate::{
19    daemon_query::{self, QueryExecError},
20    q_hash,
21    wal::append_mutation,
22    NQuin,
23};
24
25const OFFICIAL_WEB_HUB_ORIGINS: &[&str] = &[
26    "https://webizen.au",
27    "https://www.webizen.au",
28    "https://mediaprophet.github.io",
29];
30const QUERY_PAYLOAD_LIMIT_BYTES: u64 = 64 * 1024;
31const PROXY_FETCH_MAX_BYTES: usize = 64 * 1024 * 1024;
32
33/// Block loopback / RFC1918 targets for the browser CORS relay (`GET /proxy/fetch`).
34fn proxy_target_allowed(url: &reqwest::Url) -> bool {
35    match url.scheme() {
36        "http" | "https" => {}
37        _ => return false,
38    }
39
40    let host = match url.host_str() {
41        Some(h) => h.to_ascii_lowercase(),
42        None => return false,
43    };
44
45    if host == "localhost" || host.ends_with(".localhost") || host == "127.0.0.1" {
46        return false;
47    }
48    if host.starts_with("127.") || host == "::1" || host == "[::1]" {
49        return false;
50    }
51    if host.starts_with("10.")
52        || host.starts_with("192.168.")
53        || host.starts_with("169.254.")
54        || host.starts_with("fe80:")
55    {
56        return false;
57    }
58    if let Some(stripped) = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
59        if let Ok(ip) = stripped.parse::<std::net::IpAddr>() {
60            return !ip_is_restricted(ip);
61        }
62    }
63    if let Ok(ip) = host.parse::<std::net::IpAddr>() {
64        return !ip_is_restricted(ip);
65    }
66
67    true
68}
69
70/// `true` for loopback, private, or link-local addresses — used to
71/// block SSRF against internal networks from the proxy endpoint.
72fn ip_is_restricted(ip: std::net::IpAddr) -> bool {
73    match ip {
74        std::net::IpAddr::V4(v4) => v4.is_loopback() || v4.is_private() || v4.is_link_local(),
75        std::net::IpAddr::V6(v6) => {
76            v6.is_loopback() || v6.is_unicast_link_local() || v6.is_unique_local()
77        }
78    }
79}
80
81/// Shared state for the Webizen loopback server
82#[derive(Clone)]
83pub struct WebizenState {
84    pub telemetry_tx: broadcast::Sender<Vec<u8>>,
85    pub type_index: Arc<[(u64, u64)]>,
86    pub dev: bool,
87    pub token: Option<String>,
88    pub vault: Arc<Mutex<crate::key_vault::KeyVault>>,
89    pub storage_path: String,
90    pub port: u16,
91    pub in_sanctuary_mode: Arc<std::sync::atomic::AtomicBool>,
92}
93
94#[derive(Deserialize)]
95struct NativeQueryRequest {
96    query: String,
97    format: Option<String>,
98}
99
100enum OutputFormat {
101    JsonLd,
102    NTriples,
103    RawQ42,
104}
105
106const SUPPORTED_QUERY_FORMATS: &str =
107    "application/ld+json, application/n-triples, application/x-qualia-q42";
108
109/// 406 response listing the supported query output formats.
110fn not_acceptable_format_response() -> (StatusCode, Json<serde_json::Value>) {
111    (
112        StatusCode::NOT_ACCEPTABLE,
113        Json(json!({
114            "code": "not_acceptable",
115            "status": "error",
116            "message": format!("Supported formats: {SUPPORTED_QUERY_FORMATS}")
117        })),
118    )
119}
120
121/// Content negotiation: explicit `format` field wins, else the
122/// `Accept` header, else JSON-LD default. `Err(())` on unsupported.
123fn negotiate_format(
124    payload_format: Option<&str>,
125    accept: Option<&str>,
126) -> Result<OutputFormat, ()> {
127    if let Some(fmt) = payload_format {
128        return match fmt {
129            "json-ld" | "application/ld+json" => Ok(OutputFormat::JsonLd),
130            "n-triples" | "application/n-triples" => Ok(OutputFormat::NTriples),
131            "q42" | "application/x-qualia-q42" => Ok(OutputFormat::RawQ42),
132            _ => Err(()),
133        };
134    }
135    if let Some(accept) = accept {
136        if accept.contains("application/x-qualia-q42") {
137            return Ok(OutputFormat::RawQ42);
138        }
139        if accept.contains("application/n-triples") {
140            return Ok(OutputFormat::NTriples);
141        }
142        if accept.contains("application/ld+json")
143            || accept.contains("application/json")
144            || accept.contains("*/*")
145        {
146            return Ok(OutputFormat::JsonLd);
147        }
148        return Err(());
149    }
150    Ok(OutputFormat::JsonLd)
151}
152
153/// Map a `QueryExecError` to its WebSocket error envelope with the
154/// client-supplied query `id`.
155fn ws_query_error_json(id: u64, err: QueryExecError) -> serde_json::Value {
156    match err {
157        QueryExecError::EmptyQuery => json!({ "type": "error", "id": id, "code": "empty_query" }),
158        QueryExecError::ParseError(msg) => {
159            json!({ "type": "error", "id": id, "code": "parse_error", "message": msg })
160        }
161        QueryExecError::OutputBufferFull => {
162            json!({ "type": "error", "id": id, "code": "result_set_too_large" })
163        }
164        QueryExecError::InvalidProgram => json!({ "type": "error", "id": id, "code": "vm_error" }),
165        QueryExecError::ClassifiedEgress => {
166            json!({ "type": "error", "id": id, "code": "restricted_data_access" })
167        }
168    }
169}
170
171/// Whitespace-tolerant base64 decode for bench-load payloads
172/// (dependency-free; rejects non-alphabet characters).
173fn decode_bench_load_b64(b64: &str) -> Result<Vec<u8>, &'static str> {
174    let cleaned: String = b64.chars().filter(|c| !c.is_whitespace()).collect();
175    let padded = match cleaned.len() % 4 {
176        0 => cleaned,
177        n => format!("{cleaned}{}", "=".repeat(4 - n)),
178    };
179    let mut out = Vec::with_capacity(padded.len() * 3 / 4);
180    let table = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
181    let mut buf = 0u32;
182    let mut bits = 0u32;
183    for ch in padded.bytes() {
184        if ch == b'=' {
185            break;
186        }
187        let val = table
188            .iter()
189            .position(|&t| t == ch)
190            .ok_or("invalid base64")? as u32;
191        buf = (buf << 6) | val;
192        bits += 6;
193        if bits >= 8 {
194            bits -= 8;
195            out.push((buf >> bits) as u8);
196            buf &= (1u32 << bits) - 1;
197        }
198    }
199    Ok(out)
200}
201
202/// Build `WebizenState` from `qualia_global.wal` (type index scan),
203/// then spawn the axum server on a dedicated thread pinned to core 3
204/// with a current-thread tokio runtime. Returns the shared state.
205pub fn spawn_loopback_server(
206    port: u16,
207    dev: bool,
208    vault: Arc<Mutex<crate::key_vault::KeyVault>>,
209    token: Option<String>,
210) -> Arc<WebizenState> {
211    let mut flat_index = Vec::new();
212    let index_predicate = q_hash("q42:TypeIndex");
213    if let Ok(mut file) = std::fs::File::open("qualia_global.wal") {
214        use std::io::Read;
215        let mut buf = [0u8; 48];
216        while file.read_exact(&mut buf).is_ok() {
217            let quin: NQuin = bytemuck::cast(buf);
218            if quin.predicate == index_predicate {
219                flat_index.push((quin.subject, quin.object));
220            }
221        }
222    }
223    flat_index.sort_unstable_by_key(|&(k, _)| k);
224
225    let (telemetry_tx, _) = broadcast::channel(100);
226
227    let storage_path = std::env::var("QUALIA_STORAGE_PATH").unwrap_or_else(|_| {
228        std::env::var("HOME")
229            .or_else(|_| std::env::var("USERPROFILE"))
230            .map(|h| format!("{h}/.qualia"))
231            .unwrap_or_else(|_| ".qualia".to_string())
232    });
233    crate::services::poet_record_api::configure(
234        std::path::PathBuf::from(&storage_path).join("poet-cop-records.json"),
235    );
236
237    let state = Arc::new(WebizenState {
238        telemetry_tx: telemetry_tx.clone(),
239        type_index: flat_index.into(),
240        dev,
241        token: token.or_else(|| {
242            std::env::var("QUALIA_TOKEN")
243                .ok()
244                .or_else(|| std::env::var("QUALIA_DEV_TOKEN").ok())
245        }),
246        vault: vault.clone(),
247        storage_path: storage_path.clone(),
248        port,
249        in_sanctuary_mode: Arc::new(std::sync::atomic::AtomicBool::new(false)),
250    });
251
252    let server_state = state.clone();
253
254    std::thread::Builder::new()
255        .name("Webizen-Axum-Core3".into())
256        .spawn(move || {
257            if let Some(core_ids) = core_affinity::get_core_ids() {
258                if let Some(core3) = core_ids.get(3).or(core_ids.last()) {
259                    core_affinity::set_for_current(*core3);
260                }
261            }
262
263            let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
264
265            rt.block_on(async move {
266                let mut allowed_origins: Vec<HeaderValue> = OFFICIAL_WEB_HUB_ORIGINS
267                    .iter()
268                    .map(|o| o.parse().unwrap())
269                    .collect();
270                if server_state.dev {
271                    allowed_origins.extend([
272                        "http://localhost:8080".parse().unwrap(),
273                        "http://127.0.0.1:8080".parse().unwrap(),
274                        "http://localhost:8788".parse().unwrap(),
275                        "http://127.0.0.1:8788".parse().unwrap(),
276                        "http://localhost:5173".parse().unwrap(),
277                        "http://127.0.0.1:5173".parse().unwrap(),
278                        "http://localhost:4173".parse().unwrap(),
279                        "http://127.0.0.1:4173".parse().unwrap(),
280                    ]);
281                }
282
283                let cors = if server_state.dev {
284                    CorsLayer::permissive()
285                } else {
286                    CorsLayer::new()
287                        .allow_origin(allowed_origins)
288                        .allow_methods(vec![Method::GET, Method::POST, Method::OPTIONS])
289                        .allow_headers(vec![
290                            header::CONTENT_TYPE,
291                            header::ACCEPT,
292                            HeaderName::from_static("x-qualia-token"),
293                            HeaderName::from_static("x-qualia-standpoint-class"),
294                            HeaderName::from_static("x-qualia-t-slice"),
295                            HeaderName::from_static("x-qualia-t-window"),
296                            HeaderName::from_static("x-qualia-session-nonce"),
297                            HeaderName::from_static("x-qualia-identifier-did"),
298                            HeaderName::from_static("x-qualia-signature"),
299                            HeaderName::from_static("x-qualia-lane"),
300                            HeaderName::from_static("access-control-request-private-network"),
301                        ])
302                        .expose_headers(vec![
303                            HeaderName::from_static("x-qualia-compute-cost"),
304                            HeaderName::from_static("x-qualia-tensor-nodes"),
305                            HeaderName::from_static("x-qualia-tensor-bytes"),
306                        ])
307                };
308
309                let csp_layer = SetResponseHeaderLayer::overriding(
310                    header::CONTENT_SECURITY_POLICY,
311                    HeaderValue::from_static(
312                        "default-src 'self'; connect-src 'self' ws://127.0.0.1:4242; script-src 'self' 'wasm-unsafe-eval'; style-src 'self';"
313                    )
314                );
315
316                let ui_static_dir = std::env::var("QUALIA_UI_DIR").unwrap_or_else(|_| "crates/webizen-studio/dist".to_string());
317
318                let app = Router::new()
319                    // UI & Static
320                    .fallback_service(ServeDir::new(ui_static_dir).precompressed_gzip())
321
322                    // WebSockets
323                    .route("/qualia-bridge", get(bridge_handler))
324                    .route("/telemetry", get(telemetry_handler))
325                    // External WASM telemetry ingestion — external devices
326                    // (phones, browser tabs, other machines) POST their
327                    // SystemTelemetry here for local processing.
328                    .route("/telemetry/ingest", post(telemetry_ingest_handler).options(preflight_handler))
329
330                    // REST
331                    .route("/health", get(health_handler).options(preflight_handler))
332                    .route("/vibe/capabilities", get(vibe_capabilities_handler).options(preflight_handler))
333                    .route(
334                        "/tensor/slice",
335                        get(tensor_slice_handler).options(preflight_handler),
336                    )
337                    .route(
338                        "/tensor/events",
339                        get(tensor_events_handler).options(preflight_handler),
340                    )
341                    .route(
342                        "/pulse/events",
343                        get(pulse_events_handler).options(preflight_handler),
344                    )
345                    .route(
346                        "/tensor/dev-signing-key",
347                        get(tensor_dev_signing_key_handler).options(preflight_handler),
348                    )
349                    .route("/query", post(query_handler).options(preflight_handler))
350                    .route("/update", post(update_handler).options(preflight_handler))
351                    .route(
352                        "/eval",
353                        post(crate::services::poet_api::eval_handler).options(preflight_handler),
354                    )
355                    .route(
356                        "/invoke",
357                        post(crate::services::poet_api::invoke_handler).options(preflight_handler),
358                    )
359                    .route(
360                        "/gazetteer",
361                        post(crate::services::poet_api::gazetteer_handler)
362                            .options(preflight_handler),
363                    )
364                    .route(
365                        "/intent",
366                        post(crate::services::poet_api::intent_handler).options(preflight_handler),
367                    )
368                    .route(
369                        "/render/preview",
370                        post(crate::services::poet_render_api::render_preview_handler)
371                            .options(preflight_handler),
372                    )
373                    .route(
374                        "/library/stats",
375                        get(crate::services::poet_library_api::stats_handler)
376                            .options(preflight_handler),
377                    )
378                    .route(
379                        "/library/query",
380                        post(crate::services::poet_library_api::query_handler)
381                            .options(preflight_handler),
382                    )
383                    .route(
384                        "/library/ingest",
385                        post(crate::services::poet_library_api::ingest_handler)
386                            .options(preflight_handler),
387                    )
388                    .route(
389                        "/llm/models",
390                        get(crate::services::poet_llm_api::models_handler)
391                            .options(preflight_handler),
392                    )
393                    .route(
394                        "/llm/models/activate",
395                        post(crate::services::poet_llm_api::activate_model_handler)
396                            .options(preflight_handler),
397                    )
398                    .route(
399                        "/llm/models/evict",
400                        post(crate::services::poet_llm_api::evict_model_handler)
401                            .options(preflight_handler),
402                    )
403                    .route(
404                        "/llm/generate",
405                        post(crate::services::poet_llm_api::generate_handler)
406                            .options(preflight_handler),
407                    )
408                    .route(
409                        "/llm/jobs/start",
410                        post(crate::services::poet_llm_jobs::start_handler)
411                            .options(preflight_handler),
412                    )
413                    .route(
414                        "/llm/jobs/events",
415                        get(crate::services::poet_llm_jobs::events_handler)
416                            .options(preflight_handler),
417                    )
418                    .route(
419                        "/llm/jobs/cancel",
420                        post(crate::services::poet_llm_jobs::cancel_handler)
421                            .options(preflight_handler),
422                    )
423                    .route(
424                        "/records/query",
425                        post(crate::services::poet_record_api::query_handler)
426                            .options(preflight_handler),
427                    )
428                    .route(
429                        "/records/upsert",
430                        post(crate::services::poet_record_api::upsert_handler)
431                            .options(preflight_handler),
432                    )
433                    .route(
434                        "/records/delete",
435                        post(crate::services::poet_record_api::delete_handler)
436                            .options(preflight_handler),
437                    )
438                    .route("/cache", post(cache_handler))
439                    .route("/proxy/fetch", get(proxy_fetch_handler).options(preflight_handler))
440                    .route("/api/v1/system/storage/selfhood", get(storage_selfhood_handler))
441                    .route("/api/v1/system/storage/commons", get(storage_commons_handler))
442                    .route("/api/v1/permissions/compile", post(permissions_compile_handler))
443                    .route("/api/v1/webizen/rpc", post(webizen_rpc_handler))
444
445                    // Manifest
446                    .route("/manifest", post(manifest_handler))
447                    .route("/manifest/current", get(current_manifest_handler))
448
449                    // Extensions
450                    .route("/extensions/list", get(list_extensions_handler))
451                    .route("/extensions/query/{interface}", get(query_extensions_handler))
452                    .route("/extensions/register", post(register_extension_handler))
453
454                    // Mobile
455                    .route("/mobile/qr", get(mobile_qr_handler))
456                    .route("/mobile/stream", get(mobile_ws_handler))
457                    .route("/generate_pane", post(mobile_generate_pane_handler))
458                    .nest_service("/mobile/app", tower_http::services::ServeDir::new("bootstrap_gateway/mobile"))
459
460                    // External Routers
461                    .with_state(server_state.clone())
462                    .merge(crate::chat_relay_daemon::chat_relay_routes(server_state.storage_path.clone(), server_state.vault.clone()))
463                    .nest("/torrent", crate::webtorrent_routes::webtorrent_routes(server_state.port))
464                    .layer(csp_layer)
465                    .layer(cors)
466                    .layer(axum::middleware::from_fn(pna_middleware));
467
468                let addr = SocketAddr::from(([0, 0, 0, 0], server_state.port));
469                let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
470                axum::serve(listener, app).await.unwrap();
471            });
472        })
473        .expect("Failed to spawn Webizen server thread");
474
475    state
476}
477
478/// Private Network Access middleware — answers CORS preflights and
479/// adds `Access-Control-Allow-Private-Network` headers.
480async fn pna_middleware(req: axum::extract::Request, next: axum::middleware::Next) -> Response {
481    let mut res = next.run(req).await;
482    res.headers_mut().insert(
483        HeaderName::from_static("access-control-allow-private-network"),
484        HeaderValue::from_static("true"),
485    );
486    res
487}
488
489/// OPTIONS preflight responder — permissive CORS headers.
490async fn preflight_handler() -> impl IntoResponse {
491    (StatusCode::OK, Json(json!({ "status": "ok" })))
492}
493
494#[derive(Deserialize)]
495struct TensorSliceQuery {
496    max_nodes: Option<u32>,
497    t_slice: Option<f32>,
498    t_window: Option<f32>,
499    lane: Option<String>,
500}
501
502/// Parse a header value as `f32`; `None` when absent or malformed.
503fn header_parse_f32(headers: &HeaderMap, name: &str) -> Option<f32> {
504    headers
505        .get(name)
506        .and_then(|v| v.to_str().ok())
507        .and_then(|s| s.parse().ok())
508}
509
510/// Parse a header value as `u32`; `None` when absent or malformed.
511fn header_parse_u32(headers: &HeaderMap, name: &str) -> Option<u32> {
512    headers
513        .get(name)
514        .and_then(|v| v.to_str().ok())
515        .and_then(|s| s.parse().ok())
516}
517
518/// Header value as an owned `String`; `None` when absent or
519/// non-UTF-8.
520fn header_str(headers: &HeaderMap, name: &str) -> Option<String> {
521    headers
522        .get(name)
523        .and_then(|v| v.to_str().ok())
524        .map(|s| s.to_string())
525}
526
527/// `GET /tensor/slice` — serve a typed 10D tensor slice, axes and
528/// bounds from headers.
529async fn tensor_slice_handler(
530    State(state): State<Arc<WebizenState>>,
531    Query(q): Query<TensorSliceQuery>,
532    headers: HeaderMap,
533) -> Response {
534    use crate::daemon_tensor::{
535        build_tensor_slice_bytes, verify_tensor_slice_signature, TensorSliceAuthError,
536        TensorSliceError, TensorSliceLane, TensorSliceRequest, DEFAULT_SLICE_MAX_NODES,
537    };
538    use crate::render::telemetry::{STANDPOINT_DID, STANDPOINT_VAULT};
539    use crate::tensor::buffer_export::tensor_node_count;
540
541    let max_nodes = header_parse_u32(&headers, "x-qualia-max-nodes")
542        .or(q.max_nodes)
543        .map(|n| n as usize)
544        .unwrap_or(DEFAULT_SLICE_MAX_NODES);
545
546    let t_slice = header_parse_f32(&headers, "x-qualia-t-slice")
547        .or(q.t_slice)
548        .unwrap_or(0.5);
549
550    let t_window = header_parse_f32(&headers, "x-qualia-t-window")
551        .or(q.t_window)
552        .unwrap_or(1.0);
553
554    let standpoint_class = header_parse_u32(&headers, "x-qualia-standpoint-class").unwrap_or(0);
555
556    let identifier_did = header_str(&headers, "x-qualia-identifier-did").unwrap_or_default();
557    let session_nonce = header_str(&headers, "x-qualia-session-nonce").unwrap_or_default();
558    let signature_hex = header_str(&headers, "x-qualia-signature").unwrap_or_default();
559
560    let mut lane = if standpoint_class >= STANDPOINT_VAULT {
561        TensorSliceLane::Identifier
562    } else if standpoint_class >= STANDPOINT_DID {
563        TensorSliceLane::Identifier
564    } else {
565        TensorSliceLane::Commons
566    };
567
568    if standpoint_class >= STANDPOINT_DID {
569        let vault = match state.vault.lock() {
570            Ok(guard) => guard,
571            Err(_) => {
572                return (
573                    StatusCode::INTERNAL_SERVER_ERROR,
574                    Json(json!({ "error": "vault_unavailable" })),
575                )
576                    .into_response();
577            }
578        };
579        if let Err(auth_err) = verify_tensor_slice_signature(
580            &vault,
581            &identifier_did,
582            &session_nonce,
583            standpoint_class,
584            t_slice,
585            t_window,
586            &signature_hex,
587        ) {
588            let code = match auth_err {
589                TensorSliceAuthError::InvalidSignature => "invalid_signature",
590                TensorSliceAuthError::InvalidSignatureEncoding => "invalid_signature_encoding",
591                TensorSliceAuthError::SignatureRequired => "signature_required",
592                TensorSliceAuthError::IdentifierDidRequired => "identifier_did_required",
593                TensorSliceAuthError::SessionNonceRequired => "session_nonce_required",
594            };
595            return (
596                StatusCode::FORBIDDEN,
597                Json(json!({
598                    "error": "tensor_slice_auth_failed",
599                    "code": code,
600                })),
601            )
602                .into_response();
603        }
604        drop(vault);
605    } else {
606        lane = headers
607            .get("x-qualia-lane")
608            .and_then(|v| v.to_str().ok())
609            .or(q.lane.as_deref())
610            .map(TensorSliceLane::from_header)
611            .unwrap_or(TensorSliceLane::Commons);
612    }
613
614    let req = TensorSliceRequest {
615        max_nodes,
616        t_slice,
617        t_window,
618        lane,
619        standpoint_class,
620    };
621
622    let guard = crate::daemon_graph::graph_read_guard();
623    match build_tensor_slice_bytes(guard.as_slice(), &req) {
624        Ok(bytes) => {
625            let node_count = tensor_node_count(&bytes).unwrap_or(0);
626            Response::builder()
627                .status(StatusCode::OK)
628                .header(header::CONTENT_TYPE, "application/octet-stream")
629                .header("X-Qualia-Tensor-Nodes", node_count.to_string())
630                .header("X-Qualia-Tensor-Bytes", bytes.len().to_string())
631                .header(
632                    "X-Qualia-Tensor-Lane",
633                    match lane {
634                        TensorSliceLane::Commons => "commons",
635                        TensorSliceLane::Identifier => "identifier",
636                    },
637                )
638                .body(Body::from(bytes))
639                .unwrap()
640        }
641        Err(TensorSliceError::EmptyGraph) => (
642            StatusCode::NOT_FOUND,
643            Json(json!({
644                "error": "empty_graph",
645                "message": "graph empty or no nodes match temporal window"
646            })),
647        )
648            .into_response(),
649        Err(TensorSliceError::BufferTooSmall) => (
650            StatusCode::INTERNAL_SERVER_ERROR,
651            Json(json!({ "error": "tensor_buffer_error" })),
652        )
653            .into_response(),
654    }
655}
656
657/// Dev-only: export KeyVault-derived Ed25519 seed for `identifier_did` (localhost pairing).
658async fn tensor_dev_signing_key_handler(
659    State(state): State<Arc<WebizenState>>,
660    Query(qs): Query<std::collections::HashMap<String, String>>,
661) -> impl IntoResponse {
662    if !state.dev {
663        return (StatusCode::FORBIDDEN, Json(json!({ "error": "dev_only" }))).into_response();
664    }
665    let identifier_did = qs.get("identifier_did").cloned().unwrap_or_default();
666    if identifier_did.trim().is_empty() {
667        return (
668            StatusCode::BAD_REQUEST,
669            Json(json!({ "error": "identifier_did_required" })),
670        )
671            .into_response();
672    }
673    let vault = match state.vault.lock() {
674        Ok(guard) => guard,
675        Err(_) => {
676            return (
677                StatusCode::INTERNAL_SERVER_ERROR,
678                Json(json!({ "error": "vault_unavailable" })),
679            )
680                .into_response();
681        }
682    };
683    let sk = vault.derive_key(&identifier_did);
684    let pk = vault.public_key_bytes_for_context(&identifier_did);
685    (
686        StatusCode::OK,
687        Json(json!({
688            "identifier_did": identifier_did,
689            "signing_key_hex": hex::encode(sk.to_bytes()),
690            "public_key_hex": hex::encode(pk),
691            "warning": "dev_only — never expose signing keys outside localhost pairing"
692        })),
693    )
694        .into_response()
695}
696
697/// SSE stream of Lamport graph revisions for live viewport sync (`PR-C9c.1`).
698async fn tensor_events_handler() -> Response {
699    use std::convert::Infallible;
700    use std::time::Duration;
701
702    let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<String>();
703    let initial = crate::daemon_graph::graph_revision();
704
705    tokio::spawn(async move {
706        let _ = tx.send(format!("data: {{\"revision\":{initial}}}\n\n"));
707        let mut last = initial;
708        let mut sub = crate::daemon_graph::subscribe_graph_revisions();
709        let mut keepalive = tokio::time::interval(Duration::from_secs(15));
710        keepalive.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
711
712        loop {
713            if tx.is_closed() {
714                break;
715            }
716            tokio::select! {
717                result = sub.recv() => {
718                    match result {
719                        Ok(rev) => {
720                            if rev > last {
721                                last = rev;
722                                let _ = tx.send(format!("data: {{\"revision\":{rev}}}\n\n"));
723                            }
724                        }
725                        Err(broadcast::error::RecvError::Lagged(_)) => {
726                            let current = crate::daemon_graph::graph_revision();
727                            if current > last {
728                                last = current;
729                                let _ = tx.send(format!("data: {{\"revision\":{current}}}\n\n"));
730                            }
731                        }
732                        Err(broadcast::error::RecvError::Closed) => break,
733                    }
734                }
735                _ = keepalive.tick() => {
736                    let _ = tx.send(": keepalive\n\n".to_string());
737                }
738            }
739        }
740    });
741
742    let body_stream =
743        UnboundedReceiverStream::new(rx).map(|chunk| Ok::<Bytes, Infallible>(Bytes::from(chunk)));
744
745    Response::builder()
746        .status(StatusCode::OK)
747        .header(header::CONTENT_TYPE, "text/event-stream")
748        .header(header::CACHE_CONTROL, "no-cache")
749        .header(header::CONNECTION, "keep-alive")
750        .body(Body::from_stream(body_stream))
751        .unwrap()
752}
753
754/// SSE stream of `pulse.publish` events for live collaborative sync.
755///
756/// Each event is a JSON object with `seq`, `topic`, `payload_summary`, and
757/// `timestamp` fields. Subscribers connect via `GET /pulse/events` and receive
758/// a keepalive comment every 15 seconds.
759async fn pulse_events_handler() -> Response {
760    use std::convert::Infallible;
761    use std::time::Duration;
762
763    let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<String>();
764    let initial_seq = crate::pulse_transport::pulse_seq();
765
766    tokio::spawn(async move {
767        let _ = tx.send(format!(
768            "data: {{\"seq\":{initial_seq},\"topic\":\"\",\"payload_summary\":\"\",\"timestamp\":0}}\n\n"
769        ));
770        let mut sub = crate::pulse_transport::subscribe();
771        let mut keepalive = tokio::time::interval(Duration::from_secs(15));
772        keepalive.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
773
774        loop {
775            if tx.is_closed() {
776                break;
777            }
778            tokio::select! {
779                result = sub.recv() => {
780                    match result {
781                        Ok(event) => {
782                            let _ = tx.send(format!(
783                                "data: {{\"seq\":{},\"topic\":\"{}\",\"payload_summary\":\"{}\",\"timestamp\":{}}}\n\n",
784                                event.seq,
785                                event.topic.replace('"', "\\\""),
786                                event.payload_summary.replace('"', "\\\""),
787                                event.timestamp
788                            ));
789                        }
790                        Err(broadcast::error::RecvError::Lagged(_)) => {
791                            let current = crate::pulse_transport::pulse_seq();
792                            let _ = tx.send(format!(
793                                "data: {{\"seq\":{current},\"topic\":\"\",\"payload_summary\":\"lagged\",\"timestamp\":0}}\n\n"
794                            ));
795                        }
796                        Err(broadcast::error::RecvError::Closed) => break,
797                    }
798                }
799                _ = keepalive.tick() => {
800                    let _ = tx.send(": keepalive\n\n".to_string());
801                }
802            }
803        }
804    });
805
806    let body_stream =
807        UnboundedReceiverStream::new(rx).map(|chunk| Ok::<Bytes, Infallible>(Bytes::from(chunk)));
808
809    Response::builder()
810        .status(StatusCode::OK)
811        .header(header::CONTENT_TYPE, "text/event-stream")
812        .header(header::CACHE_CONTROL, "no-cache")
813        .header(header::CONNECTION, "keep-alive")
814        .body(Body::from_stream(body_stream))
815        .unwrap()
816}
817
818/// `GET /health` — liveness plus real telemetry (graph quin count,
819/// revision, webtorrent seed stats, execution environment).
820async fn health_handler(State(state): State<Arc<WebizenState>>) -> impl IntoResponse {
821    (
822        StatusCode::OK,
823        Json(json!({
824            "status": "active",
825            "engine": "qualia-core-db",
826            "version": crate::ENGINE_VERSION,
827            "dev_mode": state.dev,
828            "graph_quin_count": crate::daemon_graph::graph_quin_count(),
829            "graph_revision": crate::daemon_graph::graph_revision(),
830            "webtorrent": crate::webtorrent_seeder::telemetry(),
831            "execution_environment": crate::services::daemon::execution_environment_json(),
832        })),
833    )
834}
835
836/// Capability negotiation for local browser/WASM adapters. This describes the
837/// real daemon boundary; it does not execute a Vibe call over the synchronous
838/// `Host` trait. Clients must keep native invocation asynchronous and obtain a
839/// user-mediated pairing token before making stateful requests.
840async fn vibe_capabilities_handler(
841    State(state): State<Arc<WebizenState>>,
842    headers: HeaderMap,
843) -> impl IntoResponse {
844    if !state.dev && !bridge_probe_authorized(&state, &headers) {
845        return (
846            StatusCode::UNAUTHORIZED,
847            Json(json!({"error": "missing or invalid x-qualia-token"})),
848        )
849            .into_response();
850    }
851    (
852        StatusCode::OK,
853        Json(crate::vibe_host::bridge::negotiation_document(true)),
854    )
855        .into_response()
856}
857
858/// `true` when `x-qualia-token` matches the configured token or a
859/// vault-verified qApp pairing token for localhost.
860fn bridge_probe_authorized(state: &WebizenState, headers: &HeaderMap) -> bool {
861    let Some(token) = headers
862        .get("x-qualia-token")
863        .and_then(|value| value.to_str().ok())
864    else {
865        return false;
866    };
867    if state.token.as_deref() == Some(token) {
868        return true;
869    }
870    state
871        .vault
872        .lock()
873        .ok()
874        .and_then(|vault| vault.verify_qapp_token(token, "localhost").ok())
875        .is_some()
876}
877
878/// `GET /proxy/fetch?url=` — allow-listed outbound fetch with a
879/// byte cap; restricted IPs rejected (SSRF guard).
880async fn proxy_fetch_handler(
881    Query(qs): Query<std::collections::HashMap<String, String>>,
882) -> impl IntoResponse {
883    let target = qs.get("url").cloned().unwrap_or_default();
884    if target.is_empty() {
885        return (
886            StatusCode::BAD_REQUEST,
887            Json(json!({"error": "missing url"})),
888        )
889            .into_response();
890    }
891    let parsed = match reqwest::Url::parse(&target) {
892        Ok(u) => u,
893        Err(_) => {
894            return (
895                StatusCode::BAD_REQUEST,
896                Json(json!({"error": "invalid url"})),
897            )
898                .into_response()
899        }
900    };
901
902    if !proxy_target_allowed(&parsed) {
903        return (
904            StatusCode::FORBIDDEN,
905            Json(json!({"error": "proxy target not allowed"})),
906        )
907            .into_response();
908    }
909
910    let client = reqwest::Client::builder()
911        .timeout(std::time::Duration::from_secs(120))
912        .build()
913        .unwrap();
914    let response = match client.get(parsed).send().await {
915        Ok(r) => r,
916        Err(e) => {
917            return (
918                StatusCode::BAD_GATEWAY,
919                Json(json!({"error": e.to_string()})),
920            )
921                .into_response()
922        }
923    };
924
925    let content_type = response
926        .headers()
927        .get(reqwest::header::CONTENT_TYPE)
928        .and_then(|v| v.to_str().ok())
929        .unwrap_or("application/octet-stream")
930        .to_string();
931    let bytes = response.bytes().await.unwrap_or_default();
932    if bytes.len() > PROXY_FETCH_MAX_BYTES {
933        return (
934            StatusCode::PAYLOAD_TOO_LARGE,
935            Json(json!({"error": "too large"})),
936        )
937            .into_response();
938    }
939
940    ([(header::CONTENT_TYPE, content_type)], bytes.to_vec()).into_response()
941}
942
943/// `POST /cache?filename=` — persist a dataset shard under `.qualia/cache/`.
944/// Sanitizes filename against path traversal and returns 500 on I/O error.
945async fn cache_handler(
946    Query(qs): Query<std::collections::HashMap<String, String>>,
947    body: axum::body::Bytes,
948) -> impl IntoResponse {
949    let raw_filename = qs
950        .get("filename")
951        .cloned()
952        .unwrap_or_else(|| "dataset_shard.q42".to_string());
953
954    // Sanitize filename against directory traversal
955    let path_candidate = std::path::Path::new(&raw_filename);
956    let sanitized_name = match path_candidate.file_name().and_then(|f| f.to_str()) {
957        Some(name) if !name.is_empty() && name != "." && name != ".." => name,
958        _ => {
959            return (
960                StatusCode::BAD_REQUEST,
961                Json(json!({ "error": "invalid_filename", "message": "Filename contains invalid path characters or traversal components" })),
962            )
963                .into_response();
964        }
965    };
966
967    let cache_dir = std::path::PathBuf::from(".qualia").join("cache");
968    if let Err(e) = std::fs::create_dir_all(&cache_dir) {
969        return (
970            StatusCode::INTERNAL_SERVER_ERROR,
971            Json(json!({ "error": "cache_dir_failed", "message": e.to_string() })),
972        )
973            .into_response();
974    }
975
976    let target_path = cache_dir.join(sanitized_name);
977    let byte_len = body.len();
978    if let Err(e) = std::fs::write(&target_path, body) {
979        return (
980            StatusCode::INTERNAL_SERVER_ERROR,
981            Json(json!({ "error": "write_failed", "message": e.to_string() })),
982        )
983            .into_response();
984    }
985
986    (
987        StatusCode::OK,
988        Json(json!({
989            "status": "ok",
990            "saved_to": target_path.to_str(),
991            "bytes_written": byte_len
992        })),
993    )
994        .into_response()
995}
996
997/// `GET /storage/selfhood` — report the configured selfhood
998/// storage path (descriptor only; `"isolated"` is a static label).
999async fn storage_selfhood_handler(State(state): State<Arc<WebizenState>>) -> impl IntoResponse {
1000    let path = std::path::Path::new(&state.storage_path).join("selfhood");
1001    Json(json!({ "path": path.to_str().unwrap_or_default(), "status": "isolated" }))
1002}
1003
1004/// `GET /storage/commons` — report the configured commons storage
1005/// path (descriptor only; `"public"` is a static label).
1006async fn storage_commons_handler(State(state): State<Arc<WebizenState>>) -> impl IntoResponse {
1007    let path = std::path::Path::new(&state.storage_path).join("commons");
1008    Json(json!({ "path": path.to_str().unwrap_or_default(), "status": "public" }))
1009}
1010
1011#[derive(Deserialize)]
1012pub struct PermissionsCompileRequest {
1013    pub payload: String, // yaml-ld-q42
1014}
1015
1016#[derive(Serialize, Deserialize)]
1017pub struct CompiledPermission {
1018    pub routing_mask: u64,
1019    pub semantic_handshake: String,
1020    pub is_permissive_commons: bool,
1021}
1022
1023/// `POST /permissions/compile` — parse a yaml-ld-q42 permission
1024/// payload into a routing mask + semantic handshake descriptor.
1025pub async fn permissions_compile_handler(
1026    Json(req): Json<PermissionsCompileRequest>,
1027) -> impl IntoResponse {
1028    // Compile yaml-ld-q42 down to hardware bitmask
1029    let mut is_permissive_commons = false;
1030    let mut routing_mask = 0u64;
1031
1032    // Semantic Handshake template creation
1033    let semantic_handshake = format!(
1034        "Semantic Cryptographic Proof Template: [Payload Length: {}]",
1035        req.payload.len()
1036    );
1037
1038    if req.payload.contains("Commercial Micro-Commons") || req.payload.contains("Bilateral") {
1039        routing_mask |= 0x02 << 61; // EnforceBilateralMicroCommons
1040        routing_mask |= 1 << 50; // MASK_COMMERCIAL_BILLABLE_GATE
1041    } else if req.payload.contains("Public Commons") || req.payload.contains("PermissiveCommons") {
1042        routing_mask |= 0x01 << 61; // EnforcePermissiveCommons
1043        is_permissive_commons = true;
1044    } else {
1045        routing_mask |= 0x00 << 61; // PassthroughStandard
1046    }
1047
1048    Json(CompiledPermission {
1049        routing_mask,
1050        semantic_handshake,
1051        is_permissive_commons,
1052    })
1053}
1054
1055#[derive(Deserialize)]
1056pub struct WebizenRpcRequest {
1057    pub method: String,
1058    pub scopes: Option<Vec<String>>,
1059    pub payload: Option<String>,
1060}
1061
1062/// `POST /rpc` — Webizen JSON-RPC dispatch; refuses stateful calls
1063/// while Sanctuary Mode is engaged.
1064pub async fn webizen_rpc_handler(
1065    State(state): State<Arc<WebizenState>>,
1066    Json(req): Json<WebizenRpcRequest>,
1067) -> impl IntoResponse {
1068    if req.method == "requestAccess" {
1069        if let Some(scopes) = req.scopes {
1070            if state
1071                .in_sanctuary_mode
1072                .load(std::sync::atomic::Ordering::Relaxed)
1073            {
1074                // Fiduciary Supremacy: Reject requests to 'wf:' or the selfhood store completely.
1075                // Block both the new `selfhood` name and the legacy `sovereign` name (fail-closed —
1076                // never loosen this lock while the rename propagates).
1077                if scopes.iter().any(|s| {
1078                    s.starts_with("wf:") || s.contains("selfhood") || s.contains("sovereign")
1079                }) {
1080                    return (
1081                        StatusCode::LOCKED,
1082                        Json(json!({"error": "Selfhood path locked during Sanctuary mode."})),
1083                    )
1084                        .into_response();
1085                }
1086            }
1087        }
1088        return (StatusCode::OK, Json(json!({"status": "access_granted"}))).into_response();
1089    }
1090
1091    if req.method == "signAndInject" {
1092        // Implement pure 48-byte NQuin request and semantic handshake...
1093        return (StatusCode::OK, Json(json!({"status": "injected"}))).into_response();
1094    }
1095
1096    if req.method == "resolveNym" {
1097        return (StatusCode::OK, Json(json!({"status": "resolved"}))).into_response();
1098    }
1099
1100    (
1101        StatusCode::BAD_REQUEST,
1102        Json(json!({"error": "unknown method"})),
1103    )
1104        .into_response()
1105}
1106
1107/// `/bridge` — local browser/WASM bridge endpoint; token-gated
1108/// probe plus negotiated capability document.
1109async fn bridge_handler(
1110    ws: WebSocketUpgrade,
1111    State(state): State<Arc<WebizenState>>,
1112) -> impl IntoResponse {
1113    ws.on_upgrade(move |mut socket| async move {
1114        let handshake = json!({ "type": "HANDSHAKE_SUCCESS", "payload": { "mode": "NATIVE", "version": crate::ENGINE_VERSION } });
1115        let _ = socket.send(Message::Text(handshake.to_string().into())).await;
1116
1117        let mut pending_bench_id: Option<u64> = None;
1118        while let Some(Ok(msg)) = socket.recv().await {
1119            match msg {
1120                Message::Binary(bytes) => {
1121                    if let Some(id) = pending_bench_id.take() {
1122                        let reply = match crate::daemon_graph::replace_graph_from_flat_bytes(&bytes) {
1123                            Ok(c) => json!({ "type": "bench_loaded", "id": id, "quin_count": c }),
1124                            Err(e) => json!({ "type": "error", "id": id, "code": "bench_load_failed", "message": e }),
1125                        };
1126                        let _ = socket.send(Message::Text(reply.to_string().into())).await;
1127                    }
1128                }
1129                Message::Text(text) => {
1130                    if let Ok(frame) = serde_json::from_str::<serde_json::Value>(&text) {
1131                        let frame_type = frame.get("type").and_then(|v| v.as_str()).unwrap_or("");
1132                        let id = frame.get("id").and_then(|v| v.as_u64()).unwrap_or(0);
1133                        let reply = match frame_type {
1134                            "query" => {
1135                                let q = frame.get("query").and_then(|v| v.as_str()).unwrap_or("");
1136                                if q.len() as u64 > QUERY_PAYLOAD_LIMIT_BYTES {
1137                                    json!({
1138                                        "type": "error",
1139                                        "id": id,
1140                                        "code": "query_too_large",
1141                                        "message": format!("query exceeds {QUERY_PAYLOAD_LIMIT_BYTES} byte limit")
1142                                    })
1143                                } else {
1144                                let graph = crate::daemon_graph::graph_read_guard();
1145                                match daemon_query::execute_ntriples_metrics(q, graph.as_slice()) {
1146                                    Ok(stats) => json!({
1147                                        "type": "result",
1148                                        "id": id,
1149                                        "match_count": stats.match_count,
1150                                        "vm_cycles": stats.vm_cycles
1151                                    }),
1152                                    Err(err) => ws_query_error_json(id, err),
1153                                }
1154                                }
1155                            }
1156                            "bench_load" if state.dev => {
1157                                if frame.get("byte_length").is_some() { pending_bench_id = Some(id); json!({ "type": "bench_load_ready", "id": id }) }
1158                                else if let Some(b64) = frame.get("db_b64").and_then(|v| v.as_str()) {
1159                                    match decode_bench_load_b64(b64) {
1160                                        Ok(bytes) => match crate::daemon_graph::replace_graph_from_flat_bytes(&bytes) {
1161                                            Ok(c) => json!({ "type": "bench_loaded", "id": id, "quin_count": c }),
1162                                            Err(e) => json!({ "type": "error", "id": id, "message": e })
1163                                        },
1164                                        Err(e) => json!({ "type": "error", "id": id, "message": e })
1165                                    }
1166                                } else { json!({ "type": "error", "id": id, "message": "requires db_b64" }) }
1167                            }
1168                            _ => json!({ "type": "error", "id": id, "message": "unsupported" }),
1169                        };
1170                        let _ = socket.send(Message::Text(reply.to_string().into())).await;
1171                    }
1172                }
1173                _ => {}
1174            }
1175        }
1176    })
1177}
1178
1179#[derive(Deserialize)]
1180struct UpdateRequest {
1181    update: String,
1182}
1183
1184/// `POST /update` — apply a SPARQL 1.1 Update to the resident graph.
1185///
1186/// Same token auth as `/query`. The mutation is signed with a **real** key
1187/// derived from the daemon's key vault (never a placeholder) and persisted
1188/// durably (snapshot + signed WAL audit trail) via
1189/// `daemon_graph::apply_sparql_update_durable`. Loopback-only, like `/query`.
1190async fn update_handler(
1191    State(state): State<Arc<WebizenState>>,
1192    headers: HeaderMap,
1193    Json(request): Json<UpdateRequest>,
1194) -> impl IntoResponse {
1195    // Auth: mirror /query (token required unless dev mode).
1196    if !state.dev {
1197        let token = headers
1198            .get("x-qualia-token")
1199            .and_then(|v| v.to_str().ok())
1200            .map(|s| s.to_string());
1201        let ok = token
1202            .as_ref()
1203            .map(|t| {
1204                let vault = state.vault.lock().unwrap();
1205                vault.verify_qapp_token(t, "localhost").is_ok() || Some(t) == state.token.as_ref()
1206            })
1207            .unwrap_or(false);
1208        if !ok {
1209            return (
1210                StatusCode::UNAUTHORIZED,
1211                Json(json!({"error": "unauthorized"})),
1212            )
1213                .into_response();
1214        }
1215    }
1216
1217    let src = request.update.trim();
1218    if src.is_empty() {
1219        return (
1220            StatusCode::BAD_REQUEST,
1221            Json(json!({"error": "empty update"})),
1222        )
1223            .into_response();
1224    }
1225    if src.len() as u64 > QUERY_PAYLOAD_LIMIT_BYTES {
1226        return (
1227            StatusCode::PAYLOAD_TOO_LARGE,
1228            Json(json!({"error": "update too large", "limit_bytes": QUERY_PAYLOAD_LIMIT_BYTES})),
1229        )
1230            .into_response();
1231    }
1232    if !crate::sparql_library::sparql_grammar::is_update(src) {
1233        return (
1234            StatusCode::BAD_REQUEST,
1235            Json(json!({"error": "not a SPARQL Update (use /query for reads)"})),
1236        )
1237            .into_response();
1238    }
1239
1240    let mut ctx = crate::sparql_ast::SparqlQueryContext::new();
1241    let prefixes = std::collections::HashMap::new();
1242    let op = match crate::sparql_library::sparql_grammar::parse_update(src, &mut ctx, &prefixes) {
1243        Ok(op) => op,
1244        Err(e) => {
1245            return (
1246                StatusCode::BAD_REQUEST,
1247                Json(json!({"error": format!("update parse error: {e}")})),
1248            )
1249                .into_response()
1250        }
1251    };
1252
1253    // Real signing key from the daemon key vault — never a placeholder.
1254    let signing_key = {
1255        let vault = match state.vault.lock() {
1256            Ok(v) => v,
1257            Err(_) => {
1258                return (
1259                    StatusCode::INTERNAL_SERVER_ERROR,
1260                    Json(json!({"error": "vault_unavailable"})),
1261                )
1262                    .into_response()
1263            }
1264        };
1265        vault.derive_key("sparql-update")
1266    };
1267    let principal = crate::q_hash("did:qualia:sparql-update-principal");
1268    let agent = crate::q_hash("did:qualia:sparql-update-agent");
1269    let wal_path = format!("{}/sparql_update.wal", state.storage_path);
1270
1271    match crate::daemon_graph::apply_sparql_update_durable(
1272        &op,
1273        &ctx,
1274        &signing_key,
1275        principal,
1276        agent,
1277        &wal_path,
1278        &state.storage_path,
1279    ) {
1280        Ok(outcome) => (
1281            StatusCode::OK,
1282            Json(json!({
1283                "inserted": outcome.inserted,
1284                "deleted": outcome.deleted,
1285                "persisted": outcome.persisted,
1286            })),
1287        )
1288            .into_response(),
1289        Err(e) => (
1290            StatusCode::BAD_REQUEST,
1291            Json(json!({"error": format!("update failed: {e}")})),
1292        )
1293            .into_response(),
1294    }
1295}
1296
1297/// `POST /query` — execute a native query with format negotiation
1298/// (JSON-LD / N-Triples / raw Q42) and bounded output.
1299async fn query_handler(
1300    State(state): State<Arc<WebizenState>>,
1301    headers: HeaderMap,
1302    Json(request): Json<NativeQueryRequest>,
1303) -> impl IntoResponse {
1304    let token = headers
1305        .get("x-qualia-token")
1306        .and_then(|v| v.to_str().ok())
1307        .map(|s| s.to_string());
1308    let accept = headers.get(header::ACCEPT).and_then(|v| v.to_str().ok());
1309
1310    let mut allowed_shapes: Option<Vec<String>> = None;
1311    if !state.dev {
1312        if let Some(t) = token.as_ref() {
1313            let vault = state.vault.lock().unwrap();
1314            match vault.verify_qapp_token(t, "localhost") {
1315                Ok(payload) => {
1316                    allowed_shapes = Some(payload.capabilities);
1317                }
1318                Err(_) => {
1319                    if Some(t) != state.token.as_ref() {
1320                        return (
1321                            StatusCode::UNAUTHORIZED,
1322                            Json(json!({"error": "unauthorized"})),
1323                        )
1324                            .into_response();
1325                    }
1326                }
1327            }
1328        } else {
1329            return (
1330                StatusCode::UNAUTHORIZED,
1331                Json(json!({"error": "missing x-qualia-token"})),
1332            )
1333                .into_response();
1334        }
1335    }
1336
1337    if let Some(shapes) = allowed_shapes {
1338        let q = request.query.to_lowercase();
1339        let mut authorized = false;
1340        for shape in shapes {
1341            let ns = shape.split(':').next().unwrap_or(&shape).to_lowercase();
1342            if q.contains(&ns) {
1343                authorized = true;
1344                break;
1345            }
1346        }
1347        if !authorized && !q.is_empty() {
1348            return (
1349                StatusCode::FORBIDDEN,
1350                Json(json!({"error": "gatekeeper violation"})),
1351            )
1352                .into_response();
1353        }
1354    }
1355
1356    let output_format = match negotiate_format(request.format.as_deref(), accept) {
1357        Ok(f) => f,
1358        Err(_) => return not_acceptable_format_response().into_response(),
1359    };
1360
1361    if request.query.trim().is_empty() {
1362        return (
1363            StatusCode::BAD_REQUEST,
1364            Json(json!({"error": "empty query"})),
1365        )
1366            .into_response();
1367    }
1368
1369    if request.query.len() as u64 > QUERY_PAYLOAD_LIMIT_BYTES {
1370        return (
1371            StatusCode::PAYLOAD_TOO_LARGE,
1372            Json(json!({
1373                "error": "query too large",
1374                "limit_bytes": QUERY_PAYLOAD_LIMIT_BYTES
1375            })),
1376        )
1377            .into_response();
1378    }
1379
1380    let graph_guard = crate::daemon_graph::graph_read_guard();
1381    let (stats, final_results) =
1382        match daemon_query::execute_query_on_graph(&request.query, graph_guard.as_slice()) {
1383            Ok(pair) => pair,
1384            Err(_) => {
1385                return (
1386                    StatusCode::BAD_REQUEST,
1387                    Json(json!({"error": "query execution failed"})),
1388                )
1389                    .into_response()
1390            }
1391        };
1392
1393    let mut sanitized_results = Vec::with_capacity(final_results.len());
1394    let mut gatekeeper_halt = false;
1395    for quin in final_results {
1396        let sensitivity = quin.context >> 56;
1397        if sensitivity == 0x02 {
1398            gatekeeper_halt = true;
1399            sanitized_results.clear();
1400            break;
1401        } else {
1402            sanitized_results.push(quin);
1403        }
1404    }
1405    if gatekeeper_halt {
1406        return (
1407            StatusCode::FORBIDDEN,
1408            Json(json!({"error": "classified data egress blocked"})),
1409        )
1410            .into_response();
1411    }
1412
1413    let final_results = sanitized_results;
1414    let match_count = final_results.len();
1415
1416    let mut response_headers = HeaderMap::new();
1417    response_headers.insert(
1418        HeaderName::from_static("x-qualia-compute-cost"),
1419        HeaderValue::from_str(&format!("{}+{}", match_count, stats.vm_cycles)).unwrap(),
1420    );
1421
1422    match output_format {
1423        OutputFormat::NTriples => {
1424            let mut body_buf: Vec<u8> = Vec::with_capacity(match_count.max(1) * 80);
1425            let _ = crate::resolver::format_ntriples_to(&final_results, &mut body_buf);
1426            response_headers.insert(
1427                header::CONTENT_TYPE,
1428                HeaderValue::from_static("application/n-triples"),
1429            );
1430            (
1431                StatusCode::OK,
1432                response_headers,
1433                String::from_utf8(body_buf).unwrap_or_default(),
1434            )
1435                .into_response()
1436        }
1437        OutputFormat::JsonLd => {
1438            let graph: Vec<serde_json::Value> = final_results.iter().map(|q| json!({
1439                "subject": q.subject.to_string(), "predicate": q.predicate.to_string(), "object": q.object.to_string(),
1440                "context": q.context.to_string(), "metadata": q.metadata.to_string(), "parity": q.parity.to_string()
1441            })).collect();
1442            response_headers.insert(
1443                header::CONTENT_TYPE,
1444                HeaderValue::from_static("application/ld+json"),
1445            );
1446            let res = json!({ "@context": { "@vocab": "https://webizen.org/vocab#" }, "@graph": graph, "match_count": match_count });
1447            (StatusCode::OK, response_headers, res.to_string()).into_response()
1448        }
1449        OutputFormat::RawQ42 => {
1450            let bytes: &[u8] = bytemuck::cast_slice(&final_results);
1451            response_headers.insert(
1452                header::CONTENT_TYPE,
1453                HeaderValue::from_static("application/x-qualia-q42"),
1454            );
1455            (
1456                StatusCode::OK,
1457                response_headers,
1458                bytes.to_vec(),
1459            )
1460                .into_response()
1461        }
1462    }
1463}
1464
1465/// `GET /telemetry` (WS) — upgrade to a websocket streaming
1466/// `telemetry_tx` broadcast frames.
1467async fn telemetry_handler(
1468    ws: WebSocketUpgrade,
1469    State(state): State<Arc<WebizenState>>,
1470) -> impl IntoResponse {
1471    ws.on_upgrade(|mut socket| async move {
1472        let mut rx = state.telemetry_tx.subscribe();
1473        while let Ok(msg) = rx.recv().await {
1474            if socket.send(Message::Binary(msg.into())).await.is_err() {
1475                break;
1476            }
1477        }
1478    })
1479}
1480
1481/// External WASM telemetry ingestion endpoint.
1482///
1483/// External devices (phones, browser tabs, other machines on the LAN) can
1484/// POST their `SystemTelemetry` data here for local processing. The desktop
1485/// app receives it, processes it locally (GPU visualisation, graph storage,
1486/// anomaly detection), and broadcasts it to all connected telemetry
1487/// subscribers (including the ambient visualisation bridge).
1488///
1489/// POST /telemetry/ingest
1490/// Body: { "source": "device-id", "telemetry": { ...SystemTelemetry fields } }
1491/// Response: 200 OK { "status": "ingested", "subscribers": N }
1492async fn telemetry_ingest_handler(
1493    State(state): State<Arc<WebizenState>>,
1494    Json(payload): Json<TelemetryIngestRequest>,
1495) -> impl IntoResponse {
1496    // Serialize the SystemTelemetry to bytes and broadcast to all subscribers
1497    let bytes = bytemuck::bytes_of(&payload.telemetry);
1498    let subscriber_count = state.telemetry_tx.receiver_count();
1499
1500    // Broadcast the telemetry to all connected subscribers (ambient viz,
1501    // render bridge, etc.)
1502    let _ = state.telemetry_tx.send(bytes.to_vec());
1503
1504    // Also store the telemetry source for provenance tracking
1505    // (the source device ID is logged for audit purposes)
1506    eprintln!(
1507        "[telemetry] Ingested external telemetry from {} ({} subscribers)",
1508        payload.source, subscriber_count
1509    );
1510
1511    (
1512        StatusCode::OK,
1513        Json(json!({
1514            "status": "ingested",
1515            "source": payload.source,
1516            "subscribers": subscriber_count,
1517        })),
1518    )
1519}
1520
1521/// Request body for external telemetry ingestion
1522#[derive(Deserialize)]
1523struct TelemetryIngestRequest {
1524    /// Source device identifier (e.g. "phone-abc123", "browser-tab-1")
1525    source: String,
1526    /// The telemetry data from the external device
1527    telemetry: crate::render::telemetry::SystemTelemetry,
1528}
1529
1530/// `POST /manifest` — accept and store a new volume manifest
1531/// body (capped read).
1532async fn manifest_handler(mut body: Body) -> impl IntoResponse {
1533    use http_body_util::BodyExt;
1534    let mut payload_bytes = Vec::new();
1535    while let Some(Ok(frame)) = body.frame().await {
1536        if let Some(chunk) = frame.data_ref() {
1537            payload_bytes.extend_from_slice(chunk);
1538        }
1539    }
1540    let lamport_clock: u64 = match crate::wal::WriteAheadLog::open("qualia_global.wal") {
1541        Ok(mut wal) => wal.buffered_count().unwrap_or(0) as u64 + 1,
1542        Err(_) => 1,
1543    };
1544    match crate::yaml_ld_q42::compile_yaml_ld_to_quins(&payload_bytes, 0, lamport_clock) {
1545        Ok(quins) => {
1546            for quin in quins {
1547                let _ = append_mutation(&quin);
1548            }
1549            axum::http::StatusCode::OK
1550        }
1551        Err(_) => axum::http::StatusCode::BAD_REQUEST,
1552    }
1553}
1554
1555/// `GET /manifest/current` — return the currently stored manifest.
1556async fn current_manifest_handler() -> impl IntoResponse {
1557    let workspace = json!({ "pages": [] });
1558    Json(workspace)
1559}
1560
1561use crate::extension_bus::ExtensionBus;
1562use std::sync::OnceLock;
1563static EXTENSION_BUS: OnceLock<ExtensionBus> = OnceLock::new();
1564/// Process-global extension registry (lazily initialized).
1565fn get_extension_bus() -> &'static ExtensionBus {
1566    EXTENSION_BUS.get_or_init(|| {
1567        let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
1568        ExtensionBus::new(
1569            std::path::PathBuf::from(home)
1570                .join(".qualia")
1571                .join("extensions")
1572                .join("pool"),
1573        )
1574    })
1575}
1576/// `GET /extensions` — list registered extension manifests.
1577async fn list_extensions_handler() -> impl IntoResponse {
1578    Json(get_extension_bus().list_extensions())
1579}
1580/// `GET /extensions/query` — filter registered extensions by
1581/// capability query.
1582async fn query_extensions_handler(
1583    axum::extract::Path(interface): axum::extract::Path<String>,
1584) -> impl IntoResponse {
1585    Json(get_extension_bus().query_capability(q_hash(&interface)))
1586}
1587/// `POST /extensions/register` — ingest a new extension manifest
1588/// (capped body read); 400 on malformed input.
1589async fn register_extension_handler(mut body: Body) -> impl IntoResponse {
1590    use http_body_util::BodyExt;
1591    let mut payload_bytes = Vec::new();
1592    while let Some(Ok(frame)) = body.frame().await {
1593        if let Some(chunk) = frame.data_ref() {
1594            payload_bytes.extend_from_slice(chunk);
1595        }
1596    }
1597    let bus = get_extension_bus();
1598    let temp_file = std::env::temp_dir().join("temp_manifest.json");
1599    if std::fs::write(&temp_file, payload_bytes).is_ok()
1600        && bus.register_extension_from_path(&temp_file).is_ok()
1601    {
1602        return axum::http::StatusCode::OK;
1603    }
1604    axum::http::StatusCode::BAD_REQUEST
1605}
1606/// `GET /mobile/qr` — render an SVG QR code pairing this host's
1607/// LAN address with the bootstrap gateway URL.
1608async fn mobile_qr_handler(
1609    axum::extract::State(state): axum::extract::State<Arc<WebizenState>>,
1610) -> impl IntoResponse {
1611    let port = state.port;
1612    let local_ip = std::net::UdpSocket::bind("0.0.0.0:0")
1613        .and_then(|s| {
1614            s.connect("1.1.1.1:80")?;
1615            s.local_addr()
1616        })
1617        .map(|addr| addr.ip().to_string())
1618        .unwrap_or_else(|_| "192.168.1.45".to_string());
1619
1620    let target = format!("http://{}:{}/mobile/app/index.html", local_ip, port);
1621    let url = format!(
1622        "https://webizen.au/bootstrap_gateway/index.html?target={}",
1623        urlencoding::encode(&target)
1624    );
1625
1626    let qr = fast_qr::QRBuilder::new(url).build().unwrap();
1627    let svg = fast_qr::convert::svg::SvgBuilder::default().to_str(&qr);
1628
1629    (
1630        StatusCode::OK,
1631        [(axum::http::header::CONTENT_TYPE, "image/svg+xml")],
1632        svg,
1633    )
1634        .into_response()
1635}
1636/// `GET /mobile/stream` (and `/mobile/ws`) — **Intentional Bootstrap Scaffold**:
1637/// Returns `"WS Mock"` as a lightweight reachability probe for mobile devices connecting
1638/// to localhost via LAN pairing after scanning `GET /mobile/qr`.
1639///
1640/// Workflow Context:
1641/// 1. Desktop renders QR code via `mobile_qr_handler`, directing mobile browser to
1642///    `https://webizen.au/bootstrap_gateway/index.html?target=http://{local_ip}:{port}/mobile/app/index.html`.
1643/// 2. Mobile browser resolves LAN IP and loads the PWA (`bootstrap_gateway/mobile`).
1644/// 3. Mobile probes `/mobile/stream` to verify HTTP connectivity and port reachability
1645///    before initiating WebSocket upgrades or pane subscription. Real mobile telemetry
1646///    egress flows through the fully wired `POST /telemetry/ingest` and `/qualia-bridge`.
1647async fn mobile_ws_handler() -> impl IntoResponse {
1648    (StatusCode::OK, "WS Mock").into_response()
1649}
1650
1651/// `POST /generate_pane` (and `/mobile/pane`) — **Intentional Bootstrap Scaffold**:
1652/// Returns `"Pane Mock"` as a reachability probe for the mobile client's pane negotiation
1653/// loop during initial QR pairing handshake.
1654async fn mobile_generate_pane_handler() -> impl IntoResponse {
1655    (StatusCode::OK, "Pane Mock").into_response()
1656}
1657
1658#[cfg(test)]
1659mod tests {
1660    use super::*;
1661
1662    #[tokio::test]
1663    async fn test_permissions_compile_handler_commercial() {
1664        let req = PermissionsCompileRequest {
1665            payload: "type: Commercial Micro-Commons".to_string(),
1666        };
1667        let response = permissions_compile_handler(Json(req)).await.into_response();
1668        let body = http_body_util::BodyExt::collect(response.into_body())
1669            .await
1670            .unwrap()
1671            .to_bytes();
1672        let compiled: CompiledPermission = serde_json::from_slice(&body).unwrap();
1673
1674        assert_eq!((compiled.routing_mask >> 61) & 0x03, 0x02); // EnforceBilateralMicroCommons
1675        assert_ne!((compiled.routing_mask >> 50) & 0x01, 0); // MASK_COMMERCIAL_BILLABLE_GATE set
1676        assert_eq!(compiled.is_permissive_commons, false);
1677    }
1678
1679    #[test]
1680    fn not_acceptable_payload_matches_native_test_contract() {
1681        let (_, Json(body)) = not_acceptable_format_response();
1682        assert_eq!(body["code"], "not_acceptable");
1683        assert_eq!(body["status"], "error");
1684        let message = body["message"].as_str().expect("message");
1685        assert!(message.contains("application/ld+json"));
1686        assert!(message.contains("application/n-triples"));
1687    }
1688
1689    #[tokio::test]
1690    async fn test_permissions_compile_handler_public() {
1691        let req = PermissionsCompileRequest {
1692            payload: "type: Public Commons".to_string(),
1693        };
1694        let response = permissions_compile_handler(Json(req)).await.into_response();
1695        let body = http_body_util::BodyExt::collect(response.into_body())
1696            .await
1697            .unwrap()
1698            .to_bytes();
1699        let compiled: CompiledPermission = serde_json::from_slice(&body).unwrap();
1700
1701        assert_eq!((compiled.routing_mask >> 61) & 0x03, 0x01); // EnforcePermissiveCommons
1702        assert_eq!(compiled.is_permissive_commons, true);
1703    }
1704
1705    #[tokio::test]
1706    async fn test_webizen_rpc_sanctuary_mode_assertion() {
1707        let (telemetry_tx, _) = tokio::sync::broadcast::channel(10);
1708        let state = Arc::new(WebizenState {
1709            telemetry_tx,
1710            type_index: Arc::new([]),
1711            dev: true,
1712            token: None,
1713            vault: Arc::new(Mutex::new(crate::key_vault::KeyVault::new())),
1714            storage_path: "/tmp".to_string(),
1715            port: 8080,
1716            in_sanctuary_mode: Arc::new(std::sync::atomic::AtomicBool::new(true)),
1717        });
1718
1719        // 1. Requesting 'wf:AgentProposal' should fail with 423 LOCKED
1720        let req1 = WebizenRpcRequest {
1721            method: "requestAccess".to_string(),
1722            scopes: Some(vec!["wf:AgentProposal".to_string()]),
1723            payload: None,
1724        };
1725        let response1 = webizen_rpc_handler(axum::extract::State(state.clone()), Json(req1))
1726            .await
1727            .into_response();
1728        assert_eq!(response1.status(), StatusCode::LOCKED);
1729
1730        // 2. Requesting 'qp:Project' should succeed (Commons access allowed in Sanctuary)
1731        let req2 = WebizenRpcRequest {
1732            method: "requestAccess".to_string(),
1733            scopes: Some(vec!["qp:Project".to_string()]),
1734            payload: None,
1735        };
1736        let response2 = webizen_rpc_handler(axum::extract::State(state.clone()), Json(req2))
1737            .await
1738            .into_response();
1739        assert_eq!(response2.status(), StatusCode::OK);
1740    }
1741}