arks-server 1.2.0

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
//! Multi-repository self-hosting handler (`arks serve --root <repos_dir>`).
//!
//! Serves a Forge Dashboard at `/`, creates bare repositories via `POST /new-repo`
//! (zero `git` subprocess), and routes `/<repo>/...` for both the embedded Web UI
//! and Git Smart HTTP (`/<repo>.git/info/refs`, `git-upload-pack`, `git-receive-pack`).

use super::store::parse_form_urlencoded;
use super::{WEB_UI_CSP, handle_web_ui_with_actions, html_escape, redirect_see_other};
use crate::http::{HttpRequest, HttpResponse, handle_smart_http_auth_opts};
use crate::serve::PageHandler;
use arks_repo::Repository;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;

fn is_valid_repo_name(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 80
        && !name.starts_with('.')
        && !name.contains("..")
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
}

fn resolve_repo_git_dir(root: &Path, name: &str) -> Option<PathBuf> {
    let bare_name = name.trim_end_matches(".git");
    if !is_valid_repo_name(bare_name) {
        return None;
    }
    let bare = root.join(format!("{bare_name}.git"));
    if bare.join("HEAD").is_file() {
        return Some(bare);
    }
    let non_bare = root.join(bare_name).join(".git");
    if non_bare.join("HEAD").is_file() {
        return Some(non_bare);
    }
    let direct = root.join(bare_name);
    if direct.join("HEAD").is_file() {
        return Some(direct);
    }
    None
}

fn list_repos(root: &Path) -> Vec<(String, PathBuf, String)> {
    let mut out = Vec::new();
    let Ok(rd) = fs::read_dir(root) else {
        return out;
    };
    for ent in rd.flatten() {
        let path = ent.path();
        if !path.is_dir() {
            continue;
        }
        let raw_name = ent.file_name().to_string_lossy().into_owned();
        if raw_name.starts_with('.') {
            continue;
        }
        let git_dir = if path.join("HEAD").is_file() {
            path.clone()
        } else if path.join(".git").join("HEAD").is_file() {
            path.join(".git")
        } else {
            continue;
        };
        let display = raw_name.trim_end_matches(".git").to_string();
        let desc = fs::read_to_string(git_dir.join("description"))
            .ok()
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty() && !s.starts_with("Unnamed repository"))
            .unwrap_or_else(|| "Self-hosted Git repository".into());
        out.push((display, git_dir, desc));
    }
    out.sort_by(|a, b| a.0.cmp(&b.0));
    out
}

/// Initialize a standards-compliant bare Git repository purely in Rust (zero `git` spawn).
pub fn init_bare_repo(root: &Path, name: &str, description: &str) -> Result<PathBuf, String> {
    let clean = name.trim().trim_end_matches(".git");
    if !is_valid_repo_name(clean) {
        return Err("Invalid repository name (use alphanumeric, '-', '_', '.')".into());
    }
    let target = root.join(format!("{clean}.git"));
    if target.exists() {
        return Err(format!("Repository '{clean}' already exists"));
    }
    fs::create_dir_all(target.join("objects").join("info")).map_err(|e| e.to_string())?;
    fs::create_dir_all(target.join("objects").join("pack")).map_err(|e| e.to_string())?;
    fs::create_dir_all(target.join("refs").join("heads")).map_err(|e| e.to_string())?;
    fs::create_dir_all(target.join("refs").join("tags")).map_err(|e| e.to_string())?;
    fs::write(target.join("HEAD"), "ref: refs/heads/main\n").map_err(|e| e.to_string())?;
    fs::write(
        target.join("config"),
        "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = true\n[http]\n\treceivepack = true\n",
    )
    .map_err(|e| e.to_string())?;
    let desc = if description.trim().is_empty() {
        format!("{clean} — served by arks")
    } else {
        description.trim().to_string()
    };
    fs::write(target.join("description"), format!("{desc}\n")).map_err(|e| e.to_string())?;
    Ok(target)
}

