Skip to main content

fedimint_server_ui/dashboard/
mod.rs

1pub mod audit;
2pub(crate) mod availability;
3pub mod bitcoin;
4pub(crate) mod consensus_explorer;
5pub mod general;
6pub mod invite;
7pub mod latency;
8pub mod modules;
9
10#[cfg(test)]
11mod tests;
12
13use axum::Router;
14use axum::body::Body;
15use axum::extract::{Form, State};
16use axum::http::{StatusCode, header};
17use axum::response::{Html, IntoResponse, Response};
18use axum::routing::{get, post};
19use axum_extra::extract::cookie::CookieJar;
20use chrono::{NaiveDate, Utc};
21use consensus_explorer::consensus_explorer_view;
22use fedimint_core::config::META_FEDERATION_NAME_KEY;
23use fedimint_metrics::{Encoder, REGISTRY, TextEncoder};
24use fedimint_server_core::dashboard_ui::{DashboardApiModuleExt, DynDashboardApi};
25use fedimint_ui_common::assets::WithStaticRoutesExt;
26use fedimint_ui_common::auth::UserAuth;
27use fedimint_ui_common::{
28    CONNECTIVITY_CHECK_ROUTE, LOGIN_ROUTE, LoginInput, ROOT_ROUTE, UiState,
29    connectivity_check_handler, dashboard_layout, login_form, login_submit_response,
30    single_card_layout_with_version,
31};
32use maud::html;
33use {
34    fedimint_lnv2_server, fedimint_meta_server, fedimint_mintv2_server, fedimint_wallet_server,
35    fedimint_walletv2_server,
36};
37
38use crate::dashboard::modules::{lnv2, meta, mintv2, wallet, walletv2};
39use crate::{DOWNLOAD_BACKUP_ROUTE, EXPLORER_IDX_ROUTE, EXPLORER_ROUTE, METRICS_ROUTE};
40
41// Dashboard login form handler
42async fn login_form_handler(State(state): State<UiState<DynDashboardApi>>) -> impl IntoResponse {
43    let version = state.api.fedimintd_version().await;
44    let version_hash = state.api.fedimintd_version_hash().await;
45    Html(
46        single_card_layout_with_version(
47            "Enter Password",
48            login_form(None),
49            &version,
50            version_hash.as_deref(),
51        )
52        .into_string(),
53    )
54}
55
56// Dashboard login submit handler. Only mounted when the guardian has a
57// password configured, so `auth()` is always `Some` here.
58async fn login_submit(
59    State(state): State<UiState<DynDashboardApi>>,
60    jar: CookieJar,
61    Form(input): Form<LoginInput>,
62) -> impl IntoResponse {
63    login_submit_response(
64        state
65            .api
66            .auth_ui()
67            .expect("login route is mounted only when auth is configured"),
68        state.auth_cookie_name,
69        state.auth_cookie_value,
70        jar,
71        input,
72    )
73}
74
75// Download backup handler
76async fn download_backup(
77    State(state): State<UiState<DynDashboardApi>>,
78    user_auth: UserAuth,
79) -> impl IntoResponse {
80    let backup = state
81        .api
82        .download_guardian_config_backup(&user_auth.guardian_auth_token)
83        .await;
84    let guardian_id = state.api.guardian_id().await;
85    let guardian_names = state.api.guardian_names().await;
86    let guardian_name = guardian_names
87        .get(&guardian_id)
88        .map(String::as_str)
89        .unwrap_or_default();
90    let filename = guardian_backup_filename(Utc::now().date_naive(), guardian_name);
91
92    Response::builder()
93        .header(header::CONTENT_TYPE, "application/x-tar")
94        .header(
95            header::CONTENT_DISPOSITION,
96            format!("attachment; filename=\"{filename}\""),
97        )
98        .body(Body::from(backup.tar_archive_bytes))
99        .expect("Failed to build response")
100}
101
102/// Keep the peer component portable and safe inside a quoted HTTP filename.
103fn guardian_backup_filename(date: NaiveDate, peer_name: &str) -> String {
104    // Bound the component so the complete filename fits common filesystem limits.
105    let sanitized: String = peer_name
106        .chars()
107        .take(64)
108        .map(|c| {
109            if c.is_ascii_alphanumeric() || matches!(c, '-' | '_') {
110                c
111            } else {
112                '_'
113            }
114        })
115        .collect();
116    let peer_name = sanitized.trim_matches(['-', '_']);
117    let peer_name = if peer_name.is_empty() {
118        "guardian"
119    } else {
120        peer_name
121    };
122    format!(
123        "{}-{peer_name}-guardian-backup.tar",
124        date.format("%Y-%m-%d")
125    )
126}
127
128// Prometheus metrics handler
129async fn metrics_handler(_user_auth: UserAuth) -> impl IntoResponse {
130    let metric_families = REGISTRY.gather();
131    let result = || -> Result<String, Box<dyn std::error::Error>> {
132        let mut buffer = Vec::new();
133        let encoder = TextEncoder::new();
134        encoder.encode(&metric_families, &mut buffer)?;
135        Ok(String::from_utf8(buffer)?)
136    };
137    match result() {
138        Ok(metrics) => (
139            StatusCode::OK,
140            [(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
141            metrics,
142        )
143            .into_response(),
144        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")).into_response(),
145    }
146}
147
148// Main dashboard view
149async fn dashboard_view(
150    State(state): State<UiState<DynDashboardApi>>,
151    _auth: UserAuth,
152) -> impl IntoResponse {
153    let guardian_names = state.api.guardian_names().await;
154    let meta = if let Some(meta_module) = state.api.get_module::<fedimint_meta_server::Meta>() {
155        meta_module.get_consensus_json().await
156    } else {
157        None
158    };
159    let federation_name = resolve_federation_name(meta.as_ref(), state.api.federation_name().await);
160    let session_count = state.api.session_count().await;
161    let fedimintd_version = state.api.fedimintd_version().await;
162    let fedimintd_version_hash = state.api.fedimintd_version_hash().await;
163    let consensus_ord_latency = state.api.consensus_ord_latency().await;
164    let p2p_connection_status = state.api.p2p_connection_status().await;
165    let invite_code = state.api.federation_invite_code().await;
166    let audit_summary = state.api.federation_audit().await;
167    let bitcoin_rpc_url = state.api.bitcoin_rpc_url().await;
168    let bitcoin_rpc_status = state.api.bitcoin_rpc_status().await;
169
170    let content = html! {
171        div class="row gy-4" {
172            div class="col-md-6" {
173                (general::render(federation_name.as_deref(), session_count, &guardian_names))
174            }
175
176            div class="col-md-6" {
177                (invite::render(&invite_code, session_count))
178            }
179        }
180
181        div class="row gy-4 mt-2" {
182            div class="col-lg-6" {
183                (audit::render(&audit_summary))
184            }
185
186            div class="col-lg-6" {
187                (latency::render(consensus_ord_latency, &p2p_connection_status))
188            }
189        }
190
191        div class="row gy-4 mt-2" {
192            div class="col-12" {
193                (availability::loading())
194            }
195        }
196
197        div class="row gy-4 mt-2" {
198            div class="col-12" {
199                (bitcoin::render(bitcoin_rpc_url, &bitcoin_rpc_status))
200            }
201        }
202
203        // Conditionally add Lightning V2 UI if the module is available
204        @if let Some(lightning) = state.api.get_module::<fedimint_lnv2_server::Lightning>() {
205            div class="row gy-4 mt-2" {
206                div class="col-12" {
207                    (lnv2::render(lightning).await)
208                }
209            }
210        }
211
212        // Conditionally add Wallet V2 UI if the module is available
213        @if let Some(walletv2_module) = state.api.get_module::<fedimint_walletv2_server::Wallet>() {
214            (walletv2::render(walletv2_module).await)
215        }
216
217        // Conditionally add Mint V2 UI if the module is available
218        @if let Some(mint_module) = state.api.get_module::<fedimint_mintv2_server::Mint>() {
219            div class="row gy-4 mt-2" {
220                div class="col-12" {
221                    (mintv2::render(mint_module).await)
222                }
223            }
224        }
225
226        // Conditionally add Wallet UI if the module is available
227        @if let Some(wallet_module) = state.api.get_module::<fedimint_wallet_server::Wallet>() {
228            div class="row gy-4 mt-2" {
229                div class="col-12" {
230                    (wallet::render(wallet_module).await)
231                }
232            }
233        }
234
235        // Conditionally add Meta UI if the module is available
236        @if let Some(meta_module) = state.api.get_module::<fedimint_meta_server::Meta>() {
237            div class="row gy-4 mt-2" {
238                div class="col-12" {
239                    (meta::render(meta_module).await)
240                }
241            }
242        }
243
244        // Guardian Backup
245        div class="row gy-4 mt-2" {
246            div class="col-12" {
247                div class="card" {
248                    div class="card-header dashboard-header" { "Guardian Backup" }
249                    div class="card-body" {
250                        div class="alert alert-warning mb-3" {
251                            "You only need to download this backup once. Use it to restore your guardian if your server fails. Store this file securely since anyone with it can run your guardian node."
252                        }
253                        a href="/download-backup" class="btn btn-primary" {
254                            "Download"
255                        }
256                    }
257                }
258            }
259        }
260    };
261
262    Html(
263        dashboard_layout(
264            content,
265            &fedimintd_version,
266            fedimintd_version_hash.as_deref(),
267        )
268        .into_string(),
269    )
270    .into_response()
271}
272
273fn resolve_federation_name(
274    meta: Option<&serde_json::Value>,
275    legacy_name: Option<String>,
276) -> Option<String> {
277    meta.and_then(|json| json.get(META_FEDERATION_NAME_KEY))
278        .and_then(|value| value.as_str())
279        .map(String::from)
280        .or(legacy_name)
281}
282
283pub fn router(api: DynDashboardApi) -> Router {
284    let requires_auth = api.auth_ui().is_some();
285
286    let mut app = Router::new()
287        .route(ROOT_ROUTE, get(dashboard_view))
288        .route(EXPLORER_ROUTE, get(consensus_explorer_view))
289        .route(EXPLORER_IDX_ROUTE, get(consensus_explorer_view))
290        .route(DOWNLOAD_BACKUP_ROUTE, get(download_backup))
291        .route(METRICS_ROUTE, get(metrics_handler))
292        .route(availability::ROUTE, get(availability::view))
293        .route(
294            CONNECTIVITY_CHECK_ROUTE,
295            get(connectivity_check_handler::<DynDashboardApi>),
296        )
297        .with_static_routes();
298
299    if requires_auth {
300        app = app.route(LOGIN_ROUTE, get(login_form_handler).post(login_submit));
301    }
302
303    // routeradd LNv2 gateway routes if the module exists
304    if api
305        .get_module::<fedimint_lnv2_server::Lightning>()
306        .is_some()
307    {
308        app = app
309            .route(lnv2::LNV2_ADD_ROUTE, post(lnv2::post_add))
310            .route(lnv2::LNV2_REMOVE_ROUTE, post(lnv2::post_remove));
311    }
312
313    // Only add Meta module routes if the module exists
314    if api.get_module::<fedimint_meta_server::Meta>().is_some() {
315        app = app
316            .route(meta::META_SUBMIT_ROUTE, post(meta::post_submit))
317            .route(meta::META_SET_ROUTE, post(meta::post_set))
318            .route(meta::META_RESET_ROUTE, post(meta::post_reset))
319            .route(meta::META_DELETE_ROUTE, post(meta::post_delete))
320            .route(meta::META_MERGE_ROUTE, post(meta::post_merge))
321            .route(meta::META_VALUE_INPUT_ROUTE, get(meta::get_value_input));
322    }
323
324    // Finalize the router with state
325    app.with_state(UiState::new(api, requires_auth))
326}