ctb_io_webui/
webui.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! `WebUI` service manager and embedded HTTP server lifecycle driver.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use ctb_build_info::build_info;
30
31use std::collections::HashMap;
32use std::sync::Arc;
33
34use ::http::StatusCode;
35use anyhow::{Context, Result};
36use axum::response::{Html, IntoResponse, Response};
37use handlebars::Handlebars;
38use maplit::btreemap;
39use serde::Serialize;
40use serde_json::{Value, json, to_value};
41use tokio::sync::Mutex;
42
43use crate::extractors::request_state::RequestState;
44use crate::json_value;
45use crate::server::start_webui_server;
46use crate::session_auth::{AuthenticatedUser, SharedUser};
47use crate::utilities::serde_value::insert_key;
48use ctb_formats_markdown::{markdown2html, markdown2html_unsafe};
49use ctb_storage::{get_asset, register_views};
50
51pub mod middleware {
52    pub mod access_log_layer;
53    pub mod compression_with_range;
54    pub mod markdown_negotiation;
55}
56
57/// Extension payload holding the original source markdown bytes for pages
58/// generated from Markdown assets.
59#[derive(Clone, Debug)]
60pub struct OriginalMarkdown(pub Vec<u8>);
61pub mod error;
62pub mod extractors;
63pub mod flexible_form;
64pub mod routes;
65pub mod server;
66pub mod session_auth;
67pub mod test_helpers;
68pub mod tls_rustls_vendored;
69pub mod webview;
70pub mod controllers {
71    pub mod admin;
72    pub mod app;
73    pub mod auth;
74    pub mod base;
75    pub mod calculator;
76    pub mod crlite;
77    pub mod debug;
78    pub mod eite;
79    pub mod graph;
80    pub mod newsletter;
81    pub mod pc_settings;
82    pub mod releases;
83    pub mod rpc;
84    pub mod search;
85    pub mod sync;
86    pub mod updates;
87    pub mod v86;
88    pub mod web;
89}
90
91// Shared application state
92#[derive(Clone)]
93pub struct AppState {
94    hbs: Arc<Handlebars<'static>>,
95    users: Arc<Mutex<HashMap<u64, SharedUser>>>,
96    pub download_sizes: Arc<Mutex<Option<HashMap<String, String>>>>,
97    /// Mock the storage directory for testing.
98    pub storage_dir_override: Option<std::path::PathBuf>,
99    pub generating_downloads: Arc<Mutex<std::collections::HashSet<String>>>,
100    pub global_session_token: Arc<Mutex<Option<String>>>,
101    pub eite_states:
102        Arc<Mutex<HashMap<u64, ctb_formats_eite::eite_state::EiteState>>>,
103}
104
105impl AppState {
106    pub fn try_new() -> Result<Self> {
107        let hbs =
108            register_views().context("Could not register Handlebars views")?;
109        Ok(Self {
110            hbs: Arc::new(hbs),
111            users: Arc::new(Mutex::new(HashMap::new())),
112            download_sizes: Arc::new(Mutex::new(None)),
113            storage_dir_override: None,
114            generating_downloads: Arc::new(Mutex::new(
115                std::collections::HashSet::new(),
116            )),
117            global_session_token: Arc::new(Mutex::new(None)),
118            eite_states: Arc::new(Mutex::new(HashMap::new())),
119        })
120    }
121}
122
123/// Trait for types that can serve as a context for a Handlebars view.
124pub trait ViewContext: Serialize {
125    /// Used to add or override keys for layouts.
126    fn with_content(self, content: String) -> serde_json::Value
127    where
128        Self: Sized,
129    {
130        // Compose self and content into a merged JSON object.
131        // Reason for fallback: serialization failure on non-object ViewContext defaults to empty JSON map
132        let mut map = serde_json::to_value(self)
133            .ok()
134            .and_then(|v| v.as_object().cloned())
135            .unwrap_or_default();
136        map.insert("content".to_string(), Value::String(content));
137        Value::Object(map)
138    }
139}
140
141// Blanket impl for all Serialize types
142impl<T: Serialize> ViewContext for T {}
143
144// --- 2. Example context structs ---
145
146#[derive(Serialize)]
147struct ErrorContext {
148    message: String,
149    message_details: String,
150}
151
152pub fn start_webui() -> u16 {
153    start_webui_server()
154}
155
156// ================ Render helpers ================
157
158fn respond_general<T: serde::Serialize>(
159    state: &AppState,
160    req: RequestState,
161    view: &str,
162    data: &T,
163) -> Response {
164    match render_page(&state.hbs, None, view.to_string(), &req, data) {
165        Ok(html) => Html(html).into_response(),
166        Err(e) => error_400(state, &req, e),
167    }
168}
169
170fn respond_page<T: serde::Serialize>(
171    state: &AppState,
172    req: RequestState,
173    view: &str,
174    data: &T,
175) -> Response {
176    match render_page(&state.hbs, Some("page"), view.to_string(), &req, data) {
177        Ok(html) => Html(html).into_response(),
178        Err(e) => error_400(state, &req, e),
179    }
180}
181
182fn respond_page_literal(
183    state: &AppState,
184    req: RequestState,
185    content: &str,
186) -> Response {
187    match render_page(
188        &state.hbs,
189        Some("page"),
190        "layouts.literal".to_string(),
191        &req,
192        &crate::json_value!({
193            "page" => content.to_string(),
194        }),
195    ) {
196        Ok(html) => Html(html).into_response(),
197        Err(e) => error_400(state, &req, e),
198    }
199}
200
201fn _respond_markdown(
202    state: &AppState,
203    req: RequestState,
204    asset_path: &str,
205    allow_unsafe: bool,
206) -> Response {
207    let md = get_asset(asset_path);
208
209    if let Some(md) = md {
210        let md_bytes = md.clone();
211        let page = if allow_unsafe {
212            // Reason for fallback: markdown parsing error on asset contents falls back to empty byte buffer
213            markdown2html_unsafe(md).unwrap_or_else(|_| Vec::new())
214        } else {
215            markdown2html(md)
216        };
217
218        let mut resp = respond_page_literal(
219            state,
220            req,
221            String::from_utf8_lossy(&page).as_ref(),
222        );
223        resp.extensions_mut().insert(OriginalMarkdown(md_bytes));
224        resp
225    } else {
226        error_404(
227            state,
228            &req,
229            format!("Markdown page not found: {asset_path}"),
230        )
231    }
232}
233
234fn respond_markdown(
235    state: &AppState,
236    req: RequestState,
237    asset_path: &str,
238) -> Response {
239    _respond_markdown(state, req, asset_path, false)
240}
241
242fn respond_markdown_unsafe(
243    state: &AppState,
244    req: RequestState,
245    asset_path: &str,
246) -> Response {
247    _respond_markdown(state, req, asset_path, true)
248}
249
250fn respond_markdown_page(
251    state: &AppState,
252    req: RequestState,
253    view: &str,
254) -> Response {
255    respond_markdown(state, req, format!("views/pages/{view}.md").as_str())
256}
257
258fn respond_markdown_page_unsafe(
259    state: &AppState,
260    req: RequestState,
261    view: &str,
262) -> Response {
263    respond_markdown_unsafe(
264        state,
265        req,
266        format!("views/pages/{view}.md").as_str(),
267    )
268}
269
270fn _respond_text_file(
271    state: &AppState,
272    req: RequestState,
273    asset_path: &str,
274) -> Response {
275    let txt = get_asset(asset_path);
276
277    if let Some(txt) = txt {
278        let content =
279            branding::replace_magic_strings(&String::from_utf8_lossy(&txt));
280        Response::builder()
281            .header(
282                axum::http::header::CONTENT_TYPE,
283                "text/plain; charset=utf-8",
284            )
285            .body(axum::body::Body::from(content))
286            // Reason for fallback: response builder failure renders 500 internal server error page
287            .unwrap_or_else(|e| error_500(state, &req, e))
288    } else {
289        error_404(state, &req, format!("Text file not found: {asset_path}"))
290    }
291}
292
293fn respond_text_file(
294    state: &AppState,
295    req: RequestState,
296    view: &str,
297) -> Response {
298    _respond_text_file(state, req, format!("web/{view}.txt").as_str())
299}
300
301fn respond_dialog<T: serde::Serialize>(
302    state: &AppState,
303    req: RequestState,
304    view: &str,
305    data: &T,
306) -> Response {
307    match render_page(
308        &state.hbs,
309        Some("dialog"),
310        format!("dialogs.{view}"),
311        &req,
312        data,
313    ) {
314        Ok(html) => Html(html).into_response(),
315        Err(e) => error_400(state, &req, e),
316    }
317}
318
319// ================ Error helpers ================
320
321fn error_500<E: std::fmt::Debug + std::fmt::Display>(
322    state: &AppState,
323    req: &RequestState,
324    e: E,
325) -> Response {
326    error_response(state, req, e, StatusCode::INTERNAL_SERVER_ERROR)
327}
328
329fn error_400<E: std::fmt::Debug + std::fmt::Display>(
330    state: &AppState,
331    req: &RequestState,
332    e: E,
333) -> Response {
334    error_response(state, req, e, StatusCode::BAD_REQUEST)
335}
336
337pub(crate) fn error_401<E: std::fmt::Debug + std::fmt::Display>(
338    state: &AppState,
339    req: &RequestState,
340    e: E,
341) -> Response {
342    error_response(state, req, e, StatusCode::UNAUTHORIZED)
343}
344
345fn error_403<E: std::fmt::Debug + std::fmt::Display>(
346    state: &AppState,
347    req: &RequestState,
348    e: E,
349) -> Response {
350    error_response(state, req, e, StatusCode::FORBIDDEN)
351}
352
353fn error_404<E: std::fmt::Debug + std::fmt::Display>(
354    state: &AppState,
355    req: &RequestState,
356    e: E,
357) -> Response {
358    error_response(state, req, e, StatusCode::NOT_FOUND)
359}
360
361fn recoverable_error<E: std::fmt::Display>(
362    state: &AppState,
363    req: RequestState,
364    e: E,
365) -> Response {
366    let accept = req.accept.clone();
367    let is_json_requested = req.is_js_request
368        || accept
369            .as_ref()
370            .is_some_and(|a| a.contains("application/json"));
371
372    if is_json_requested {
373        return error_response_json_with_details(
374            e.to_string(),
375            String::new(),
376            StatusCode::BAD_REQUEST,
377        );
378    }
379
380    // FIXME: Use JS to intercept this (if JS is running) and show a modal dialog instead of a full page
381    let mut response = respond_page(
382        state,
383        req,
384        "layouts._recoverable-error",
385        &btreemap! { "recoverable_error_message".to_string() =>  e.to_string()},
386    );
387    let status = response.status_mut();
388    *status = StatusCode::BAD_REQUEST;
389    response
390}
391
392fn error_response<E: std::fmt::Debug + std::fmt::Display>(
393    state: &AppState,
394    req: &RequestState,
395    e: E,
396    status_code: StatusCode,
397) -> Response {
398    let accept = req.accept.clone();
399    let is_json_requested = req.is_js_request
400        || accept
401            .as_ref()
402            .is_some_and(|a| a.contains("application/json"));
403
404    let (message, details) = {
405        let message = e.to_string();
406        let details = format!("{e:?}");
407        (message, details)
408    };
409
410    if is_json_requested {
411        // Return JSON error
412        return error_response_json_with_details(
413            message.clone(),
414            details.clone(),
415            status_code,
416        );
417    }
418
419    if req.route.starts_with("/releases/") {
420        let body = format!(
421            "HTTP Status: {status_code}\n{message}\ndetails:\n{details}"
422        );
423        let mut resp = Response::new(axum::body::Body::from(body));
424        resp.headers_mut().insert(
425            ::http::header::CONTENT_TYPE,
426            ::http::HeaderValue::from_static("text/plain; charset=utf-8"),
427        );
428        *resp.status_mut() = status_code;
429        return resp;
430    }
431
432    // Default or for "text/html"
433    match render_page(
434        &state.hbs,
435        Some("page"),
436        "error".to_string(),
437        req,
438        &ErrorContext {
439            message: message.clone(),
440            message_details: format!(
441                "{message}\nHTTP Status: {status_code}\ndetails:\n{details}"
442            ),
443        },
444    ) {
445        Ok(html) => {
446            let mut resp = Html(html).into_response();
447            *resp.status_mut() = status_code;
448            resp
449        }
450        Err(e) => error_response_json_with_details(
451            format!("Error rendering error response {e:?}"),
452            details,
453            status_code,
454        ),
455    }
456}
457
458/// Returns a JSON error response including message and details.
459fn error_response_json_with_details<E: std::fmt::Display>(
460    message: E,
461    details: String,
462    status_code: StatusCode,
463) -> Response {
464    let body = json!({
465        "type": "error",
466        "message": message.to_string(),
467        "message_details": details,
468    });
469    (status_code, axum::Json(body)).into_response()
470}
471
472// ================ Template rendering ================
473
474fn render_view<T: serde::Serialize>(
475    hbs: &Handlebars<'_>,
476    view: String,
477    req: &RequestState,
478    data: &T,
479) -> Result<String> {
480    hbs_render(hbs, &view, req, data).context("Could not render view")
481}
482
483fn render_page<T: serde::Serialize>(
484    hbs: &Handlebars<'_>,
485    layout: Option<&str>,
486    view: String,
487    req: &RequestState,
488    data: &T,
489) -> Result<String> {
490    let view_rendered = hbs_render(hbs, view.as_str(), req, data)?;
491
492    let layout_rendered = if let Some(layout) = layout {
493        hbs_render(
494            hbs,
495            format!("layouts.{layout}").as_str(),
496            req,
497            &data.with_content(view_rendered),
498        )
499    } else {
500        Ok(view_rendered)
501    }?;
502
503    let outer_layout = if req.is_embedded {
504        "layouts.embedded"
505    } else {
506        "layouts.app"
507    };
508
509    hbs_render(hbs, outer_layout, req, &data.with_content(layout_rendered))
510}
511
512fn hbs_render<T: serde::Serialize>(
513    hbs: &Handlebars<'_>,
514    view: &str,
515    req: &RequestState,
516    data: &T,
517) -> Result<String> {
518    // Convert data to a HashMap
519    let req_value = to_value(req).context("Could not serialize request")?;
520    let build_info = build_info();
521    let mut data_with_request = insert_key(data, "_request", req_value)?;
522
523    if let Value::Object(ref mut map) = data_with_request {
524        let branding_keys = [
525            ("ui_build_version", json!(build_info.version)),
526            ("ui_build_id", json!(build_info.build_id)),
527            ("ui_build_date", json!(build_info.build_date)),
528            ("can_restart_pc", json!(ctb_io_system::can_restart_pc())),
529            ("is_debug_build", json!(environment::is_debug_build())),
530            ("is_branded_build", json!(branding::is_branded_build())),
531            ("official_domain", json!(branding::official_domain())),
532            ("official_url", json!(branding::official_url())),
533            ("official_email", json!(branding::official_email())),
534            (
535                "official_application_name",
536                json!(branding::official_application_name()),
537            ),
538            ("domain_name", json!(branding::default_domain())),
539            ("site_url", json!(branding::default_url())),
540            ("site_name", json!(branding::application_name())),
541        ];
542        for (k, v) in branding_keys {
543            if !map.contains_key(k) {
544                map.insert(k.to_string(), v);
545            }
546        }
547    }
548
549    hbs.render(view, &data_with_request).map_err(|e| {
550        anyhow::anyhow!(
551            "Could not render template: {}\n\
552             Template: {:?}\n\
553             Line: {:?}\n\
554             Column: {:?}\n\
555             Reason: {}",
556            view,
557            e.template_name,
558            e.line_no,
559            e.column_no,
560            e.reason(),
561        )
562    })
563}
564
565// Macros for user and graph access
566
567#[macro_export]
568macro_rules! get_user {
569    ($shared_user:expr, $req:expr, $user:ident) => {
570        let $user = $shared_user.lock().await; // keep guard in scope
571    };
572}
573
574#[macro_export]
575macro_rules! get_user_and_graph {
576    ($state:expr, $req:expr, $shared_user:expr, $graph_id:expr, $user:ident, $graph:ident) => {
577        let $user = $shared_user.user.lock().await; // keep guard in scope
578        let graph = $user.get_graph_by_id($graph_id);
579        if (graph.is_none()) {
580            return error_400($state, $req, "Graph not found");
581        }
582        let $graph = graph.unwrap();
583        if !$graph.is_writable_by(&*$user) {
584            return error_403($state, $req, "User can't write to graph");
585        }
586    };
587}
588
589#[cfg(test)]
590#[allow(
591    clippy::panic,
592    clippy::expect_used,
593    clippy::unwrap_used,
594    clippy::unwrap_in_result,
595    clippy::panic_in_result_fn,
596    clippy::indexing_slicing,
597    clippy::arithmetic_side_effects,
598    reason = "Standard repository test boilerplate"
599)]
600mod tests {
601    use super::*;
602
603    #[crate::ctb_test]
604    fn test_is_send_and_sync() {
605        fn is_send_and_sync<T: Send + Sync>() {}
606        is_send_and_sync::<AppState>();
607    }
608}