/// Build a [`PageHandler`] serving multiple Git repositories under `root_dir`.
pub fn multi_repo_page_handler(
    root_dir: impl Into<PathBuf>,
    allow_local_actions: bool,
) -> PageHandler {
    let root = root_dir.into();
    Arc::new(move |req: &HttpRequest| handle_multi_repo(&root, req, allow_local_actions))
}

pub fn handle_multi_repo(
    root: &Path,
    req: &HttpRequest,
    allow_local_actions: bool,
) -> Option<HttpResponse> {
    let path = req.path.as_str();
    let host = req.host.as_deref().unwrap_or("127.0.0.1:8080");

    if req.method == "GET" && (path == "/" || path.is_empty()) {
        let resp = render_dashboard(root, host, req);
        let global_dir = root.join(".arks-global-auth");
        let gstore = super::store::ForgeStore::load(&global_dir);
        if let Some((user, csrf)) = super::auth_api::resolve_session_with_csrf(&gstore, req) {
            return Some(super::decorate_html_for_session(resp, &user, &csrf));
        }
        return Some(resp);
    }
    if req.method == "GET" && path == "/robots.txt" {
        return Some(HttpResponse {
            status: 200,
            content_type: "text/plain; charset=utf-8".into(),
            body: b"User-agent: *\nDisallow: /admin\nDisallow: /settings\nDisallow: /api/\n"
                .to_vec(),
            www_authenticate: None,
            extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
        });
    }
    if req.method == "GET" && path == "/search" {
        return Some(render_cross_repo_search(root, &req.query, req));
    }
    // Global multi-repo auth (`/register`, `/login`, `/logout`) shared across all child repos.
    if matches!(path, "/register" | "/login" | "/logout") {
        let global_dir = root.join(".arks-global-auth");
        let _ = fs::create_dir_all(&global_dir);
        let ctx = super::RepoContext {
            name: "arks Multi-Repo Forge".into(),
            description: "Global multi-repository authentication".into(),
            default_branch: "main".into(),
            branches: Vec::new(),
            tags: Vec::new(),
            clone_url: format!("http://{host}/"),
            has_lfs: false,
        };
        if req.method == "GET" && path == "/register" {
            return Some(render_root_auth_form("Create Global Account", "/register"));
        }
        if req.method == "GET" && path == "/login" {
            return Some(render_root_auth_form("Sign in (Global)", "/login"));
        }
        if req.method == "POST" && path == "/register" {
            if super::auth_api::registration_disabled() {
                return Some(super::render_page(
                    403,
                    &ctx,
                    super::ActiveTab::Settings,
                    "Registration Disabled",
                    "Public self-registration is disabled by operator policy (ARKS_DISABLE_REGISTRATION).",
                ));
            }
            let form = parse_form_urlencoded(&req.body);
            let username = form.get("username").map(|s| s.trim()).unwrap_or("");
            let password = form.get("password").map(|s| s.as_str()).unwrap_or("");
            if username.is_empty() || password.len() < 4 {
                return Some(super::render_page(
                    400,
                    &ctx,
                    super::ActiveTab::Settings,
                    "Invalid registration",
                    "Username required and password must be at least 4 characters.",
                ));
            }
            let mut gstore = super::store::ForgeStore::lock_mut(&global_dir);
            if gstore.users.iter().any(|u| u.username == username) {
                return Some(super::render_page(
                    409,
                    &ctx,
                    super::ActiveTab::Settings,
                    "User exists",
                    "Username already exists.",
                ));
            }
            let role = if gstore.users.is_empty() {
                "admin"
            } else {
                super::auth_api::default_registration_role()
            };
            let now = super::store::now_unix();
            gstore.users.push(super::store::UserAccount {
                username: username.to_string(),
                password_hash: super::auth_api::hash_user_password(username, password),
                role: role.into(),
                ssh_keys: Vec::new(),
                created_at: now,
                totp_secret_b32: None,
                recovery_codes: Vec::new(),
            });
            let tok = super::auth_api::generate_token("arks_gsess_");
            let csrf = super::auth_api::generate_token("csrf_g_");
            gstore.sessions.push(super::store::SessionRecord {
                token: tok.clone(),
                username: username.to_string(),
                csrf_token: csrf,
                expires_at: now + 86400 * 30,
            });
            let _ = gstore.commit();
            return Some(HttpResponse {
                status: 303,
                content_type: "text/plain; charset=utf-8".into(),
                body: Vec::new(),
                www_authenticate: None,
                extra_headers: vec![
                    ("Location".into(), "/".into()),
                    (
                        "Set-Cookie".into(),
                        super::auth_api::session_cookie_header(&tok, req, false),
                    ),
                    ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
                ],
            });
        }
        if req.method == "POST" && path == "/login" {
            let form = parse_form_urlencoded(&req.body);
            let username = form.get("username").map(|s| s.trim()).unwrap_or("");
            let password = form.get("password").map(String::as_str).unwrap_or("");
            if super::auth_api::is_login_rate_limited(username) {
                let mut resp = super::render_page(
                    429,
                    &ctx,
                    super::ActiveTab::Settings,
                    "Too Many Requests",
                    "<div class=\"card\"><div class=\"card-body\">Too many failed login attempts. Try again in 60 seconds.</div></div>",
                );
                resp.extra_headers.push(("Retry-After".into(), "60".into()));
                return Some(resp);
            }
            let mut gstore = super::store::ForgeStore::lock_mut(&global_dir);
            let Some(acct) = gstore
                .users
                .iter()
                .find(|u| {
                    u.username == username
                        && super::auth_api::verify_user_password(
                            username,
                            password,
                            &u.password_hash,
                        )
                })
                .cloned()
            else {
                super::auth_api::record_login_failure(username);
                return Some(super::render_page(
                    401,
                    &ctx,
                    super::ActiveTab::Settings,
                    "Invalid credentials",
                    "<div class=\"card\"><div class=\"card-body\">Invalid username or password.</div></div>",
                ));
            };
            if let Some(ref secret) = acct.totp_secret_b32 {
                let totp = form.get("totp").map(|s| s.trim()).unwrap_or("");
                let totp_ok =
                    super::admin_2fa::verify_totp_window(secret, totp, super::store::now_unix());
                let mut used_recovery = false;
                if !totp_ok {
                    if let Some(u) = gstore.users.iter_mut().find(|u| u.username == username) {
                        if let Some(pos) = u
                            .recovery_codes
                            .iter()
                            .position(|c| super::auth_api::ct_str_eq(c, totp))
                        {
                            u.recovery_codes.remove(pos);
                            used_recovery = true;
                        }
                    }
                }
                if !totp_ok && !used_recovery {
                    super::auth_api::record_login_failure(username);
                    return Some(super::render_page(
                        401,
                        &ctx,
                        super::ActiveTab::Settings,
                        "2FA Required",
                        "<div class=\"card\"><div class=\"card-body\">Valid 6-digit TOTP 2FA code or recovery code required.</div></div>",
                    ));
                }
            }
            let now = super::store::now_unix();
            let tok = super::auth_api::generate_token("arks_gsess_");
            let csrf = super::auth_api::generate_token("csrf_g_");
            gstore.sessions.push(super::store::SessionRecord {
                token: tok.clone(),
                username: username.to_string(),
                csrf_token: csrf,
                expires_at: now + 86400 * 30,
            });
            let _ = gstore.commit();
            return Some(HttpResponse {
                status: 303,
                content_type: "text/plain; charset=utf-8".into(),
                body: Vec::new(),
                www_authenticate: None,
                extra_headers: vec![
                    ("Location".into(), "/".into()),
                    (
                        "Set-Cookie".into(),
                        super::auth_api::session_cookie_header(&tok, req, false),
                    ),
                    ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
                ],
            });
        }
        if req.method == "POST" && path == "/logout" {
            let mut gstore = super::store::ForgeStore::lock_mut(&global_dir);
            let mut revoked_tokens = Vec::new();
            if let Some(ref cookie_hdr) = req.cookie {
                for part in cookie_hdr.split(';') {
                    if let Some(val) = part.trim().strip_prefix("arks_session=") {
                        gstore.sessions.retain(|s| s.token != val);
                        revoked_tokens.push(val.to_string());
                    }
                }
            }
            let _ = gstore.commit();
            if !revoked_tokens.is_empty() {
                for (_, git_dir, _) in list_repos(root) {
                    let mut rstore = super::store::ForgeStore::lock_mut(&git_dir);
                    let before = rstore.sessions.len();
                    rstore
                        .sessions
                        .retain(|s| !revoked_tokens.iter().any(|t| t == &s.token));
                    if rstore.sessions.len() != before {
                        let _ = rstore.commit();
                    }
                }
            }
            return Some(HttpResponse {
                status: 303,
                content_type: "text/plain; charset=utf-8".into(),
                body: Vec::new(),
                www_authenticate: None,
                extra_headers: vec![
                    ("Location".into(), "/login".into()),
                    (
                        "Set-Cookie".into(),
                        super::auth_api::session_cookie_header("", req, true),
                    ),
                    ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
                ],
            });
        }
    }
    if req.method == "POST" && path == "/new-repo" {
        // Enforce RBAC when global user accounts exist so anonymous users cannot create repos.
        let global_dir = root.join(".arks-global-auth");
        let gstore = super::store::ForgeStore::load(&global_dir);
        if let Err(denied) = super::auth_api::enforce_write_rbac(&gstore, req) {
            return Some(denied);
        }
        let form = parse_form_urlencoded(&req.body);
        let name = form.get("name").map(|s| s.trim()).unwrap_or("");
        let desc = form.get("description").map(|s| s.trim()).unwrap_or("");
        return match init_bare_repo(root, name, desc) {
            Ok(_) => {
                let clean = name.trim().trim_end_matches(".git");
                Some(redirect_see_other(&format!("/{clean}/")))
            }
            Err(e) => Some(HttpResponse {
                status: 400,
                content_type: "text/plain; charset=utf-8".into(),
                body: format!("Failed to create repository: {e}\n").into_bytes(),
                www_authenticate: None,
                extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
            }),
        };
    }

    // Shared static assets at root (`/style.css`, `/assets/*`, `/favicon.svg`).
    if req.method == "GET" && path == "/style.css" {
        return Some(HttpResponse {
            status: 200,
            content_type: "text/css; charset=utf-8".into(),
            body: super::STYLESHEET.as_bytes().to_vec(),
            www_authenticate: None,
            extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
        });
    }
    if req.method == "GET" && path == "/favicon.svg" {
        return Some(HttpResponse {
            status: 200,
            content_type: "image/svg+xml".into(),
            body: super::FAVICON_SVG.as_bytes().to_vec(),
            www_authenticate: None,
            extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
        });
    }
    if req.method == "GET" && path.starts_with("/assets/") {
        if let Some((_, first_git, _)) = list_repos(root).into_iter().next() {
            return handle_web_ui_with_actions(&first_git, req, allow_local_actions);
        }
    }

    // Route `/<repo>[.git]/<subpath>` to the matching repository.
    let trimmed = path.strip_prefix('/').unwrap_or(path);
    let (repo_seg, rest) = match trimmed.split_once('/') {
        Some((r, p)) => (r, format!("/{p}")),
        None => (trimmed, "/".to_string()),
    };
    let git_dir = resolve_repo_git_dir(root, repo_seg)?;
    sync_global_auth_into_repo(root, &git_dir);

    if req.method == "POST" && rest == "/settings/repo/delete" {
        let gstore = super::store::ForgeStore::load(&root.join(".arks-global-auth"));
        let rbac_store = if gstore.users.is_empty() {
            super::store::ForgeStore::load(&git_dir)
        } else {
            gstore
        };
        if let Err(denied) = super::auth_api::enforce_admin_rbac(&rbac_store, req) {
            return Some(denied);
        }
        let form = parse_form_urlencoded(&req.body);
        let clean = repo_seg.trim_end_matches(".git");
        let confirm = form.get("confirm").map(|s| s.trim()).unwrap_or("");
        if confirm != clean {
            return Some(HttpResponse {
                status: 400,
                content_type: "text/plain; charset=utf-8".into(),
                body: format!("Confirmation mismatch: type '{clean}' to delete repository.\n")
                    .into_bytes(),
                www_authenticate: None,
                extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
            });
        }
        let _ = fs::remove_dir_all(&git_dir);
        return Some(redirect_see_other("/"));
    }

    let mut sub_req = req.clone();
    sub_req.path = rest.clone();

    // Git Smart/Dumb HTTP & LFS traffic for `/<repo>.git/...`
    if rest.contains("/info/refs")
        || rest.contains("/info/lfs/")
        || rest.contains("/git-upload-pack")
        || rest.contains("/git-receive-pack")
        || rest.starts_with("/objects/")
        || rest == "/HEAD"
    {
        let is_write = rest.contains("/git-receive-pack")
            || (rest.contains("/info/refs") && sub_req.query.contains("git-receive-pack"))
            || (rest.contains("/info/lfs/") && sub_req.method == "PUT");
        if let Err(denied) = super::auth_api::check_git_http_auth(&git_dir, &sub_req, is_write) {
            return Some(denied);
        }
        let Ok(mut repo) = Repository::open(&git_dir) else {
            return Some(HttpResponse {
                status: 500,
                content_type: "text/plain".into(),
                body: b"repository open failed\n".to_vec(),
                www_authenticate: None,
                extra_headers: Vec::new(),
            });
        };
        return match handle_smart_http_auth_opts(&mut repo, &sub_req, None, true, "http") {
            Ok(resp) => Some(resp),
            Err(e) => Some(HttpResponse {
                status: 500,
                content_type: "text/plain".into(),
                body: format!("{e}\n").into_bytes(),
                www_authenticate: None,
                extra_headers: Vec::new(),
            }),
        };
    }

    let prefix = format!("/{}", repo_seg.trim_end_matches(".git"));
    handle_web_ui_with_actions(&git_dir, &sub_req, allow_local_actions)
        .map(|resp| rewrite_response_for_repo_prefix(resp, &prefix))
}

