arks-server 1.0.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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
//! Embedded single-binary SSR Forge Web UI for `arks serve` (E8 — GitHub/GitLab common interface).
//!
//! Compile-time embedded assets (`include_str!`), strict HTML entity escaping on every dynamic
//! value, and `Content-Security-Policy: default-src 'self'; script-src 'self'`.
//! Never interferes with Git smart/dumb HTTP (`info/refs`, `git-upload-pack`,
//! `git-receive-pack`, `objects/`, `HEAD`) or Git LFS (`info/lfs/`).
//!
//! Spec: `sot:root/v0-2-0-scope-expansion` §2.8 (E8).

mod actions;
mod admin_2fa;
mod archives;
mod auth_api;
mod code;
mod diff;
mod editor;
mod enterprise;
mod forge;
mod forge_extras;
mod highlight;
mod merge;
mod multi_repo;
mod polish;
mod projects_wiki;
pub(crate) mod store;

pub(crate) use actions::trigger_event_workflows;
pub(crate) use auth_api::check_git_http_auth;
pub(crate) use forge_extras::{
    dispatch_webhook_event, is_branch_delete_protected, is_force_push_blocked,
};
pub use multi_repo::{init_bare_repo, multi_repo_page_handler};

use crate::http::{HttpRequest, HttpResponse};
use crate::serve::PageHandler;
use arks_object::{Commit, ObjectKind};
use arks_oid::Oid;
use arks_refs::RefTarget;
use arks_repo::Repository;
use std::collections::HashSet;
use std::fs;
use std::path::PathBuf;
use std::sync::Arc;

pub const WEB_UI_CSP: &str = "default-src 'self'; script-src 'self'";
pub(crate) const STYLESHEET: &str = include_str!("../web_ui.css");
const HTMX_JS: &str = include_str!("../assets/htmx.min.js");
const DIFF2HTML_JS: &str = include_str!("../assets/diff2html.min.js");
const DIFF2HTML_CSS: &str = include_str!("../assets/diff2html.min.css");
const APP_JS: &str = include_str!("../assets/app.js");
pub(crate) const FAVICON_SVG: &str = include_str!("../assets/favicon.svg");

pub(crate) const ICON_DIR: &str = "<svg class=\"icon icon-dir\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z\"/></svg>";
pub(crate) const ICON_FILE: &str = "<svg class=\"icon icon-file\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z\"/></svg>";

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ActiveTab {
    Code,
    Issues,
    Pulls,
    Actions,
    Projects,
    Wiki,
    Security,
    Insights,
    Settings,
}

pub(crate) struct RepoContext {
    pub name: String,
    pub description: String,
    pub default_branch: String,
    pub branches: Vec<(String, Oid)>,
    pub tags: Vec<(String, Oid)>,
    pub clone_url: String,
    pub has_lfs: bool,
}

impl RepoContext {
    fn from_repo(repo: &Repository, host: Option<&str>) -> Self {
        let common = repo.common_dir();
        let name = common
            .file_name()
            .and_then(|s| s.to_str())
            .map(|n| {
                if n == ".git" {
                    common
                        .parent()
                        .and_then(|p| p.file_name())
                        .and_then(|s| s.to_str())
                        .unwrap_or("repository")
                        .to_string()
                } else {
                    n.trim_end_matches(".git").to_string()
                }
            })
            .unwrap_or_else(|| "repository".into());

        let description = fs::read_to_string(common.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 served by arks".into());

        let default_branch = head_branch_label(repo);
        let all_refs = repo.refs().list_refs("refs/").unwrap_or_default();
        let mut branches = Vec::new();
        let mut tags = Vec::new();
        for (rname, oid) in all_refs {
            if let Some(b) = rname.strip_prefix("refs/heads/") {
                branches.push((b.to_string(), oid));
            } else if let Some(t) = rname.strip_prefix("refs/tags/") {
                tags.push((t.to_string(), oid));
            }
        }
        let clone_url = format!("http://{}/", host.unwrap_or("127.0.0.1:8080"));
        let has_lfs = common.join("lfs").join("objects").is_dir();

        Self {
            name,
            description,
            default_branch,
            branches,
            tags,
            clone_url,
            has_lfs,
        }
    }
}

/// Strictly escape HTML special characters to prevent XSS.
pub fn html_escape(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for ch in input.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#x27;"),
            other => out.push(other),
        }
    }
    out
}

pub(crate) fn render_partial(status: u16, fragment: &str) -> HttpResponse {
    HttpResponse {
        status,
        content_type: "text/html; charset=utf-8".into(),
        body: fragment.as_bytes().to_vec(),
        www_authenticate: None,
        extra_headers: vec![
            ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
            ("X-Content-Type-Options".into(), "nosniff".into()),
        ],
    }
}

