ctb_io_webui/controllers/
web.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//! Controller for general web pages outside of the app UI itself.
21
22use axum::{extract::State, response::Response};
23use ctb_io_environment;
24use ctb_utilities::branding::newsletter_url;
25use ctb_utilities::ipc::service_traits::storage::UserDto;
26use ctb_utilities::{__ctb_ipc_ctx, __ctb_ipcb_get, ipcb};
27
28// for `oneshot`
29
30use crate::controllers::base::redirect_temporary;
31use crate::utilities::pc_settings::{PcSettingStrKey, get_str_setting};
32use crate::{
33    AppState, RequestState, respond_general, respond_markdown_page_unsafe,
34};
35use crate::{json_value, respond_text_file};
36
37pub async fn get_index(
38    State(state): State<AppState>,
39    headers: axum::http::HeaderMap,
40    req: RequestState,
41) -> Response {
42    let mut sizes_lock = state.download_sizes.lock().await;
43    let sizes = if let Some(s) = &*sizes_lock {
44        s.clone()
45    } else {
46        let s = super::releases::calculate_download_sizes(
47            state.storage_dir_override.clone(),
48        )
49        .await;
50        *sizes_lock = Some(s.clone());
51        s
52    };
53
54    let user_agent = headers
55        .get(axum::http::header::USER_AGENT)
56        .and_then(|v| v.to_str().ok())
57        // Reason for fallback: User-Agent header missing defaults string to empty string
58        .unwrap_or("");
59
60    let os = ctb_formats_useragent::detect_os(user_agent);
61    let is_freebsd = user_agent.to_ascii_lowercase().contains("freebsd");
62
63    let (
64        linux_expanded,
65        windows_expanded,
66        freebsd_expanded,
67        macos_expanded,
68    );
69    let (linux_class, windows_class, freebsd_class, macos_class);
70
71    if is_freebsd {
72        linux_expanded = "";
73        windows_expanded = "";
74        freebsd_expanded = "open";
75        macos_expanded = "";
76        freebsd_class = "order-1";
77        linux_class = "order-2";
78        windows_class = "order-3";
79        macos_class = "order-4";
80    } else {
81        match os {
82            ctb_formats_useragent::OperatingSystem::Linux => {
83                linux_expanded = "open";
84                windows_expanded = "";
85                freebsd_expanded = "";
86                macos_expanded = "";
87                linux_class = "order-1";
88                windows_class = "order-2";
89                freebsd_class = "order-3";
90                macos_class = "order-4";
91            }
92            ctb_formats_useragent::OperatingSystem::Windows => {
93                linux_expanded = "";
94                windows_expanded = "open";
95                freebsd_expanded = "";
96                macos_expanded = "";
97                windows_class = "order-1";
98                linux_class = "order-2";
99                freebsd_class = "order-3";
100                macos_class = "order-4";
101            }
102            ctb_formats_useragent::OperatingSystem::MacOS => {
103                linux_expanded = "";
104                windows_expanded = "";
105                freebsd_expanded = "";
106                macos_expanded = "open";
107                macos_class = "order-1";
108                linux_class = "order-2";
109                windows_class = "order-3";
110                freebsd_class = "order-4";
111            }
112            ctb_formats_useragent::OperatingSystem::Unknown => {
113                linux_expanded = "";
114                windows_expanded = "";
115                freebsd_expanded = "";
116                macos_expanded = "";
117                linux_class = "order-1";
118                windows_class = "order-2";
119                freebsd_class = "order-3";
120                macos_class = "order-4";
121            }
122        }
123    }
124
125    // Reason for fallback: release public key setting unconfigured defaults to empty string
126    let release_public_key =
127        get_str_setting(PcSettingStrKey::ReleasePublicKey).unwrap_or_default();
128    let server_url = get_str_setting(PcSettingStrKey::ServerUrl)
129        // Reason for fallback: server URL setting unconfigured defaults to DEFAULT_SERVER_URL constant
130        .unwrap_or_else(|| {
131            crate::utilities::pc_settings::DEFAULT_SERVER_URL.to_string()
132        });
133
134    respond_general(
135        &state,
136        req,
137        "index",
138        &json_value!({
139            "sizes" => sizes,
140            "linux_expanded" => linux_expanded,
141            "windows_expanded" => windows_expanded,
142            "freebsd_expanded" => freebsd_expanded,
143            "macos_expanded" => macos_expanded,
144            "linux_class" => linux_class,
145            "windows_class" => windows_class,
146            "freebsd_class" => freebsd_class,
147            "macos_class" => macos_class,
148            "release_public_key" => release_public_key,
149            "server_url" => server_url,
150        }),
151    )
152}
153
154pub async fn privacy_policy(
155    State(state): State<AppState>,
156    req: RequestState,
157) -> Response {
158    // Content embedded as assets should be safe
159    respond_markdown_page_unsafe(&state, req, "privacy-policy")
160}
161
162pub async fn security_report_policy(
163    State(state): State<AppState>,
164    req: RequestState,
165) -> Response {
166    // Content embedded as assets should be safe
167    respond_markdown_page_unsafe(&state, req, "security-report-policy")
168}
169
170pub async fn robots_txt(
171    State(state): State<AppState>,
172    req: RequestState,
173) -> Response {
174    respond_text_file(&state, req, "robots")
175}
176
177pub async fn security_txt(
178    State(state): State<AppState>,
179    req: RequestState,
180) -> Response {
181    respond_text_file(&state, req, "security")
182}
183
184pub async fn llms_txt(
185    State(state): State<AppState>,
186    req: RequestState,
187) -> Response {
188    respond_text_file(&state, req, "llms")
189}
190
191use crate::session_auth::AuthenticatedUser;
192use crate::utilities::feature;
193
194pub async fn subscribe_newsletter(
195    State(_state): State<AppState>,
196    req: RequestState,
197) -> Response {
198    redirect_temporary(req.is_js_request, newsletter_url())
199}
200
201pub async fn subscribe_account(
202    State(state): State<AppState>,
203    user: AuthenticatedUser,
204    req: RequestState,
205) -> Response {
206    if !feature("login") {
207        return redirect_temporary(req.is_js_request, "/");
208    }
209
210    let u = user.user.lock().await;
211    let user_id = u.local_id();
212    let username = u.name();
213
214    // Reason for fallback: system clock time prior to UNIX epoch defaults timestamp to 0 seconds
215    let now = std::time::SystemTime::now()
216        .duration_since(std::time::UNIX_EPOCH)
217        .unwrap_or_default()
218        .as_secs();
219
220    let dto = ipcb!(storage)
221        .get_user_by_id_b(user_id)
222        .ok()
223        .flatten()
224        // Reason for fallback: user DTO lookup failure constructs fallback UserDto struct with empty defaults
225        .unwrap_or_else(|| UserDto {
226            id: user_id,
227            username: username.clone(),
228            uuid: Vec::new(),
229            auth: None,
230            display_name: None,
231            picture: None,
232            key_encryption_key_params: None,
233            wrapped_dek: None,
234            pubkey: None,
235            subscription_expiry: None,
236            token_quota: None,
237            remote_status: None,
238        });
239    // Reason for fallback: user DTO missing subscription_expiry defaults expiry to 0 timestamp
240    let expiry = dto.subscription_expiry.unwrap_or(0);
241    // Reason for fallback: user DTO missing token_quota defaults quota to 0
242    let quota = dto.token_quota.unwrap_or(0);
243    let is_subscribed = expiry > now;
244
245    let expiry_formatted = if is_subscribed {
246        // Reason for fallback: subscription expiry timestamp i64 conversion overflow defaults to 0 timestamp
247        ctb_utilities::jiff::Timestamp::from_second(
248            i64::try_from(expiry).unwrap_or(0),
249        )
250        .ok()
251        .map(|dt| dt.strftime("%Y-%m-%d %H:%M:%S UTC").to_string())
252    } else {
253        None
254    };
255
256    respond_general(
257        &state,
258        req,
259        "subscribe",
260        &json_value!({
261            "username" => username,
262            "is_subscribed" => is_subscribed,
263            "expiry_formatted" => expiry_formatted,
264            "quota" => quota,
265        }),
266    )
267}
268
269#[derive(serde::Deserialize)]
270pub struct SubscribeForm {
271    _payment_type: String,
272    _card_number: Option<String>,
273    _check_routing: Option<String>,
274    _check_account: Option<String>,
275}
276
277pub async fn post_subscribe_account(
278    State(_state): State<AppState>,
279    user: AuthenticatedUser,
280    req: RequestState,
281    axum::Form(_input): axum::Form<SubscribeForm>,
282) -> Response {
283    if !feature("login") {
284        return redirect_temporary(req.is_js_request, "/");
285    }
286
287    let u = user.user.lock().await;
288    let user_id = u.local_id();
289
290    // Reason for fallback: system clock time prior to UNIX epoch defaults timestamp to 0 seconds
291    let now = std::time::SystemTime::now()
292        .duration_since(std::time::UNIX_EPOCH)
293        .unwrap_or_default()
294        .as_secs();
295
296    // 30 days subscription duration
297    let expiry = now.saturating_add(30 * 24 * 60 * 60);
298
299    if let Ok(Some(mut dto)) = ipcb!(storage).get_user_by_id_b(user_id) {
300        dto.subscription_expiry = Some(expiry);
301        dto.token_quota = Some(100);
302        let _ = ipcb!(storage).update_user_b(dto);
303    }
304
305    redirect_temporary(req.is_js_request, "/home/subscribe")
306}
307
308/// Response returned by the `/api/ip` endpoint.
309#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
310pub struct ClientIpResponse {
311    /// Detected public IP address of the client.
312    pub ip: String,
313    /// Server's current system time in nanoseconds since Unix epoch.
314    pub server_time_nanos: u128,
315}
316
317/// Endpoint handler for `GET /api/ip`.
318///
319/// Detects the remote client IP from reverse proxy headers (e.g.
320/// `CF-Connecting-IP`, `X-Forwarded-For`, `X-Real-IP`) or
321/// `ConnectInfo<SocketAddr>`, and reports the current server system time in
322/// nanoseconds.
323pub async fn get_client_ip(
324    req: axum::extract::Request,
325) -> axum::Json<ClientIpResponse> {
326    let headers = req.headers();
327    let cloudflare_ip = headers
328        .get("CF-Connecting-IP")
329        .and_then(|h| h.to_str().ok())
330        .map(str::trim);
331
332    let x_forwarded_for = headers
333        .get("X-Forwarded-For")
334        .and_then(|h| h.to_str().ok())
335        .and_then(|s| s.split(',').next())
336        .map(str::trim);
337
338    let x_real_ip = headers
339        .get("X-Real-IP")
340        .and_then(|h| h.to_str().ok())
341        .map(str::trim);
342
343    let connect_ip = req
344        .extensions()
345        .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
346        .map(|c| c.0.ip().to_string());
347
348    // Reason for fallback: when no remote address or proxy header is available,
349    // default to loopback
350    let ip = cloudflare_ip
351        .or(x_forwarded_for)
352        .or(x_real_ip)
353        .map(ToString::to_string)
354        .or(connect_ip)
355        .unwrap_or_else(|| "127.0.0.1".to_string());
356
357    let server_time_nanos = ctb_io_environment::unix_system_time_now();
358
359    axum::Json(ClientIpResponse {
360        ip,
361        server_time_nanos,
362    })
363}
364
365#[cfg(test)]
366#[allow(
367    clippy::panic,
368    clippy::expect_used,
369    clippy::unwrap_used,
370    clippy::unwrap_in_result,
371    clippy::panic_in_result_fn,
372    clippy::indexing_slicing,
373    clippy::arithmetic_side_effects,
374    reason = "Standard repository test boilerplate"
375)]
376mod tests {
377    use ctb_utilities::branding::newsletter_url;
378
379    use crate::test_helpers::{
380        assert_eq_or_print_body, assert_or_print_body, test_get_no_login,
381    };
382
383    #[crate::ctb_test("tokio")]
384    async fn can_get_index() {
385        let (status, body) = test_get_no_login("/").await;
386        assert_eq_or_print_body(status, 200, &body);
387        assert_or_print_body(
388            body.contains(&format!(
389                "<title>{}</title>",
390                crate::utilities::branding::application_name()
391            )),
392            &body,
393        );
394    }
395
396    #[crate::ctb_test("tokio")]
397    async fn test_index_os_detection() {
398        use crate::test_helpers::{test_app, test_request};
399        use axum::http::{HeaderMap, Method};
400
401        let (_state, app) = test_app();
402
403        // 1. Linux User-Agent
404        let mut headers_linux = HeaderMap::new();
405        headers_linux.insert(
406            "User-Agent",
407            "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/119.0"
408                .parse()
409                .unwrap(),
410        );
411        let (status, body) = test_request::<()>(
412            &app,
413            Method::GET,
414            "/",
415            Some(headers_linux),
416            None,
417            None,
418            None,
419            None,
420        )
421        .await;
422        assert_eq!(status, 200);
423        assert!(body.contains("details class=\"p-4 order-1\" open"));
424        assert!(body.contains("details class=\"p-4 order-2\""));
425
426        // 2. Windows User-Agent
427        let mut headers_windows = HeaderMap::new();
428        headers_windows.insert(
429            "User-Agent",
430            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
431                .parse()
432                .unwrap(),
433        );
434        let (status, body) = test_request::<()>(
435            &app,
436            Method::GET,
437            "/",
438            Some(headers_windows),
439            None,
440            None,
441            None,
442            None,
443        )
444        .await;
445        assert_eq!(status, 200);
446        assert!(body.contains("details class=\"p-4 order-1\" open"));
447
448        // 3. macOS User-Agent
449        let mut headers_macos = HeaderMap::new();
450        headers_macos.insert(
451            "User-Agent",
452            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15"
453                .parse()
454                .unwrap(),
455        );
456        let (status, body) = test_request::<()>(
457            &app,
458            Method::GET,
459            "/",
460            Some(headers_macos),
461            None,
462            None,
463            None,
464            None,
465        )
466        .await;
467        assert_eq!(status, 200);
468        assert!(body.contains("details class=\"p-4 order-1\" open"));
469
470        // FreeBSD User-Agent prioritizes and expands FreeBSD section
471        let mut headers_freebsd = axum::http::HeaderMap::new();
472        headers_freebsd.insert(
473            axum::http::header::USER_AGENT,
474            "Mozilla/5.0 (X11; FreeBSD amd64; rv:128.0) Gecko/20100101 Firefox/128.0"
475                .parse()
476                .unwrap(),
477        );
478        let (status_bsd, body_bsd) = test_request::<()>(
479            &app,
480            Method::GET,
481            "/",
482            Some(headers_freebsd),
483            None,
484            None,
485            None,
486            None,
487        )
488        .await;
489        assert_eq!(status_bsd, 200);
490        assert!(body_bsd.contains(
491            "<details class=\"p-4 order-1\" open>\n                        <summary class=\"cursor-pointer\">FreeBSD</summary>"
492        ));
493    }
494
495    #[crate::ctb_test("tokio")]
496    async fn test_text_routes() {
497        use crate::test_helpers::TestApp;
498        use axum::http::{Method, StatusCode};
499        let test_app = TestApp::new();
500
501        // 1. robots.txt
502        let resp = test_app
503            .request_get_response::<()>(
504                Method::GET,
505                "/robots.txt",
506                None,
507                None,
508                None,
509                None,
510            )
511            .await;
512        assert_eq!(resp.status(), StatusCode::OK);
513        assert_eq!(
514            resp.headers()
515                .get("content-type")
516                .unwrap()
517                .to_str()
518                .unwrap(),
519            "text/plain; charset=utf-8"
520        );
521        let body = crate::test_helpers::body_to_text(resp).await;
522        assert!(body.contains("User-agent: *"));
523
524        // 2. security.txt
525        let resp = test_app
526            .request_get_response::<()>(
527                Method::GET,
528                "/security.txt",
529                None,
530                None,
531                None,
532                None,
533            )
534            .await;
535        assert_eq!(resp.status(), StatusCode::OK);
536        assert_eq!(
537            resp.headers()
538                .get("content-type")
539                .unwrap()
540                .to_str()
541                .unwrap(),
542            "text/plain; charset=utf-8"
543        );
544        let body = crate::test_helpers::body_to_text(resp).await;
545        assert!(body.contains("Contact:"));
546
547        // 3. .well-known/security.txt
548        let resp = test_app
549            .request_get_response::<()>(
550                Method::GET,
551                "/.well-known/security.txt",
552                None,
553                None,
554                None,
555                None,
556            )
557            .await;
558        assert_eq!(resp.status(), StatusCode::OK);
559        let body = crate::test_helpers::body_to_text(resp).await;
560        assert!(body.contains("Contact:"));
561
562        // 4. llms.txt
563        let resp = test_app
564            .request_get_response::<()>(
565                Method::GET,
566                "/llms.txt",
567                None,
568                None,
569                None,
570                None,
571            )
572            .await;
573        assert_eq!(resp.status(), StatusCode::OK);
574        assert_eq!(
575            resp.headers()
576                .get("content-type")
577                .unwrap()
578                .to_str()
579                .unwrap(),
580            "text/plain; charset=utf-8"
581        );
582        let body = crate::test_helpers::body_to_text(resp).await;
583        assert!(body.contains("# "));
584    }
585
586    #[crate::ctb_test("tokio")]
587    async fn test_subscribe_newsletter_redirect() {
588        use crate::test_helpers::test_get_redirect_no_login;
589        use axum::http::StatusCode;
590
591        let (status, location) = test_get_redirect_no_login("/subscribe").await;
592        assert!(status.is_redirection(), "Status was not redirect: {status}");
593        assert_eq!(status, StatusCode::SEE_OTHER);
594        assert_eq!(location, newsletter_url());
595    }
596
597    #[crate::ctb_test("tokio")]
598    async fn test_get_client_ip() {
599        use super::ClientIpResponse;
600        use crate::test_helpers::TestApp;
601        use axum::http::{HeaderMap, HeaderValue, Method, StatusCode};
602
603        let test_app = TestApp::new();
604
605        // 1. Basic request
606        let resp = test_app
607            .request_get_response::<()>(
608                Method::GET,
609                "/api/ip",
610                None,
611                None,
612                None,
613                None,
614            )
615            .await;
616        assert_eq!(resp.status(), StatusCode::OK);
617        let body = crate::test_helpers::body_to_text(resp).await;
618        let parsed: ClientIpResponse = serde_json::from_str(&body)
619            .expect("Failed to parse ClientIpResponse");
620        assert!(!parsed.ip.is_empty());
621        assert!(parsed.server_time_nanos > 0);
622
623        // 2. CF-Connecting-IP header
624        let mut headers = HeaderMap::new();
625        headers.insert(
626            "CF-Connecting-IP",
627            HeaderValue::from_static("198.51.100.25"),
628        );
629        let resp = test_app
630            .request_get_response::<()>(
631                Method::GET,
632                "/api/ip",
633                Some(headers),
634                None,
635                None,
636                None,
637            )
638            .await;
639        assert_eq!(resp.status(), StatusCode::OK);
640        let body = crate::test_helpers::body_to_text(resp).await;
641        let parsed: ClientIpResponse = serde_json::from_str(&body)
642            .expect("Failed to parse ClientIpResponse");
643        assert_eq!(parsed.ip, "198.51.100.25");
644
645        // 3. X-Forwarded-For header
646        let mut headers = HeaderMap::new();
647        headers.insert(
648            "X-Forwarded-For",
649            HeaderValue::from_static("203.0.113.50, 10.0.0.1"),
650        );
651        let resp = test_app
652            .request_get_response::<()>(
653                Method::GET,
654                "/api/ip",
655                Some(headers),
656                None,
657                None,
658                None,
659            )
660            .await;
661        assert_eq!(resp.status(), StatusCode::OK);
662        let body = crate::test_helpers::body_to_text(resp).await;
663        let parsed: ClientIpResponse = serde_json::from_str(&body)
664            .expect("Failed to parse ClientIpResponse");
665        assert_eq!(parsed.ip, "203.0.113.50");
666    }
667}