/// Rewrite root-relative links, forms, HTMX attributes, and `Location` redirects so every
/// intra-repository navigation stays scoped under `/<repo>/...` while root static assets
/// (`/style.css`, `/assets/*`, `/favicon.svg`) stay shared at `/`.
pub(crate) fn rewrite_response_for_repo_prefix(
    mut resp: HttpResponse,
    prefix: &str,
) -> HttpResponse {
    for (k, v) in &mut resp.extra_headers {
        if k.eq_ignore_ascii_case("location") {
            *v = rewrite_repo_prefix_location(v, prefix);
        }
    }
    if resp.content_type.starts_with("text/html") {
        if let Ok(html) = String::from_utf8(resp.body.clone()) {
            resp.body = rewrite_repo_prefix_html(&html, prefix).into_bytes();
        }
    }
    resp
}

fn is_shared_root_asset(path: &str) -> bool {
    path == "/style.css"
        || path == "/favicon.svg"
        || path.starts_with("/assets/")
        || path.starts_with("//")
}

pub(crate) fn rewrite_repo_prefix_location(loc: &str, prefix: &str) -> String {
    if !loc.starts_with('/')
        || is_shared_root_asset(loc)
        || loc.starts_with(&format!("{prefix}/"))
        || loc == prefix
    {
        return loc.to_string();
    }
    format!("{prefix}{loc}")
}