pub(crate) fn render_page(
    status: u16,
    ctx: &RepoContext,
    tab: ActiveTab,
    title: &str,
    main_html: &str,
) -> HttpResponse {
    let cls = |t: ActiveTab| if t == tab { "tab active" } else { "tab" };
    let open_prs = ctx
        .branches
        .iter()
        .filter(|(b, _)| b != &ctx.default_branch)
        .count();
    let arks_clone = format!("arks clone {}", ctx.clone_url);
    let git_clone = format!("git clone {}", ctx.clone_url);
    let title_esc = html_escape(title);
    let desc_esc = html_escape(&ctx.description);

    let doc = format!(
        "<!doctype html>\n<html lang=\"en\" data-theme=\"dark\">\n<head>\n<meta charset=\"utf-8\">\n\
         <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n\
         <title>{title_esc}</title>\n\
         <meta property=\"og:title\" content=\"{title_esc}\">\n\
         <meta property=\"og:description\" content=\"{desc_esc}\">\n\
         <link rel=\"alternate\" type=\"application/atom+xml\" title=\"Commits\" href=\"/commits.atom\">\n\
         <link rel=\"icon\" type=\"image/svg+xml\" href=\"/favicon.svg\">\n\
         <link rel=\"stylesheet\" href=\"/assets/diff2html.min.css\">\n\
         <link rel=\"stylesheet\" href=\"/style.css\">\n\
         <script src=\"/assets/htmx.min.js\" defer></script>\n\
         <script src=\"/assets/diff2html.min.js\" defer></script>\n\
         <script src=\"/assets/app.js\" defer></script>\n\
         </head>\n<body hx-boost=\"true\">\n\
         <header class=\"topbar\"><div class=\"topbar-inner\">\n\
         <div class=\"repo-head\">\n\
           <div class=\"repo-title\"><img src=\"/favicon.svg\" width=\"26\" height=\"26\" alt=\"arks\">\
           <a href=\"/\">{}</a><span class=\"badge\">arks serve</span>\
           <span class=\"badge badge-green\">HTMX v2</span></div>\n\
           <div class=\"head-actions\">\n\
             <button type=\"button\" class=\"btn\" data-action=\"open-cmd\">Search / ⌘K</button>\n\
             <a class=\"btn\" href=\"/notifications\">Notifications</a>\n\
             <a class=\"btn\" href=\"/releases\">Releases</a>\n\
             <a class=\"btn\" href=\"/login\">Sign in</a>\n\
             <details class=\"popover\">\n\
               <summary class=\"btn btn-primary\">&lt;&gt; Code ▾</summary>\n\
               <div class=\"popover-panel right\">\n\
                 <div class=\"popover-head\">Clone repository</div>\n\
                 <div style=\"padding:10px 12px;display:flex;flex-direction:column;gap:8px\">\n\
                   <div class=\"btn-group\">\n\
                     <button type=\"button\" class=\"btn active\" data-clone-cmd=\"{}\">arks</button>\n\
                     <button type=\"button\" class=\"btn\" data-clone-cmd=\"{}\">git</button>\n\
                   </div>\n\
                   <div style=\"display:flex;gap:6px;align-items:center\">\n\
                     <code id=\"clone-cmd-text\" class=\"input\" style=\"flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap\">{}</code>\n\
                     <button type=\"button\" class=\"btn\" data-copy-target=\"clone-cmd-text\">Copy</button>\n\
                   </div>\n\
                 </div>\n\
               </div>\n\
             </details>\n\
             <button type=\"button\" class=\"btn\" data-action=\"toggle-theme\">Theme</button>\n\
           </div>\n\
         </div>\n\
         <nav class=\"tabs\">\n\
           <a class=\"{}\" href=\"/\">Code</a>\n\
           <a class=\"{}\" href=\"/issues\">Issues</a>\n\
           <a class=\"{}\" href=\"/pulls\">Pull Requests <span class=\"counter\">{}</span></a>\n\
           <a class=\"{}\" href=\"/actions\">Actions</a>\n\
           <a class=\"{}\" href=\"/projects\">Projects</a>\n\
           <a class=\"{}\" href=\"/wiki\">Wiki</a>\n\
           <a class=\"{}\" href=\"/security\">Security</a>\n\
           <a class=\"{}\" href=\"/insights\">Insights</a>\n\
           <a class=\"{}\" href=\"/settings\">Settings</a>\n\
         </nav>\n\
         </div></header>\n\
         <main>\n{main_html}\n</main>\n\
         <div id=\"cmd-modal\" class=\"cmd-backdrop\">\n\
           <div class=\"cmd-dialog\">\n\
             <div class=\"popover-head\" style=\"display:flex;justify-content:space-between\">\n\
               <span>Quick Jump (⌘K)</span>\n\
               <button type=\"button\" class=\"btn\" data-action=\"close-cmd\">ESC</button>\n\
             </div>\n\
             <a class=\"cmd-item\" href=\"/\"><span>Code &amp; File Tree</span><span class=\"muted\">/</span></a>\n\
             <a class=\"cmd-item\" href=\"/commits/{}\"><span>Commits History</span><span class=\"muted\">/commits</span></a>\n\
             <a class=\"cmd-item\" href=\"/branches\"><span>Branches</span><span class=\"muted\">{}</span></a>\n\
             <a class=\"cmd-item\" href=\"/tags\"><span>Tags</span><span class=\"muted\">{}</span></a>\n\
             <a class=\"cmd-item\" href=\"/releases\"><span>Releases &amp; Assets</span><span class=\"muted\">/releases</span></a>\n\
             <a class=\"cmd-item\" href=\"/pulls/new\"><span>New Pull Request</span><span class=\"muted\">/pulls/new</span></a>\n\
             <a class=\"cmd-item\" href=\"/notifications\"><span>Notifications (@mentions)</span><span class=\"muted\">/notifications</span></a>\n\
             <a class=\"cmd-item\" href=\"/compare\"><span>Compare Branches</span><span class=\"muted\">/compare</span></a>\n\
             <a class=\"cmd-item\" href=\"/actions\"><span>Actions &amp; Workflows</span><span class=\"muted\">/actions</span></a>\n\
             <a class=\"cmd-item\" href=\"/security\"><span>Security &amp; Signatures</span><span class=\"muted\">/security</span></a>\n\
             <a class=\"cmd-item\" href=\"/insights\"><span>Insights &amp; Contributors</span><span class=\"muted\">/insights</span></a>\n\
             <a class=\"cmd-item\" href=\"/settings\"><span>Repository Settings</span><span class=\"muted\">/settings</span></a>\n\
             <a class=\"cmd-item\" href=\"/settings/webhooks\"><span>Webhooks (HMAC-SHA256)</span><span class=\"muted\">/settings/webhooks</span></a>\n\
             <a class=\"cmd-item\" href=\"/settings/branches\"><span>Branch Protection Rules</span><span class=\"muted\">/settings/branches</span></a>\n\
             <a class=\"cmd-item\" href=\"/settings/keys\"><span>SSH Keys</span><span class=\"muted\">/settings/keys</span></a>\n\
             <a class=\"cmd-item\" href=\"/settings/tokens\"><span>Personal Access Tokens</span><span class=\"muted\">/settings/tokens</span></a>\n\
           </div>\n\
         </div>\n\
         </body>\n</html>\n",
        html_escape(&ctx.name),
        html_escape(&arks_clone),
        html_escape(&git_clone),
        html_escape(&arks_clone),
        cls(ActiveTab::Code),
        cls(ActiveTab::Issues),
        cls(ActiveTab::Pulls),
        open_prs,
        cls(ActiveTab::Actions),
        cls(ActiveTab::Projects),
        cls(ActiveTab::Wiki),
        cls(ActiveTab::Security),
        cls(ActiveTab::Insights),
        cls(ActiveTab::Settings),
        html_escape(&ctx.default_branch),
        ctx.branches.len(),
        ctx.tags.len(),
    );
    HttpResponse {
        status,
        content_type: "text/html; charset=utf-8".into(),
        body: doc.into_bytes(),
        www_authenticate: None,
        extra_headers: vec![
            ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
            ("X-Content-Type-Options".into(), "nosniff".into()),
            ("X-Frame-Options".into(), "DENY".into()),
            ("Referrer-Policy".into(), "same-origin".into()),
        ],
    }
}