pub(crate) fn rewrite_repo_prefix_html(html: &str, prefix: &str) -> String {
    let mut out = html.to_string();
    for attr in ["href=\"/", "action=\"/", "hx-get=\"/", "hx-post=\"/"] {
        let mut rebuilt = String::with_capacity(out.len() + 256);
        let mut rest = out.as_str();
        while let Some(pos) = rest.find(attr) {
            rebuilt.push_str(&rest[..pos]);
            let after_quote = &rest[pos + attr.len() - 1..]; // starts with '/'
            let end_quote = after_quote.find('"').unwrap_or(after_quote.len());
            let target = &after_quote[..end_quote];
            let attr_prefix = &attr[..attr.len() - 1]; // e.g. `href="`
            rebuilt.push_str(attr_prefix);
            if is_shared_root_asset(target)
                || target == prefix
                || target.starts_with(&format!("{prefix}/"))
            {
                rebuilt.push_str(target);
            } else {
                rebuilt.push_str(prefix);
                rebuilt.push_str(target);
            }
            rest = &after_quote[end_quote..];
        }
        rebuilt.push_str(rest);
        out = rebuilt;
    }
    out
}

fn render_dashboard(root: &Path, host: &str, req: &HttpRequest) -> HttpResponse {
    let repos = list_repos(root);
    let mut rows = String::new();
    let mut visible_count = 0usize;
    for (name, git_dir, desc) in &repos {
        sync_global_auth_into_repo(root, git_dir);
        let rstore = super::store::ForgeStore::load(git_dir);
        if !super::auth_api::can_read_repo(&rstore, req) {
            continue;
        }
        visible_count += 1;
        let clone_url = format!("http://{host}/{name}.git");
        let vis_badge = if rstore.visibility == "private" {
            " <span class=\"badge\">private</span>"
        } else {
            ""
        };
        rows.push_str(&format!(
            "<tr><td><a href=\"/{}/\"><strong>{}</strong></a>{vis_badge}\
             <div class=\"muted\">{}</div></td>\
             <td class=\"mono mr-clone-cell\"><code>arks clone {}</code></td>\
             <td class=\"mr-action-cell\"><a class=\"btn\" href=\"/{}/\">Open</a></td></tr>",
            html_escape(name),
            html_escape(name),
            html_escape(desc),
            html_escape(&clone_url),
            html_escape(name),
        ));
    }
    if rows.is_empty() {
        rows.push_str(
            "<tr><td colspan=\"3\" class=\"muted\">No repositories yet. Create your first repository below.</td></tr>",
        );
    }
    let html = format!(
        "<!doctype html><html lang=\"en\" data-theme=\"dark\"><head><meta charset=\"utf-8\">\
         <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
         <title>arks Multi-Repo Forge</title>\
         <link rel=\"stylesheet\" href=\"/style.css\"></head><body>\
         <header class=\"mr-header\">\
           <div class=\"mr-header-inner\">\
             <div class=\"mr-brand\">\
               <a href=\"/\"><strong>arks Multi-Repo Forge</strong></a>\
               <span class=\"badge badge-green\">{visible_count} repos</span>\
               <a class=\"muted\" href=\"/search\">Search</a>\
               <a class=\"muted\" href=\"/healthz\">Health</a>\
             </div>\
             <form class=\"mr-search-form\" method=\"get\" action=\"/search\">\
               <input class=\"input\" type=\"search\" name=\"q\" placeholder=\"Search across repos...\" />\
               <button class=\"btn\" type=\"submit\">Search</button>\
             </form>\
             <div class=\"mr-auth-actions\">\
               <a class=\"btn\" href=\"/login\">Sign in</a>\
               <a class=\"btn\" href=\"/register\">Register</a>\
             </div>\
           </div>\
         </header>\
         <main class=\"mr-main\">\
           <div class=\"card\"><div class=\"card-header\"><strong>Repositories</strong></div>\
           <table class=\"tree-table\">{rows}</table></div>\
           <div class=\"card\"><div class=\"card-header\"><strong>New Repository</strong></div>\
           <form class=\"card-body mr-new-repo-form\" method=\"post\" action=\"/new-repo\">\
             <input class=\"input\" type=\"text\" name=\"name\" placeholder=\"Repository name (e.g. backend)\" required />\
             <input class=\"input mr-new-repo-desc\" type=\"text\" name=\"description\" placeholder=\"Description (optional)\" />\
             <button class=\"btn btn-primary\" type=\"submit\">Create Repository</button>\
           </form></div>\
         </main></body></html>"
    );
    HttpResponse {
        status: 200,
        content_type: "text/html; charset=utf-8".into(),
        body: html.into_bytes(),
        www_authenticate: None,
        extra_headers: vec![
            ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
            ("X-Content-Type-Options".into(), "nosniff".into()),
        ],
    }
}