pub(crate) fn redirect_see_other(location: &str) -> HttpResponse {
    HttpResponse {
        status: 303,
        content_type: "text/plain; charset=utf-8".into(),
        body: Vec::new(),
        www_authenticate: None,
        extra_headers: vec![
            ("Location".into(), location.into()),
            ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
            ("X-Content-Type-Options".into(), "nosniff".into()),
        ],
    }
}

fn static_asset(content_type: &str, body: &[u8], immutable: bool) -> HttpResponse {
    HttpResponse {
        status: 200,
        content_type: content_type.into(),
        body: body.to_vec(),
        www_authenticate: None,
        extra_headers: vec![
            ("X-Content-Type-Options".into(), "nosniff".into()),
            (
                "Cache-Control".into(),
                if immutable {
                    "public, max-age=31536000, immutable"
                } else {
                    "public, max-age=86400"
                }
                .into(),
            ),
        ],
    }
}

/// Build a [`PageHandler`] serving the embedded SSR Web UI for `git_dir`
/// (local Actions runner disabled unless `ARKS_SERVE_ALLOW_LOCAL_ACTIONS=1`).
pub fn web_ui_page_handler(git_dir: impl Into<PathBuf>) -> PageHandler {
    let allow = std::env::var("ARKS_SERVE_ALLOW_LOCAL_ACTIONS")
        .ok()
        .as_deref()
        == Some("1");
    web_ui_page_handler_with_actions(git_dir, allow)
}

/// Build a [`PageHandler`] serving the embedded SSR Web UI with explicit opt-in
/// control over local Actions workflow execution.
pub fn web_ui_page_handler_with_actions(
    git_dir: impl Into<PathBuf>,
    allow_local_actions: bool,
) -> PageHandler {
    let dir = git_dir.into();
    Arc::new(move |req: &HttpRequest| handle_web_ui_with_actions(&dir, req, allow_local_actions))
}

/// Route browser `GET`/`POST` requests to the embedded SSR Web UI (local Actions disabled).
pub fn handle_web_ui(git_dir: &std::path::Path, req: &HttpRequest) -> Option<HttpResponse> {
    handle_web_ui_with_actions(git_dir, req, false)
}

/// Route browser `GET`/`POST` requests to the embedded SSR Web UI; returns `None` for
/// Git smart/dumb HTTP and LFS paths so protocol traffic passes through untouched.
pub fn handle_web_ui_with_actions(
    git_dir: &std::path::Path,
    req: &HttpRequest,
    allow_local_actions: bool,
) -> Option<HttpResponse> {
    let resp = handle_web_ui_inner(git_dir, req, allow_local_actions)?;
    if resp.content_type.starts_with("text/html") {
        let store = store::ForgeStore::load(git_dir);
        if let Some((user, csrf)) = auth_api::resolve_session_with_csrf(&store, req) {
            return Some(decorate_html_for_session(resp, &user, &csrf));
        }
    }
    Some(resp)
}

pub(crate) fn decorate_html_for_session(
    mut resp: HttpResponse,
    username: &str,
    csrf_token: &str,
) -> HttpResponse {
    let Ok(mut html) = String::from_utf8(resp.body.clone()) else {
        return resp;
    };
    let sign_in_btn = "<a class=\"btn\" href=\"/login\">Sign in</a>";
    if html.contains(sign_in_btn) {
        let signed_in = format!(
            "<span class=\"badge badge-green\">@{}</span>\
             <form method=\"post\" action=\"/logout\" style=\"display:inline\">\
             <button class=\"btn\" type=\"submit\">Sign out</button></form>",
            html_escape(username)
        );
        html = html.replacen(sign_in_btn, &signed_in, 1);
    }
    // Inject hidden `_csrf` field into every POST `<form ...>` tag.
    let csrf_input = format!(
        "<input type=\"hidden\" name=\"_csrf\" value=\"{}\" />",
        html_escape(csrf_token)
    );
    let mut out = String::with_capacity(html.len() + 256);
    let mut rest = html.as_str();
    while let Some(pos) = rest.find("<form") {
        out.push_str(&rest[..pos]);
        let after = &rest[pos..];
        if let Some(gt) = after.find('>') {
            let tag = &after[..=gt];
            out.push_str(tag);
            let lower_tag = tag.to_ascii_lowercase();
            if lower_tag.contains("method=\"post\"") {
                out.push_str(&csrf_input);
            }
            rest = &after[gt + 1..];
        } else {
            out.push_str(after);
            rest = "";
        }
    }
    out.push_str(rest);
    resp.body = out.into_bytes();
    resp
}