fn sync_global_auth_into_repo(root: &Path, git_dir: &Path) {
    use std::collections::HashMap;
    use std::sync::{OnceLock, RwLock};
    type Stamp = (u64, Option<std::time::SystemTime>);
    static SYNCED: OnceLock<RwLock<HashMap<(PathBuf, PathBuf), Stamp>>> = OnceLock::new();

    let global_dir = root.join(".arks-global-auth");
    let global_store_file = global_dir.join("arks-forge").join("store.json");
    let Ok(meta) = fs::metadata(&global_store_file) else {
        return;
    };
    let stamp: Stamp = (meta.len(), meta.modified().ok());
    let key = (global_dir.clone(), git_dir.to_path_buf());
    let map = SYNCED.get_or_init(|| RwLock::new(HashMap::new()));
    if map
        .read()
        .unwrap_or_else(|e| e.into_inner())
        .get(&key)
        .copied()
        == Some(stamp)
    {
        return;
    }

    let gstore = super::store::ForgeStore::load(&global_dir);
    let mut rstore = super::store::ForgeStore::lock_mut(git_dir);
    let mut changed = false;
    for u in &gstore.users {
        if let Some(existing) = rstore.users.iter_mut().find(|e| e.username == u.username) {
            if existing.password_hash != u.password_hash
                || existing.role != u.role
                || existing.totp_secret_b32 != u.totp_secret_b32
            {
                existing.password_hash = u.password_hash.clone();
                existing.role = u.role.clone();
                existing.totp_secret_b32 = u.totp_secret_b32.clone();
                existing.recovery_codes = u.recovery_codes.clone();
                changed = true;
            }
        } else {
            rstore.users.push(u.clone());
            changed = true;
        }
    }
    let before_sessions = rstore.sessions.len();
    rstore.sessions.retain(|s| {
        !s.token.starts_with("arks_gsess_") || gstore.sessions.iter().any(|gs| gs.token == s.token)
    });
    if rstore.sessions.len() != before_sessions {
        changed = true;
    }
    for s in gstore.sessions {
        if !rstore.sessions.iter().any(|e| e.token == s.token) {
            rstore.sessions.push(s);
            changed = true;
        }
    }
    for p in gstore.pats {
        if !rstore.pats.iter().any(|e| e.token_hash == p.token_hash) {
            rstore.pats.push(p);
            changed = true;
        }
    }
    if changed {
        let _ = rstore.commit();
    }
    map.write()
        .unwrap_or_else(|e| e.into_inner())
        .insert(key, stamp);
}