fn handle_web_ui_inner(
    git_dir: &std::path::Path,
    req: &HttpRequest,
    allow_local_actions: bool,
) -> Option<HttpResponse> {
    if !matches!(req.method.as_str(), "GET" | "POST" | "PATCH" | "DELETE") {
        return None;
    }
    let path = req.path.as_str();
    // Never intercept Git smart/dumb HTTP or LFS routes.
    if path.contains("/info/refs")
        || path.contains("/info/lfs/")
        || path.contains("/git-upload-pack")
        || path.contains("/git-receive-pack")
        || path.starts_with("/objects/")
        || path == "/HEAD"
    {
        return None;
    }
    if req.method == "GET" {
        match path {
            "/style.css" => {
                return Some(static_asset(
                    "text/css; charset=utf-8",
                    STYLESHEET.as_bytes(),
                    false,
                ));
            }
            "/assets/htmx.min.js" => {
                return Some(static_asset(
                    "application/javascript; charset=utf-8",
                    HTMX_JS.as_bytes(),
                    true,
                ));
            }
            "/assets/diff2html.min.js" => {
                return Some(static_asset(
                    "application/javascript; charset=utf-8",
                    DIFF2HTML_JS.as_bytes(),
                    true,
                ));
            }
            "/assets/diff2html.min.css" => {
                return Some(static_asset(
                    "text/css; charset=utf-8",
                    DIFF2HTML_CSS.as_bytes(),
                    true,
                ));
            }
            "/assets/app.js" => {
                return Some(static_asset(
                    "application/javascript; charset=utf-8",
                    APP_JS.as_bytes(),
                    false,
                ));
            }
            "/favicon.svg" => {
                return Some(static_asset("image/svg+xml", FAVICON_SVG.as_bytes(), false));
            }
            _ => {}
        }
    }

    let Ok(mut repo) = Repository::open(git_dir) else {
        return Some(render_partial(500, "Repository unavailable\n"));
    };
    let ctx = RepoContext::from_repo(&repo, req.host.as_deref());
    let query = req.query.as_str();

    // Unified JSON REST API (`/api/v1/*`) sharing the single atomic ForgeStore.
    if let Some(api_resp) = auth_api::handle_unified_api(&repo, &ctx, req) {
        return Some(api_resp);
    }

    if req.method == "POST" {
        // Public auth & RFC 8628 OAuth Device Flow endpoints (no prior session required).
        if path == "/register" {
            return Some(auth_api::handle_register(&repo, &ctx, req));
        }
        if path == "/login" {
            return Some(auth_api::handle_login(&repo, &ctx, req));
        }
        if path == "/logout" {
            return Some(auth_api::handle_logout(&repo, req));
        }
        if path == "/login/device/code" {
            return Some(auth_api::handle_device_code(&repo, &ctx));
        }
        if path == "/login/device" {
            return Some(auth_api::handle_device_approve(&repo, &ctx, req));
        }
        if path == "/login/oauth/access_token" {
            return Some(auth_api::handle_device_token(&repo, req));
        }

        // Enforce RBAC on all state-mutating Web UI routes when user accounts exist.
        let store_check = store::ForgeStore::load(repo.common_dir());
        if let Err(denied) = auth_api::enforce_write_rbac(&store_check, req) {
            return Some(denied);
        }
        // Archived repositories reject all write mutations except `/settings/repo` (to unarchive).
        if store_check.archived && path != "/settings/repo" {
            return Some(HttpResponse {
                status: 403,
                content_type: "text/plain; charset=utf-8".into(),
                body: b"Forbidden: repository is archived (read-only).\n".to_vec(),
                www_authenticate: None,
                extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
            });
        }

        if path == "/settings/keys" {
            return Some(auth_api::handle_add_ssh_key(&repo, &ctx, req));
        }
        if path == "/settings/tokens" {
            return Some(auth_api::handle_create_token(&repo, &ctx, req));
        }
        if let Some(rest) = path.strip_prefix("/settings/tokens/") {
            if let Some(id_str) = rest.strip_suffix("/revoke") {
                return Some(auth_api::handle_revoke_token(&repo, id_str));
            }
        }
        if path == "/settings/webhooks" {
            return Some(forge_extras::handle_create_webhook(&repo, &ctx, req));
        }
        if let Some(rest) = path.strip_prefix("/settings/webhooks/") {
            if let Some(id_str) = rest.strip_suffix("/delete") {
                return Some(forge_extras::handle_delete_webhook(&repo, id_str));
            }
            if let Some(id_str) = rest.strip_suffix("/test") {
                return Some(forge_extras::handle_test_webhook(&repo, &ctx, id_str));
            }
        }
        if path == "/settings/branches" {
            return Some(forge_extras::handle_create_branch_rule(&repo, &ctx, req));
        }
        if path == "/settings/access" {
            return Some(enterprise::handle_access_settings(&repo, req));
        }
        if path == "/notifications/mark-read" {
            return Some(enterprise::handle_mark_notifications_read(&repo, req));
        }
        if path == "/watch" {
            return Some(enterprise::handle_toggle_watch(&repo, req));
        }
        if let Some(rest) = path.strip_prefix("/settings/branches/") {
            if let Some(pat) = rest.strip_suffix("/delete") {
                return Some(forge_extras::handle_delete_branch_rule(&repo, pat));
            }
        }
        if path == "/releases" {
            return Some(forge_extras::handle_create_release(&repo, &ctx, req));
        }
        if let Some(rest) = path.strip_prefix("/releases/") {
            if let Some(id_str) = rest.strip_suffix("/assets") {
                return Some(forge_extras::handle_upload_asset(&repo, &ctx, id_str, req));
            }
        }
        if path == "/pulls/new" {
            return Some(forge_extras::handle_create_pr(&repo, &ctx, req));
        }
        if path == "/issues" {
            return Some(forge::handle_create_issue(&repo, &ctx, req));
        }
        if let Some(rest) = path.strip_prefix("/issues/") {
            if let Some((id_str, c_rest)) = rest.split_once("/comments/") {
                if let Some(idx_str) = c_rest.strip_suffix("/edit") {
                    return Some(forge::handle_edit_issue_comment(
                        &repo, id_str, idx_str, req,
                    ));
                }
                if let Some(idx_str) = c_rest.strip_suffix("/delete") {
                    return Some(forge::handle_delete_issue_comment(&repo, id_str, idx_str));
                }
            }
            if let Some(id_str) = rest.strip_suffix("/comment") {
                return Some(forge::handle_issue_comment(&repo, &ctx, id_str, req));
            }
            if let Some(id_str) = rest.strip_suffix("/edit") {
                return Some(forge::handle_edit_issue(&repo, id_str, req));
            }
            if let Some(id_str) = rest.strip_suffix("/delete") {
                return Some(forge::handle_delete_issue(&repo, id_str));
            }
            if let Some(id_str) = rest.strip_suffix("/react") {
                return Some(polish::handle_issue_react(&repo, id_str, req));
            }
            if let Some(id_str) = rest.strip_suffix("/state") {
                return Some(forge::handle_issue_state(&repo, &ctx, id_str));
            }
            if let Some(id_str) = rest.strip_suffix("/meta") {
                return Some(forge::handle_issue_meta(&repo, &ctx, id_str, req));
            }
        }
        if let Some(rest) = path.strip_prefix("/pulls/") {
            if let Some(branch) = rest.strip_suffix("/edit") {
                return Some(forge::handle_edit_pr(&repo, branch, req));
            }
            if let Some(branch) = rest.strip_suffix("/draft") {
                return Some(polish::handle_toggle_pr_draft(&repo, branch));
            }
            if let Some(branch) = rest.strip_suffix("/reviewers") {
                return Some(polish::handle_assign_pr_reviewers(&repo, branch, req));
            }
            if let Some(branch) = rest.strip_suffix("/state") {
                return Some(polish::handle_toggle_pr_state(&repo, branch));
            }
            if let Some(branch) = rest.strip_suffix("/inline-comment") {
                return Some(forge_extras::handle_inline_comment(
                    &repo, &ctx, branch, req,
                ));
            }
            if let Some((branch_part, id_part)) = rest.rsplit_once("/inline-comment/") {
                if let Some(id_str) = id_part.strip_suffix("/resolve") {
                    return Some(forge_extras::handle_resolve_inline(
                        &repo,
                        branch_part,
                        id_str,
                    ));
                }
            }
            if let Some(branch) = rest.strip_suffix("/review") {
                return Some(forge_extras::handle_pr_review_verdict(&repo, branch, req));
            }
            if let Some(branch) = rest.strip_suffix("/comment") {
                return Some(forge::handle_pr_comment(&repo, branch, req));
            }
            if let Some(branch) = rest.strip_suffix("/merge") {
                return Some(forge::handle_pr_merge(&mut repo, &ctx, branch, req));
            }
            if let Some(branch) = rest.strip_suffix("/delete-branch") {
                return Some(forge::handle_pr_delete_branch(&mut repo, &ctx, branch));
            }
        }
        if path == "/actions/run" {
            return Some(actions::handle_run_workflow(
                &repo,
                &ctx,
                req,
                allow_local_actions,
            ));
        }
        if let Some(rest) = path.strip_prefix("/actions/runs/") {
            if let Some(id_str) = rest.strip_suffix("/cancel") {
                return Some(actions::handle_cancel_workflow_run(
                    &repo,
                    &ctx,
                    id_str,
                    allow_local_actions,
                ));
            }
            if let Some(id_str) = rest.strip_suffix("/rerun") {
                return Some(polish::handle_rerun_workflow(
                    &repo,
                    &ctx,
                    id_str,
                    req,
                    allow_local_actions,
                ));
            }
            if let Some(id_str) = rest.strip_suffix("/artifacts") {
                return Some(admin_2fa::handle_upload_artifact(&repo, &ctx, id_str, req));
            }
        }
        if path == "/settings/repo" {
            return Some(polish::handle_repo_settings(&repo, req));
        }
        if path == "/settings/profile/password" {
            return Some(polish::handle_change_password(&repo, &ctx, req));
        }
        if path == "/settings/profile/sessions/revoke" {
            return Some(polish::handle_revoke_other_sessions(&repo, req));
        }
        if path == "/agents/leases/unlock" {
            return Some(polish::handle_force_unlock_lease(&repo, req));
        }
        if path == "/markdown/preview" {
            return Some(polish::handle_markdown_preview(req));
        }
        if path == "/settings/2fa" {
            return Some(admin_2fa::handle_enable_2fa(&repo, &ctx, req));
        }
        if path == "/settings/2fa/disable" {
            return Some(admin_2fa::handle_disable_2fa(&repo, &ctx, req));
        }
        if path == "/settings/secrets" {
            return Some(actions::handle_upsert_secret(&repo, req));
        }
        if let Some(rest) = path.strip_prefix("/settings/secrets/") {
            if let Some(name) = rest.strip_suffix("/delete") {
                return Some(actions::handle_delete_secret(&repo, name));
            }
        }
        if let Some(rest) = path.strip_prefix("/admin/users/") {
            if let Some(username) = rest.strip_suffix("/role") {
                if let Err(denied) = auth_api::enforce_admin_rbac(&store_check, req) {
                    return Some(denied);
                }
                return Some(admin_2fa::handle_admin_update_role(&repo, username, req));
            }
        }
        if let Some(rest) = path.strip_prefix("/edit/") {
            let (rev, subpath) = split_rev_and_path(rest);
            return Some(editor::handle_save_file(&mut repo, &ctx, rev, subpath, req));
        }
        if let Some(rest) = path.strip_prefix("/delete/") {
            let (rev, subpath) = split_rev_and_path(rest);
            return Some(editor::handle_delete_file(
                &mut repo, &ctx, rev, subpath, req,
            ));
        }
        if let Some(rev) = path.strip_prefix("/upload/") {
            if !rev.is_empty() {
                return Some(editor::handle_upload_file(&mut repo, &ctx, rev, req));
            }
        }
        if let Some(rev) = path.strip_prefix("/new/") {
            if !rev.is_empty() {
                return Some(editor::handle_create_file(&mut repo, &ctx, rev, req));
            }
        }
        if path == "/branches/create" {
            return Some(editor::handle_create_branch(&mut repo, &ctx, req));
        }
        if path == "/tags/create" {
            return Some(editor::handle_create_tag(&mut repo, &ctx, req));
        }
        if path == "/projects/cards" {
            return Some(projects_wiki::handle_create_card(&repo, &ctx, req));
        }
        if let Some(rest) = path.strip_prefix("/projects/cards/") {
            if let Some(id_str) = rest.strip_suffix("/move") {
                return Some(projects_wiki::handle_move_card(&repo, &ctx, id_str, req));
            }
            if let Some(id_str) = rest.strip_suffix("/delete") {
                return Some(projects_wiki::handle_delete_card(&repo, &ctx, id_str));
            }
        }
        if path == "/wiki" {
            return Some(projects_wiki::handle_upsert_wiki(&repo, &ctx, None, req));
        }
        if let Some(rest) = path.strip_prefix("/wiki/") {
            if let Some(slug) = rest.strip_suffix("/delete") {
                return Some(projects_wiki::handle_delete_wiki(&repo, &ctx, slug));
            }
            if !rest.is_empty() && !rest.contains('/') {
                return Some(projects_wiki::handle_upsert_wiki(
                    &repo,
                    &ctx,
                    Some(rest),
                    req,
                ));
            }
        }
        return Some(render_page(
            405,
            &ctx,
            ActiveTab::Code,
            "405 Method Not Allowed",
            "<div class=\"card\"><div class=\"card-body\">Method not allowed for this route.</div></div>",
        ));
    }

    if path == "/robots.txt" {
        return Some(HttpResponse {
            status: 200,
            content_type: "text/plain; charset=utf-8".into(),
            body: b"User-agent: *\nDisallow: /admin\nDisallow: /settings\n".to_vec(),
            www_authenticate: None,
            extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
        });
    }
    if path == "/login" {
        return Some(auth_api::render_login(&repo, &ctx));
    }
    if path == "/register" {
        return Some(auth_api::render_register(&repo, &ctx));
    }
    if path == "/login/device" {
        return Some(auth_api::render_device_approve(&repo, &ctx));
    }
    let vis_store = store::ForgeStore::load(repo.common_dir());
    if let Err(denied) = auth_api::enforce_read_visibility(&vis_store, req) {
        return Some(denied);
    }
    if path == "/settings/keys" {
        return Some(auth_api::render_ssh_keys(&repo, &ctx, req));
    }
    if path == "/settings/tokens" {
        return Some(auth_api::render_tokens(&repo, &ctx, req));
    }
    if path == "/settings/webhooks" {
        return Some(forge_extras::render_webhooks(&repo, &ctx));
    }
    if path == "/settings/branches" {
        return Some(forge_extras::render_branch_rules(&repo, &ctx));
    }
    if path == "/settings/access" {
        return Some(enterprise::render_access_settings(&repo, &ctx));
    }
    if path == "/settings/2fa" {
        return Some(admin_2fa::render_2fa_settings(&repo, &ctx, req));
    }
    if path == "/settings/secrets" {
        return Some(actions::render_secrets_settings(&repo, &ctx));
    }
    if let Some(file) = path.strip_prefix("/archive/") {
        if !file.is_empty() {
            return Some(archives::handle_archive_download(&repo, &ctx.name, file));
        }
    }
    if let Some(rest) = path.strip_prefix("/commit/") {
        if let Some(rev) = rest.strip_suffix(".patch") {
            return Some(archives::handle_commit_patch(&repo, rev, true));
        }
        if let Some(rev) = rest.strip_suffix(".diff") {
            return Some(archives::handle_commit_patch(&repo, rev, false));
        }
    }
    if let Some(rest) = path.strip_prefix("/pulls/") {
        if let Some(branch) = rest.strip_suffix(".patch") {
            return Some(archives::handle_pr_patch(
                &repo,
                &ctx.default_branch,
                branch,
                true,
            ));
        }
        if let Some(branch) = rest.strip_suffix(".diff") {
            return Some(archives::handle_pr_patch(
                &repo,
                &ctx.default_branch,
                branch,
                false,
            ));
        }
    }
    if path == "/settings/repo" {
        return Some(polish::render_repo_settings(&repo, &ctx));
    }
    if path == "/settings/profile" {
        return Some(polish::render_profile_settings(&repo, &ctx, req));
    }
    if path == "/commits.atom" {
        return Some(polish::render_commits_atom(&repo, &ctx));
    }
    if path == "/releases.atom" {
        return Some(polish::render_releases_atom(&repo, &ctx));
    }
    if let Some(rest) = path.strip_prefix("/actions/runs/") {
        if let Some(id_str) = rest.strip_suffix("/log-partial") {
            return Some(polish::render_action_log_partial(&repo, id_str));
        }
    }
    if path == "/admin/audit/verify" {
        let store_check = store::ForgeStore::load(repo.common_dir());
        if let Err(denied) = auth_api::enforce_admin_rbac(&store_check, req) {
            return Some(denied);
        }
        return Some(admin_2fa::handle_verify_audit_chain(&repo));
    }
    if path == "/admin/audit.csv" || path == "/admin/audit.jsonl" {
        let store_check = store::ForgeStore::load(repo.common_dir());
        if let Err(denied) = auth_api::enforce_admin_rbac(&store_check, req) {
            return Some(denied);
        }
        return Some(polish::export_audit_log(&repo, path.ends_with(".jsonl")));
    }
    if path == "/admin" {
        let store_check = store::ForgeStore::load(repo.common_dir());
        if let Err(denied) = auth_api::enforce_admin_rbac(&store_check, req) {
            return Some(denied);
        }
        return Some(admin_2fa::render_admin_dashboard(&repo, &ctx, query));
    }
    if path == "/agents" {
        return Some(enterprise::render_agents_dashboard(&repo, &ctx));
    }
    if path == "/releases" {
        return Some(forge_extras::render_releases(&repo, &ctx));
    }
    if let Some(rest) = path.strip_prefix("/releases/") {
        if let Some((id_str, filename)) = rest.split_once("/assets/") {
            return Some(forge_extras::handle_download_asset(&repo, id_str, filename));
        }
    }
    if path == "/pulls/new" {
        return Some(forge_extras::render_new_pr(&repo, &ctx));
    }
    if path == "/" || path.is_empty() {
        return Some(code::render_tree(&repo, &ctx, &ctx.default_branch, ""));
    }
    if path == "/search" {
        return Some(code::render_search_partial(&repo, &ctx, query));
    }
    if path == "/notifications" {
        return Some(editor::render_notifications(&repo, &ctx, query));
    }
    if let Some(rest) = path.strip_prefix("/edit/") {
        let (rev, subpath) = split_rev_and_path(rest);
        return Some(editor::render_edit_file(&repo, &ctx, rev, subpath));
    }
    if let Some(rev) = path.strip_prefix("/new/") {
        if !rev.is_empty() {
            return Some(editor::render_new_file(&repo, &ctx, rev));
        }
    }
    if path == "/branches" || path == "/refs" {
        return Some(code::render_branches(&ctx));
    }
    if path == "/tags" {
        return Some(code::render_tags(&ctx));
    }
    if path == "/commits" {
        return Some(code::render_commits(
            &repo,
            &ctx,
            &ctx.default_branch,
            query,
        ));
    }
    if let Some(rev) = path.strip_prefix("/commits/") {
        return Some(code::render_commits(&repo, &ctx, rev, query));
    }
    if let Some(oid_str) = path.strip_prefix("/commit/") {
        return Some(diff::render_commit(&repo, &ctx, oid_str));
    }
    if path == "/compare" {
        return Some(diff::render_compare(&repo, &ctx, ""));
    }
    if let Some(spec) = path.strip_prefix("/compare/") {
        return Some(diff::render_compare(&repo, &ctx, spec));
    }
    if let Some(rest) = path.strip_prefix("/tree/") {
        let (rev, subpath) = split_rev_and_path(rest);
        return Some(code::render_tree(&repo, &ctx, rev, subpath));
    }
    if let Some(rest) = path.strip_prefix("/blob/") {
        let (rev, subpath) = split_rev_and_path(rest);
        return Some(code::render_blob(&repo, &ctx, rev, subpath));
    }
    if let Some(rest) = path.strip_prefix("/blame/") {
        let (rev, subpath) = split_rev_and_path(rest);
        return Some(code::render_blame(&repo, &ctx, rev, subpath));
    }
    if let Some(rest) = path.strip_prefix("/raw/") {
        let (rev, subpath) = split_rev_and_path(rest);
        return Some(code::render_raw(&repo, rev, subpath));
    }
    if path == "/issues" {
        return Some(forge::render_issues(&repo, &ctx, query));
    }
    if let Some(id_str) = path.strip_prefix("/issues/") {
        if id_str.chars().all(|c| c.is_ascii_digit()) && !id_str.is_empty() {
            return Some(forge::render_issue_detail(&repo, &ctx, id_str));
        }
    }
    if path == "/pulls" {
        return Some(forge::render_pulls(&repo, &ctx));
    }
    if let Some(branch) = path.strip_prefix("/pulls/") {
        if !branch.is_empty() {
            return Some(forge::render_pr_detail(&repo, &ctx, branch));
        }
    }
    if path == "/actions" {
        return Some(actions::render_actions(&repo, &ctx, allow_local_actions));
    }
    if let Some(rest) = path.strip_prefix("/actions/runs/") {
        if let Some((id_str, name)) = rest.split_once("/artifacts/") {
            return Some(admin_2fa::handle_download_artifact(&repo, id_str, name));
        }
        if let Some(id_str) = rest.strip_suffix("/stream") {
            return Some(actions::render_action_run_stream(&repo, id_str));
        }
        if rest.chars().all(|c| c.is_ascii_digit()) && !rest.is_empty() {
            return Some(actions::render_action_run(&repo, &ctx, rest));
        }
    }
    if path == "/projects" {
        return Some(projects_wiki::render_projects(&repo, &ctx));
    }
    if path == "/wiki" {
        return Some(projects_wiki::render_wiki(&repo, &ctx));
    }
    if let Some(slug) = path.strip_prefix("/wiki/") {
        if !slug.is_empty() && !slug.contains('/') {
            return Some(projects_wiki::render_wiki_page(&repo, &ctx, slug));
        }
    }
    if path == "/security" {
        return Some(forge::render_security(&repo, &ctx));
    }
    if path == "/insights" {
        return Some(forge::render_insights(&repo, &ctx));
    }
    if path == "/settings" {
        return Some(forge::render_settings(&repo, &ctx));
    }

    Some(render_page(
        404,
        &ctx,
        ActiveTab::Code,
        "404 Not Found",
        "<div class=\"card\"><div class=\"card-body\">Page not found.</div></div>",
    ))
}