fn render_root_auth_form(title: &str, action: &str) -> HttpResponse {
    let totp_input = if action == "/login" {
        "<input class=\"input\" type=\"text\" name=\"totp\" placeholder=\"2FA TOTP or recovery code (if enabled)\" />"
    } else {
        ""
    };
    let html = format!(
        "<!doctype html><html lang=\"en\" data-theme=\"dark\"><head><meta charset=\"utf-8\">\
         <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
         <title>{title} — arks</title><link rel=\"stylesheet\" href=\"/style.css\"></head><body>\
         <main class=\"mr-auth-main\">\
           <div class=\"card\"><div class=\"card-header\"><strong>{title}</strong></div>\
           <form class=\"card-body mr-auth-form\" method=\"post\" action=\"{action}\">\
             <input class=\"input\" type=\"text\" name=\"username\" placeholder=\"Username\" required />\
             <input class=\"input\" type=\"password\" name=\"password\" placeholder=\"Password\" required />\
             {totp_input}\
             <button class=\"btn btn-primary\" type=\"submit\">{title}</button>\
           </form></div>\
         </main></body></html>"
    );
    HttpResponse {
        status: 200,
        content_type: "text/html; charset=utf-8".into(),
        body: html.into_bytes(),
        www_authenticate: None,
        extra_headers: vec![
            ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
            ("X-Content-Type-Options".into(), "nosniff".into()),
        ],
    }
}