fn split_rev_and_path(rest: &str) -> (&str, &str) {
    match rest.split_once('/') {
        Some((r, p)) => (r, p),
        None => (rest, ""),
    }
}

pub(crate) fn head_branch_label(repo: &Repository) -> String {
    match repo.head_target() {
        Ok(RefTarget::Symbolic(s)) => s.strip_prefix("refs/heads/").unwrap_or(&s).to_string(),
        Ok(RefTarget::Direct(o)) => o.to_hex()[..7.min(o.to_hex().len())].to_string(),
        Err(_) => "HEAD".into(),
    }
}

pub(crate) fn resolve_rev_oid(repo: &Repository, rev: &str) -> Option<Oid> {
    if rev == "HEAD" {
        return repo.refs().resolve("HEAD").ok();
    }
    if let Ok(oid) = Oid::from_hex(rev) {
        if repo.get_object(&oid).is_ok() {
            return Some(oid);
        }
    }
    for candidate in [
        rev.to_string(),
        format!("refs/heads/{rev}"),
        format!("refs/tags/{rev}"),
    ] {
        if let Ok(oid) = repo.refs().resolve(&candidate) {
            return Some(oid);
        }
    }
    None
}

pub(crate) fn load_commit(repo: &Repository, oid: &Oid) -> Option<Commit> {
    let obj = repo.get_object(oid).ok()?;
    if obj.kind != ObjectKind::Commit {
        return None;
    }
    Commit::decode(&obj.payload).ok()
}

pub(crate) fn load_tree(repo: &Repository, oid: &Oid) -> Option<arks_object::Tree> {
    let obj = repo.get_object(oid).ok()?;
    if obj.kind != ObjectKind::Tree {
        return None;
    }
    arks_object::Tree::decode(&obj.payload, repo.oid_kind()).ok()
}

pub(crate) fn load_blob(repo: &Repository, oid: &Oid) -> Option<Vec<u8>> {
    let obj = repo.get_object(oid).ok()?;
    if obj.kind != ObjectKind::Blob {
        return None;
    }
    Some(obj.payload)
}

pub(crate) fn commit_has_sig(commit: &Commit) -> bool {
    commit.gpgsig.is_some()
}

pub(crate) fn collect_recent_commits(
    repo: &Repository,
    start: Oid,
    limit: usize,
) -> Vec<(Oid, Commit)> {
    let mut out = Vec::new();
    let mut visited = HashSet::new();
    let mut cur = Some(start);
    while let Some(oid) = cur {
        if out.len() >= limit || !visited.insert(oid) {
            break;
        }
        let Some(commit) = load_commit(repo, &oid) else {
            break;
        };
        let next = commit.parents.first().copied();
        out.push((oid, commit));
        cur = next;
    }
    out
}

/// Format a Unix timestamp as human-readable UTC (`YYYY-MM-DD HH:MM UTC`) plus relative age.
pub(crate) fn format_timestamp(ts: i64) -> String {
    if ts <= 0 {
        return "1970-01-01 00:00 UTC".into();
    }
    let secs_per_day = 86_400i64;
    let z = ts.div_euclid(secs_per_day) + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = (z - era * 146_097) as u64;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = (yoe as i64) + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = y + if m <= 2 { 1 } else { 0 };
    let rem = ts.rem_euclid(secs_per_day);
    let hour = rem / 3600;
    let min = (rem % 3600) / 60;

    let now = store::now_unix();
    let rel = if now >= ts {
        let diff = now - ts;
        if diff < 60 {
            "just now".into()
        } else if diff < 3600 {
            format!("{}m ago", diff / 60)
        } else if diff < 86_400 {
            format!("{}h ago", diff / 3600)
        } else {
            format!("{}d ago", diff / 86_400)
        }
    } else {
        "upcoming".into()
    };
    format!("{year:04}-{m:02}-{d:02} {hour:02}:{min:02} UTC ({rel})")
}