fn render_cross_repo_search(root: &Path, query: &str, req: &HttpRequest) -> HttpResponse {
    let params = parse_form_urlencoded(query.as_bytes());
    let q = params.get("q").map(|s| s.trim()).unwrap_or("");
    let q_low = q.to_ascii_lowercase();
    let repos = list_repos(root);
    let mut rows = String::new();
    let mut hits = 0usize;

    if !q_low.is_empty() {
        for (repo_name, git_dir, _) in &repos {
            sync_global_auth_into_repo(root, git_dir);
            let store = super::store::ForgeStore::load(git_dir);
            if !super::auth_api::can_read_repo(&store, req) {
                continue;
            }
            for iss in &store.issues {
                if iss.title.to_ascii_lowercase().contains(&q_low)
                    || iss.body.to_ascii_lowercase().contains(&q_low)
                {
                    hits += 1;
                    rows.push_str(&format!(
                        "<tr><td><span class=\"badge\">issue</span> \
                         <a href=\"/{}/issues/{}\"><strong>{} #{} — {}</strong></a></td></tr>",
                        html_escape(repo_name),
                        iss.id,
                        html_escape(repo_name),
                        iss.id,
                        html_escape(&iss.title),
                    ));
                }
            }
            if let Ok(repo) = Repository::open(git_dir) {
                let default_br = super::head_branch_label(&repo);
                if let Some(oid) = super::resolve_rev_oid(&repo, &default_br) {
                    if let Ok(tree) = arks_repo::commit_tree_map(&repo, &oid) {
                        for (path, _) in tree {
                            if path.to_ascii_lowercase().contains(&q_low) {
                                hits += 1;
                                rows.push_str(&format!(
                                    "<tr><td><span class=\"badge badge-green\">file</span> \
                                     <a href=\"/{}/blob/{}/{}\"><strong>{}/{}</strong></a></td></tr>",
                                    html_escape(repo_name),
                                    html_escape(&default_br),
                                    html_escape(&path),
                                    html_escape(repo_name),
                                    html_escape(&path),
                                ));
                            }
                        }
                    }
                }
            }
        }
    }
    if rows.is_empty() {
        rows.push_str("<tr><td class=\"muted\">No cross-repository matches found.</td></tr>");
    }
    let html = format!(
        "<!doctype html><html lang=\"en\" data-theme=\"dark\"><head><meta charset=\"utf-8\">\
         <title>Global Search — arks</title><link rel=\"stylesheet\" href=\"/style.css\"></head><body>\
         <main class=\"mr-main\">\
           <h1>Global Cross-Repo Search <span class=\"badge badge-green\">{hits} hits</span></h1>\
           <form class=\"mr-search-bar\" method=\"get\" action=\"/search\">\
             <input class=\"input\" type=\"text\" name=\"q\" value=\"{}\" placeholder=\"Search files &amp; issues across all repos...\" />\
             <button class=\"btn btn-primary\" type=\"submit\">Search</button>\
           </form>\
           <div class=\"card\"><table class=\"tree-table\">{rows}</table></div>\
         </main></body></html>",
        html_escape(q),
    );
    HttpResponse {
        status: 200,
        content_type: "text/html; charset=utf-8".into(),
        body: html.into_bytes(),
        www_authenticate: None,
        extra_headers: vec![
            ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
            ("X-Content-Type-Options".into(), "nosniff".into()),
        ],
    }
}