Skip to main content

arks_server/web_ui/
mod.rs

1//! Embedded single-binary SSR Forge Web UI for `arks serve` (E8 — GitHub/GitLab common interface).
2//!
3//! Compile-time embedded assets (`include_str!`), strict HTML entity escaping on every dynamic
4//! value, and `Content-Security-Policy: default-src 'self'; script-src 'self'`.
5//! Never interferes with Git smart/dumb HTTP (`info/refs`, `git-upload-pack`,
6//! `git-receive-pack`, `objects/`, `HEAD`) or Git LFS (`info/lfs/`).
7//!
8//! Spec: `sot:root/v0-2-0-scope-expansion` §2.8 (E8).
9
10mod actions;
11mod admin_2fa;
12mod archives;
13mod auth_api;
14mod code;
15mod diff;
16mod editor;
17mod enterprise;
18mod forge;
19mod forge_extras;
20mod highlight;
21mod merge;
22mod multi_repo;
23mod polish;
24mod projects_wiki;
25pub(crate) mod store;
26
27pub(crate) use actions::trigger_event_workflows;
28pub(crate) use auth_api::check_git_http_auth;
29pub use forge_extras::{
30    LoopbackWebhookGuard, allow_loopback_webhooks_for_repo, is_ssrf_blocked_url,
31};
32pub(crate) use forge_extras::{
33    dispatch_webhook_event, is_branch_delete_protected, is_force_push_blocked,
34};
35pub(crate) use multi_repo::sync_global_auth_into_repo;
36pub use multi_repo::{
37    init_bare_repo, multi_repo_page_handler, multi_repo_page_handler_full,
38    multi_repo_page_handler_opts,
39};
40
41use crate::http::{HttpRequest, HttpResponse};
42use crate::serve::PageHandler;
43use arks_object::{Commit, ObjectKind};
44use arks_oid::Oid;
45use arks_refs::RefTarget;
46use arks_repo::Repository;
47use std::collections::HashSet;
48use std::fs;
49use std::path::PathBuf;
50use std::sync::Arc;
51
52pub const WEB_UI_CSP: &str = "default-src 'self'; script-src 'self'";
53pub(crate) const STYLESHEET: &str = include_str!("../web_ui.css");
54const HTMX_JS: &str = include_str!("../assets/htmx.min.js");
55const DIFF2HTML_JS: &str = include_str!("../assets/diff2html.min.js");
56const DIFF2HTML_CSS: &str = include_str!("../assets/diff2html.min.css");
57const APP_JS: &str = include_str!("../assets/app.js");
58pub(crate) const FAVICON_SVG: &str = include_str!("../assets/favicon.svg");
59
60pub(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>";
61pub(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>";
62
63#[derive(Clone, Copy, PartialEq, Eq)]
64pub(crate) enum ActiveTab {
65    Code,
66    Issues,
67    Pulls,
68    Actions,
69    Projects,
70    Wiki,
71    Security,
72    Insights,
73    Settings,
74}
75
76pub(crate) struct RepoContext {
77    pub name: String,
78    pub description: String,
79    pub default_branch: String,
80    pub branches: Vec<(String, Oid)>,
81    pub tags: Vec<(String, Oid)>,
82    pub clone_url: String,
83    pub has_lfs: bool,
84}
85
86impl RepoContext {
87    fn from_repo(repo: &Repository, host: Option<&str>) -> Self {
88        Self::from_repo_with_scheme(repo, host, false)
89    }
90
91    fn from_repo_with_scheme(repo: &Repository, host: Option<&str>, is_https: bool) -> Self {
92        let common = repo.common_dir();
93        let name = common
94            .file_name()
95            .and_then(|s| s.to_str())
96            .map(|n| {
97                if n == ".git" {
98                    common
99                        .parent()
100                        .and_then(|p| p.file_name())
101                        .and_then(|s| s.to_str())
102                        .unwrap_or("repository")
103                        .to_string()
104                } else {
105                    n.trim_end_matches(".git").to_string()
106                }
107            })
108            .unwrap_or_else(|| "repository".into());
109
110        let description = fs::read_to_string(common.join("description"))
111            .ok()
112            .map(|s| s.trim().to_string())
113            .filter(|s| !s.is_empty() && !s.starts_with("Unnamed repository"))
114            .unwrap_or_else(|| "Self-hosted Git repository served by arks".into());
115
116        let default_branch = head_branch_label(repo);
117        let all_refs = repo.refs().list_refs("refs/").unwrap_or_default();
118        let mut branches = Vec::new();
119        let mut tags = Vec::new();
120        for (rname, oid) in all_refs {
121            if let Some(b) = rname.strip_prefix("refs/heads/") {
122                branches.push((b.to_string(), oid));
123            } else if let Some(t) = rname.strip_prefix("refs/tags/") {
124                tags.push((t.to_string(), oid));
125            }
126        }
127        let scheme = if is_https { "https" } else { "http" };
128        let clone_url = format!("{scheme}://{}/", host.unwrap_or("127.0.0.1:8080"));
129        let has_lfs = common.join("lfs").join("objects").is_dir();
130
131        Self {
132            name,
133            description,
134            default_branch,
135            branches,
136            tags,
137            clone_url,
138            has_lfs,
139        }
140    }
141}
142
143/// Strictly escape HTML special characters to prevent XSS.
144pub fn html_escape(input: &str) -> String {
145    let mut out = String::with_capacity(input.len());
146    for ch in input.chars() {
147        match ch {
148            '&' => out.push_str("&amp;"),
149            '<' => out.push_str("&lt;"),
150            '>' => out.push_str("&gt;"),
151            '"' => out.push_str("&quot;"),
152            '\'' => out.push_str("&#x27;"),
153            other => out.push(other),
154        }
155    }
156    out
157}
158
159pub(crate) fn render_partial(status: u16, fragment: &str) -> HttpResponse {
160    HttpResponse {
161        status,
162        content_type: "text/html; charset=utf-8".into(),
163        body: fragment.as_bytes().to_vec(),
164        www_authenticate: None,
165        extra_headers: vec![
166            ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
167            ("X-Content-Type-Options".into(), "nosniff".into()),
168        ],
169    }
170}
171
172pub(crate) fn render_page(
173    status: u16,
174    ctx: &RepoContext,
175    tab: ActiveTab,
176    title: &str,
177    main_html: &str,
178) -> HttpResponse {
179    let cls = |t: ActiveTab| if t == tab { "tab active" } else { "tab" };
180    let open_prs = ctx
181        .branches
182        .iter()
183        .filter(|(b, _)| b != &ctx.default_branch)
184        .count();
185    let arks_clone = format!("arks clone {}", ctx.clone_url);
186    let git_clone = format!("git clone {}", ctx.clone_url);
187    let title_esc = html_escape(title);
188    let desc_esc = html_escape(&ctx.description);
189
190    let doc = format!(
191        "<!doctype html>\n<html lang=\"en\" data-theme=\"dark\">\n<head>\n<meta charset=\"utf-8\">\n\
192         <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n\
193         <title>{title_esc}</title>\n\
194         <meta property=\"og:title\" content=\"{title_esc}\">\n\
195         <meta property=\"og:description\" content=\"{desc_esc}\">\n\
196         <link rel=\"alternate\" type=\"application/atom+xml\" title=\"Commits\" href=\"/commits.atom\">\n\
197         <link rel=\"icon\" type=\"image/svg+xml\" href=\"/favicon.svg\">\n\
198         <link rel=\"stylesheet\" href=\"/assets/diff2html.min.css\">\n\
199         <link rel=\"stylesheet\" href=\"/style.css\">\n\
200         <script src=\"/assets/htmx.min.js\" defer></script>\n\
201         <script src=\"/assets/diff2html.min.js\" defer></script>\n\
202         <script src=\"/assets/app.js\" defer></script>\n\
203         </head>\n<body hx-boost=\"true\">\n\
204         <header class=\"topbar\"><div class=\"topbar-inner\">\n\
205         <div class=\"repo-head\">\n\
206           <div class=\"repo-title\"><img src=\"/favicon.svg\" width=\"26\" height=\"26\" alt=\"arks\">\
207           <a href=\"/\">{}</a><span class=\"badge\">arks serve</span>\
208           <span class=\"badge badge-green\">HTMX v2</span></div>\n\
209           <div class=\"head-actions\">\n\
210             <button type=\"button\" class=\"btn\" data-action=\"open-cmd\">Search / ⌘K</button>\n\
211             <a class=\"btn\" href=\"/notifications\">Notifications</a>\n\
212             <a class=\"btn\" href=\"/releases\">Releases</a>\n\
213             <a class=\"btn\" href=\"/login\">Sign in</a>\n\
214             <details class=\"popover\">\n\
215               <summary class=\"btn btn-primary\">&lt;&gt; Code ▾</summary>\n\
216               <div class=\"popover-panel right\">\n\
217                 <div class=\"popover-head\">Clone repository</div>\n\
218                 <div style=\"padding:10px 12px;display:flex;flex-direction:column;gap:8px\">\n\
219                   <div class=\"btn-group\">\n\
220                     <button type=\"button\" class=\"btn active\" data-clone-cmd=\"{}\">arks</button>\n\
221                     <button type=\"button\" class=\"btn\" data-clone-cmd=\"{}\">git</button>\n\
222                   </div>\n\
223                   <div style=\"display:flex;gap:6px;align-items:center\">\n\
224                     <code id=\"clone-cmd-text\" class=\"input\" style=\"flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap\">{}</code>\n\
225                     <button type=\"button\" class=\"btn\" data-copy-target=\"clone-cmd-text\">Copy</button>\n\
226                   </div>\n\
227                 </div>\n\
228               </div>\n\
229             </details>\n\
230             <button type=\"button\" class=\"btn\" data-action=\"toggle-theme\">Theme</button>\n\
231           </div>\n\
232         </div>\n\
233         <nav class=\"tabs\">\n\
234           <a class=\"{}\" href=\"/\">Code</a>\n\
235           <a class=\"{}\" href=\"/issues\">Issues</a>\n\
236           <a class=\"{}\" href=\"/pulls\">Pull Requests <span class=\"counter\">{}</span></a>\n\
237           <a class=\"{}\" href=\"/actions\">Actions</a>\n\
238           <a class=\"{}\" href=\"/projects\">Projects</a>\n\
239           <a class=\"{}\" href=\"/wiki\">Wiki</a>\n\
240           <a class=\"{}\" href=\"/security\">Security</a>\n\
241           <a class=\"{}\" href=\"/insights\">Insights</a>\n\
242           <a class=\"{}\" href=\"/settings\">Settings</a>\n\
243         </nav>\n\
244         </div></header>\n\
245         <main>\n{main_html}\n</main>\n\
246         <div id=\"cmd-modal\" class=\"cmd-backdrop\">\n\
247           <div class=\"cmd-dialog\">\n\
248             <div class=\"popover-head\" style=\"display:flex;justify-content:space-between\">\n\
249               <span>Quick Jump (⌘K)</span>\n\
250               <button type=\"button\" class=\"btn\" data-action=\"close-cmd\">ESC</button>\n\
251             </div>\n\
252             <a class=\"cmd-item\" href=\"/\"><span>Code &amp; File Tree</span><span class=\"muted\">/</span></a>\n\
253             <a class=\"cmd-item\" href=\"/commits/{}\"><span>Commits History</span><span class=\"muted\">/commits</span></a>\n\
254             <a class=\"cmd-item\" href=\"/branches\"><span>Branches</span><span class=\"muted\">{}</span></a>\n\
255             <a class=\"cmd-item\" href=\"/tags\"><span>Tags</span><span class=\"muted\">{}</span></a>\n\
256             <a class=\"cmd-item\" href=\"/releases\"><span>Releases &amp; Assets</span><span class=\"muted\">/releases</span></a>\n\
257             <a class=\"cmd-item\" href=\"/pulls/new\"><span>New Pull Request</span><span class=\"muted\">/pulls/new</span></a>\n\
258             <a class=\"cmd-item\" href=\"/notifications\"><span>Notifications (@mentions)</span><span class=\"muted\">/notifications</span></a>\n\
259             <a class=\"cmd-item\" href=\"/compare\"><span>Compare Branches</span><span class=\"muted\">/compare</span></a>\n\
260             <a class=\"cmd-item\" href=\"/actions\"><span>Actions &amp; Workflows</span><span class=\"muted\">/actions</span></a>\n\
261             <a class=\"cmd-item\" href=\"/security\"><span>Security &amp; Signatures</span><span class=\"muted\">/security</span></a>\n\
262             <a class=\"cmd-item\" href=\"/insights\"><span>Insights &amp; Contributors</span><span class=\"muted\">/insights</span></a>\n\
263             <a class=\"cmd-item\" href=\"/settings\"><span>Repository Settings</span><span class=\"muted\">/settings</span></a>\n\
264             <a class=\"cmd-item\" href=\"/settings/webhooks\"><span>Webhooks (HMAC-SHA256)</span><span class=\"muted\">/settings/webhooks</span></a>\n\
265             <a class=\"cmd-item\" href=\"/settings/branches\"><span>Branch Protection Rules</span><span class=\"muted\">/settings/branches</span></a>\n\
266             <a class=\"cmd-item\" href=\"/settings/keys\"><span>SSH Keys</span><span class=\"muted\">/settings/keys</span></a>\n\
267             <a class=\"cmd-item\" href=\"/settings/tokens\"><span>Personal Access Tokens</span><span class=\"muted\">/settings/tokens</span></a>\n\
268           </div>\n\
269         </div>\n\
270         </body>\n</html>\n",
271        html_escape(&ctx.name),
272        html_escape(&arks_clone),
273        html_escape(&git_clone),
274        html_escape(&arks_clone),
275        cls(ActiveTab::Code),
276        cls(ActiveTab::Issues),
277        cls(ActiveTab::Pulls),
278        open_prs,
279        cls(ActiveTab::Actions),
280        cls(ActiveTab::Projects),
281        cls(ActiveTab::Wiki),
282        cls(ActiveTab::Security),
283        cls(ActiveTab::Insights),
284        cls(ActiveTab::Settings),
285        html_escape(&ctx.default_branch),
286        ctx.branches.len(),
287        ctx.tags.len(),
288    );
289    HttpResponse {
290        status,
291        content_type: "text/html; charset=utf-8".into(),
292        body: doc.into_bytes(),
293        www_authenticate: None,
294        extra_headers: vec![
295            ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
296            ("X-Content-Type-Options".into(), "nosniff".into()),
297            ("X-Frame-Options".into(), "DENY".into()),
298            ("Referrer-Policy".into(), "same-origin".into()),
299        ],
300    }
301}
302
303pub(crate) fn redirect_see_other(location: &str) -> HttpResponse {
304    HttpResponse {
305        status: 303,
306        content_type: "text/plain; charset=utf-8".into(),
307        body: Vec::new(),
308        www_authenticate: None,
309        extra_headers: vec![
310            ("Location".into(), location.into()),
311            ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
312            ("X-Content-Type-Options".into(), "nosniff".into()),
313        ],
314    }
315}
316
317fn static_asset(content_type: &str, body: &[u8], immutable: bool) -> HttpResponse {
318    HttpResponse {
319        status: 200,
320        content_type: content_type.into(),
321        body: body.to_vec(),
322        www_authenticate: None,
323        extra_headers: vec![
324            ("X-Content-Type-Options".into(), "nosniff".into()),
325            (
326                "Cache-Control".into(),
327                if immutable {
328                    "public, max-age=31536000, immutable"
329                } else {
330                    "public, max-age=86400"
331                }
332                .into(),
333            ),
334        ],
335    }
336}
337
338/// Build a [`PageHandler`] serving the embedded SSR Web UI for `git_dir`
339/// (local Actions runner disabled unless `ARKS_SERVE_ALLOW_LOCAL_ACTIONS=1`).
340pub fn web_ui_page_handler(git_dir: impl Into<PathBuf>) -> PageHandler {
341    let allow = std::env::var("ARKS_SERVE_ALLOW_LOCAL_ACTIONS")
342        .ok()
343        .as_deref()
344        == Some("1");
345    web_ui_page_handler_with_actions(git_dir, allow)
346}
347
348/// Build a [`PageHandler`] serving the embedded SSR Web UI with explicit opt-in
349/// control over local Actions workflow execution.
350pub fn web_ui_page_handler_with_actions(
351    git_dir: impl Into<PathBuf>,
352    allow_local_actions: bool,
353) -> PageHandler {
354    let dir = git_dir.into();
355    Arc::new(move |req: &HttpRequest| handle_web_ui_with_actions(&dir, req, allow_local_actions))
356}
357
358/// Route browser `GET`/`POST` requests to the embedded SSR Web UI (local Actions disabled).
359pub fn handle_web_ui(git_dir: &std::path::Path, req: &HttpRequest) -> Option<HttpResponse> {
360    handle_web_ui_with_actions(git_dir, req, false)
361}
362
363/// Route browser `GET`/`POST` requests to the embedded SSR Web UI; returns `None` for
364/// Git smart/dumb HTTP and LFS paths so protocol traffic passes through untouched.
365pub fn handle_web_ui_with_actions(
366    git_dir: &std::path::Path,
367    req: &HttpRequest,
368    allow_local_actions: bool,
369) -> Option<HttpResponse> {
370    let resp = handle_web_ui_inner(git_dir, req, allow_local_actions)?;
371    if resp.content_type.starts_with("text/html") {
372        let store = store::ForgeStore::load_shared(git_dir);
373        if let Some((user, csrf)) = auth_api::resolve_session_with_csrf(&store, req) {
374            return Some(decorate_html_for_session(resp, &user, &csrf));
375        }
376    }
377    Some(resp)
378}
379
380pub(crate) fn decorate_html_for_session(
381    mut resp: HttpResponse,
382    username: &str,
383    csrf_token: &str,
384) -> HttpResponse {
385    let Ok(mut html) = String::from_utf8(resp.body.clone()) else {
386        return resp;
387    };
388    let sign_in_btn = "<a class=\"btn\" href=\"/login\">Sign in</a>";
389    if html.contains(sign_in_btn) {
390        let signed_in = format!(
391            "<span class=\"badge badge-green\">@{}</span>\
392             <form method=\"post\" action=\"/logout\" style=\"display:inline\">\
393             <button class=\"btn\" type=\"submit\">Sign out</button></form>",
394            html_escape(username)
395        );
396        html = html.replacen(sign_in_btn, &signed_in, 1);
397    }
398    if let Some(head_end) = html.find("</head>") {
399        let meta = format!(
400            "<meta name=\"arks-csrf\" content=\"{}\">",
401            html_escape(csrf_token)
402        );
403        let mut with_meta = String::with_capacity(html.len() + meta.len());
404        with_meta.push_str(&html[..head_end]);
405        with_meta.push_str(&meta);
406        with_meta.push_str(&html[head_end..]);
407        html = with_meta;
408    }
409    let out = inject_csrf_into_post_forms(&html, csrf_token);
410    resp.body = out.into_bytes();
411    resp
412}
413
414pub(crate) fn inject_csrf_into_post_forms(html: &str, csrf_token: &str) -> String {
415    let hidden = format!(
416        "<input type=\"hidden\" name=\"_csrf\" value=\"{}\" />",
417        html_escape(csrf_token)
418    );
419    let bytes = html.as_bytes();
420    let lower = html.to_ascii_lowercase();
421    let lower_bytes = lower.as_bytes();
422    let mut out = String::with_capacity(html.len() + 256);
423    let mut cursor = 0usize;
424
425    while cursor < bytes.len() {
426        let Some(rel_start) = lower[cursor..].find("<form") else {
427            out.push_str(&html[cursor..]);
428            break;
429        };
430        let form_start = cursor + rel_start;
431        let after_tag_name = form_start + 5;
432        let valid_form_tag = lower_bytes
433            .get(after_tag_name)
434            .is_some_and(|b| b.is_ascii_whitespace() || *b == b'>');
435        if !valid_form_tag {
436            out.push_str(&html[cursor..after_tag_name]);
437            cursor = after_tag_name;
438            continue;
439        }
440        let Some(rel_gt) = html[form_start..].find('>') else {
441            out.push_str(&html[cursor..]);
442            break;
443        };
444        let tag_end = form_start + rel_gt + 1;
445        out.push_str(&html[cursor..tag_end]);
446
447        let tag_lower = &lower[form_start..tag_end];
448        let is_post = tag_lower.contains("method=\"post\"")
449            || tag_lower.contains("method='post'")
450            || tag_lower.contains("method=post ")
451            || tag_lower.contains("method=post>");
452
453        if is_post {
454            let form_close = lower[tag_end..]
455                .find("</form>")
456                .map(|r| tag_end + r)
457                .unwrap_or(html.len());
458            let body_lower = &lower[tag_end..form_close];
459            if !body_lower.contains("name=\"_csrf\"") && !body_lower.contains("name='_csrf'") {
460                out.push_str(&hidden);
461            }
462        }
463        cursor = tag_end;
464    }
465    out
466}
467
468fn handle_web_ui_inner(
469    git_dir: &std::path::Path,
470    req: &HttpRequest,
471    allow_local_actions: bool,
472) -> Option<HttpResponse> {
473    if !matches!(req.method.as_str(), "GET" | "POST" | "PATCH" | "DELETE") {
474        return None;
475    }
476    let path = req.path.as_str();
477    // Never intercept Git smart/dumb HTTP or LFS routes.
478    if path.contains("/info/refs")
479        || path.contains("/info/lfs/")
480        || path.contains("/git-upload-pack")
481        || path.contains("/git-receive-pack")
482        || path.starts_with("/objects/")
483        || path == "/HEAD"
484    {
485        return None;
486    }
487    if req.method == "GET" {
488        match path {
489            "/style.css" => {
490                return Some(static_asset(
491                    "text/css; charset=utf-8",
492                    STYLESHEET.as_bytes(),
493                    false,
494                ));
495            }
496            "/assets/htmx.min.js" => {
497                return Some(static_asset(
498                    "application/javascript; charset=utf-8",
499                    HTMX_JS.as_bytes(),
500                    true,
501                ));
502            }
503            "/assets/diff2html.min.js" => {
504                return Some(static_asset(
505                    "application/javascript; charset=utf-8",
506                    DIFF2HTML_JS.as_bytes(),
507                    true,
508                ));
509            }
510            "/assets/diff2html.min.css" => {
511                return Some(static_asset(
512                    "text/css; charset=utf-8",
513                    DIFF2HTML_CSS.as_bytes(),
514                    true,
515                ));
516            }
517            "/assets/app.js" => {
518                return Some(static_asset(
519                    "application/javascript; charset=utf-8",
520                    APP_JS.as_bytes(),
521                    false,
522                ));
523            }
524            "/favicon.svg" => {
525                return Some(static_asset("image/svg+xml", FAVICON_SVG.as_bytes(), false));
526            }
527            _ => {}
528        }
529    }
530
531    let Ok(mut repo) = Repository::open(git_dir) else {
532        return Some(render_partial(500, "Repository unavailable\n"));
533    };
534    let ctx = RepoContext::from_repo_with_scheme(&repo, req.host.as_deref(), req.is_https());
535    let query = req.query.as_str();
536
537    // Unified JSON REST API (`/api/v1/*`) sharing the single atomic ForgeStore.
538    if let Some(api_resp) = auth_api::handle_unified_api(&repo, &ctx, req) {
539        return Some(api_resp);
540    }
541
542    if req.method == "POST" {
543        // Public auth & RFC 8628 OAuth Device Flow endpoints (no prior session required).
544        if path == "/register" {
545            return Some(auth_api::handle_register(&repo, &ctx, req));
546        }
547        if path == "/login" {
548            return Some(auth_api::handle_login(&repo, &ctx, req));
549        }
550        if path == "/logout" {
551            return Some(auth_api::handle_logout(&repo, req));
552        }
553        if path == "/login/device/code" {
554            return Some(auth_api::handle_device_code(&repo, &ctx));
555        }
556        if path == "/login/device" {
557            return Some(auth_api::handle_device_approve(&repo, &ctx, req));
558        }
559        if path == "/login/oauth/access_token" {
560            return Some(auth_api::handle_device_token(&repo, req));
561        }
562
563        // Enforce RBAC on all state-mutating Web UI routes when user accounts exist.
564        let store_check = store::ForgeStore::load_shared(repo.common_dir());
565        if let Err(denied) = auth_api::enforce_write_rbac(&store_check, req) {
566            return Some(denied);
567        }
568        // Archived repositories reject all write mutations except `/settings/repo` (to unarchive).
569        if store_check.archived && path != "/settings/repo" {
570            return Some(HttpResponse {
571                status: 403,
572                content_type: "text/plain; charset=utf-8".into(),
573                body: b"Forbidden: repository is archived (read-only).\n".to_vec(),
574                www_authenticate: None,
575                extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
576            });
577        }
578
579        if path == "/settings/keys" {
580            return Some(auth_api::handle_add_ssh_key(&repo, &ctx, req));
581        }
582        if let Some(rest) = path.strip_prefix("/settings/keys/") {
583            if let Some(user_and_idx) = rest.strip_suffix("/delete") {
584                if let Some((user, idx_str)) = user_and_idx.rsplit_once('/') {
585                    return Some(auth_api::handle_delete_ssh_key(
586                        &repo, &ctx, req, user, idx_str,
587                    ));
588                }
589            }
590        }
591        if path == "/settings/tokens" {
592            return Some(auth_api::handle_create_token(&repo, &ctx, req));
593        }
594        if let Some(rest) = path.strip_prefix("/settings/tokens/") {
595            if let Some(id_str) = rest.strip_suffix("/revoke") {
596                return Some(auth_api::handle_revoke_token(&repo, id_str));
597            }
598        }
599        if path == "/settings/webhooks" {
600            return Some(forge_extras::handle_create_webhook(&repo, &ctx, req));
601        }
602        if let Some(rest) = path.strip_prefix("/settings/webhooks/") {
603            if let Some(id_str) = rest.strip_suffix("/delete") {
604                return Some(forge_extras::handle_delete_webhook(&repo, id_str));
605            }
606            if let Some(id_str) = rest.strip_suffix("/test") {
607                return Some(forge_extras::handle_test_webhook(&repo, &ctx, id_str));
608            }
609        }
610        if path == "/settings/branches" {
611            return Some(forge_extras::handle_create_branch_rule(&repo, &ctx, req));
612        }
613        if path == "/settings/access" {
614            return Some(enterprise::handle_access_settings(&repo, req));
615        }
616        if path == "/notifications/mark-read" {
617            return Some(enterprise::handle_mark_notifications_read(&repo, req));
618        }
619        if path == "/watch" {
620            return Some(enterprise::handle_toggle_watch(&repo, req));
621        }
622        if let Some(rest) = path.strip_prefix("/settings/branches/") {
623            if let Some(pat) = rest.strip_suffix("/delete") {
624                return Some(forge_extras::handle_delete_branch_rule(&repo, pat));
625            }
626        }
627        if path == "/releases" {
628            return Some(forge_extras::handle_create_release(&repo, &ctx, req));
629        }
630        if let Some(rest) = path.strip_prefix("/releases/") {
631            if let Some(id_str) = rest.strip_suffix("/assets") {
632                return Some(forge_extras::handle_upload_asset(&repo, &ctx, id_str, req));
633            }
634        }
635        if path == "/pulls/new" {
636            return Some(forge_extras::handle_create_pr(&repo, &ctx, req));
637        }
638        if path == "/issues" {
639            return Some(forge::handle_create_issue(&repo, &ctx, req));
640        }
641        if let Some(rest) = path.strip_prefix("/issues/") {
642            if let Some((id_str, c_rest)) = rest.split_once("/comments/") {
643                if let Some(idx_str) = c_rest.strip_suffix("/edit") {
644                    return Some(forge::handle_edit_issue_comment(
645                        &repo, id_str, idx_str, req,
646                    ));
647                }
648                if let Some(idx_str) = c_rest.strip_suffix("/delete") {
649                    return Some(forge::handle_delete_issue_comment(&repo, id_str, idx_str));
650                }
651            }
652            if let Some(id_str) = rest.strip_suffix("/comment") {
653                return Some(forge::handle_issue_comment(&repo, &ctx, id_str, req));
654            }
655            if let Some(id_str) = rest.strip_suffix("/edit") {
656                return Some(forge::handle_edit_issue(&repo, id_str, req));
657            }
658            if let Some(id_str) = rest.strip_suffix("/delete") {
659                return Some(forge::handle_delete_issue(&repo, id_str));
660            }
661            if let Some(id_str) = rest.strip_suffix("/react") {
662                return Some(polish::handle_issue_react(&repo, id_str, req));
663            }
664            if let Some(id_str) = rest.strip_suffix("/state") {
665                return Some(forge::handle_issue_state(&repo, &ctx, id_str));
666            }
667            if let Some(id_str) = rest.strip_suffix("/meta") {
668                return Some(forge::handle_issue_meta(&repo, &ctx, id_str, req));
669            }
670        }
671        if let Some(rest) = path.strip_prefix("/pulls/") {
672            if let Some(branch) = rest.strip_suffix("/edit") {
673                return Some(forge::handle_edit_pr(&repo, branch, req));
674            }
675            if let Some(branch) = rest.strip_suffix("/draft") {
676                return Some(polish::handle_toggle_pr_draft(&repo, branch));
677            }
678            if let Some(branch) = rest.strip_suffix("/reviewers") {
679                return Some(polish::handle_assign_pr_reviewers(&repo, branch, req));
680            }
681            if let Some(branch) = rest.strip_suffix("/state") {
682                return Some(polish::handle_toggle_pr_state(&repo, branch));
683            }
684            if let Some(branch) = rest.strip_suffix("/inline-comment") {
685                return Some(forge_extras::handle_inline_comment(
686                    &repo, &ctx, branch, req,
687                ));
688            }
689            if let Some((branch_part, id_part)) = rest.rsplit_once("/inline-comment/") {
690                if let Some(id_str) = id_part.strip_suffix("/resolve") {
691                    return Some(forge_extras::handle_resolve_inline(
692                        &repo,
693                        branch_part,
694                        id_str,
695                    ));
696                }
697            }
698            if let Some(branch) = rest.strip_suffix("/review") {
699                return Some(forge_extras::handle_pr_review_verdict(&repo, branch, req));
700            }
701            if let Some(branch) = rest.strip_suffix("/comment") {
702                return Some(forge::handle_pr_comment(&repo, branch, req));
703            }
704            if let Some(branch) = rest.strip_suffix("/merge") {
705                return Some(forge::handle_pr_merge(&mut repo, &ctx, branch, req));
706            }
707            if let Some(branch) = rest.strip_suffix("/delete-branch") {
708                return Some(forge::handle_pr_delete_branch_with_req(
709                    &mut repo,
710                    &ctx,
711                    branch,
712                    Some(req),
713                ));
714            }
715        }
716        if path == "/actions/run" {
717            return Some(actions::handle_run_workflow(
718                &repo,
719                &ctx,
720                req,
721                allow_local_actions,
722            ));
723        }
724        if let Some(rest) = path.strip_prefix("/actions/runs/") {
725            if let Some(id_str) = rest.strip_suffix("/cancel") {
726                return Some(actions::handle_cancel_workflow_run(
727                    &repo,
728                    &ctx,
729                    id_str,
730                    allow_local_actions,
731                ));
732            }
733            if let Some(id_str) = rest.strip_suffix("/rerun") {
734                return Some(polish::handle_rerun_workflow(
735                    &repo,
736                    &ctx,
737                    id_str,
738                    req,
739                    allow_local_actions,
740                ));
741            }
742            if let Some(id_str) = rest.strip_suffix("/artifacts") {
743                return Some(admin_2fa::handle_upload_artifact(&repo, &ctx, id_str, req));
744            }
745        }
746        if path == "/settings/repo" {
747            return Some(polish::handle_repo_settings(&repo, req));
748        }
749        if path == "/settings/profile/password" {
750            return Some(polish::handle_change_password(&repo, &ctx, req));
751        }
752        if path == "/settings/profile/sessions/revoke" {
753            return Some(polish::handle_revoke_other_sessions(&repo, req));
754        }
755        if path == "/agents/leases/unlock" {
756            return Some(polish::handle_force_unlock_lease(&repo, req));
757        }
758        if path == "/markdown/preview" {
759            return Some(polish::handle_markdown_preview(req));
760        }
761        if path == "/settings/2fa" {
762            return Some(admin_2fa::handle_enable_2fa(&repo, &ctx, req));
763        }
764        if path == "/settings/2fa/disable" {
765            return Some(admin_2fa::handle_disable_2fa(&repo, &ctx, req));
766        }
767        if path == "/settings/secrets" {
768            return Some(actions::handle_upsert_secret(&repo, req));
769        }
770        if let Some(rest) = path.strip_prefix("/settings/secrets/") {
771            if let Some(name) = rest.strip_suffix("/delete") {
772                return Some(actions::handle_delete_secret(&repo, name));
773            }
774        }
775        if let Some(rest) = path.strip_prefix("/admin/users/") {
776            if let Some(username) = rest.strip_suffix("/role") {
777                if let Err(denied) = auth_api::enforce_admin_rbac(&store_check, req) {
778                    return Some(denied);
779                }
780                return Some(admin_2fa::handle_admin_update_role(&repo, username, req));
781            }
782        }
783        if let Some(rest) = path.strip_prefix("/edit/") {
784            let (rev, subpath) = split_rev_and_path(&repo, rest);
785            return Some(editor::handle_save_file(&mut repo, &ctx, rev, subpath, req));
786        }
787        if let Some(rest) = path.strip_prefix("/delete/") {
788            let (rev, subpath) = split_rev_and_path(&repo, rest);
789            return Some(editor::handle_delete_file(
790                &mut repo, &ctx, rev, subpath, req,
791            ));
792        }
793        if let Some(rev) = path.strip_prefix("/upload/") {
794            if !rev.is_empty() {
795                return Some(editor::handle_upload_file(&mut repo, &ctx, rev, req));
796            }
797        }
798        if let Some(rev) = path.strip_prefix("/new/") {
799            if !rev.is_empty() {
800                return Some(editor::handle_create_file(&mut repo, &ctx, rev, req));
801            }
802        }
803        if path == "/branches/create" {
804            return Some(editor::handle_create_branch(&mut repo, &ctx, req));
805        }
806        if path == "/tags/create" {
807            return Some(editor::handle_create_tag(&mut repo, &ctx, req));
808        }
809        if path == "/projects/cards" {
810            return Some(projects_wiki::handle_create_card(&repo, &ctx, req));
811        }
812        if let Some(rest) = path.strip_prefix("/projects/cards/") {
813            if let Some(id_str) = rest.strip_suffix("/move") {
814                return Some(projects_wiki::handle_move_card(&repo, &ctx, id_str, req));
815            }
816            if let Some(id_str) = rest.strip_suffix("/delete") {
817                return Some(projects_wiki::handle_delete_card(&repo, &ctx, id_str));
818            }
819        }
820        if path == "/wiki" {
821            return Some(projects_wiki::handle_upsert_wiki(&repo, &ctx, None, req));
822        }
823        if let Some(rest) = path.strip_prefix("/wiki/") {
824            if let Some(slug) = rest.strip_suffix("/delete") {
825                return Some(projects_wiki::handle_delete_wiki(&repo, &ctx, slug));
826            }
827            if !rest.is_empty() && !rest.contains('/') {
828                return Some(projects_wiki::handle_upsert_wiki(
829                    &repo,
830                    &ctx,
831                    Some(rest),
832                    req,
833                ));
834            }
835        }
836        return Some(render_page(
837            405,
838            &ctx,
839            ActiveTab::Code,
840            "405 Method Not Allowed",
841            "<div class=\"card\"><div class=\"card-body\">Method not allowed for this route.</div></div>",
842        ));
843    }
844
845    if path == "/robots.txt" {
846        return Some(HttpResponse {
847            status: 200,
848            content_type: "text/plain; charset=utf-8".into(),
849            body: b"User-agent: *\nDisallow: /admin\nDisallow: /settings\n".to_vec(),
850            www_authenticate: None,
851            extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
852        });
853    }
854    if path == "/login" {
855        return Some(auth_api::render_login(&repo, &ctx));
856    }
857    if path == "/register" {
858        return Some(auth_api::render_register(&repo, &ctx));
859    }
860    if path == "/login/device" {
861        return Some(auth_api::render_device_approve(&repo, &ctx));
862    }
863    let vis_store = store::ForgeStore::load_shared(repo.common_dir());
864    if let Err(denied) = auth_api::enforce_read_visibility(&vis_store, req) {
865        return Some(denied);
866    }
867    if path == "/settings/keys" {
868        return Some(auth_api::render_ssh_keys(&repo, &ctx, req));
869    }
870    if path == "/settings/tokens" {
871        return Some(auth_api::render_tokens(&repo, &ctx, req));
872    }
873    if path == "/settings/webhooks" {
874        return Some(forge_extras::render_webhooks(&repo, &ctx));
875    }
876    if path == "/settings/branches" {
877        return Some(forge_extras::render_branch_rules(&repo, &ctx));
878    }
879    if path == "/settings/access" {
880        return Some(enterprise::render_access_settings(&repo, &ctx));
881    }
882    if path == "/settings/2fa" {
883        return Some(admin_2fa::render_2fa_settings(&repo, &ctx, req));
884    }
885    if path == "/settings/secrets" {
886        return Some(actions::render_secrets_settings(&repo, &ctx));
887    }
888    if let Some(file) = path.strip_prefix("/archive/") {
889        if !file.is_empty() {
890            return Some(archives::handle_archive_download(&repo, &ctx.name, file));
891        }
892    }
893    if let Some(rest) = path.strip_prefix("/commit/") {
894        if let Some(rev) = rest.strip_suffix(".patch") {
895            return Some(archives::handle_commit_patch(&repo, rev, true));
896        }
897        if let Some(rev) = rest.strip_suffix(".diff") {
898            return Some(archives::handle_commit_patch(&repo, rev, false));
899        }
900    }
901    if let Some(rest) = path.strip_prefix("/pulls/") {
902        if let Some(branch) = rest.strip_suffix(".patch") {
903            return Some(archives::handle_pr_patch(
904                &repo,
905                &ctx.default_branch,
906                branch,
907                true,
908            ));
909        }
910        if let Some(branch) = rest.strip_suffix(".diff") {
911            return Some(archives::handle_pr_patch(
912                &repo,
913                &ctx.default_branch,
914                branch,
915                false,
916            ));
917        }
918    }
919    if path == "/settings/repo" {
920        return Some(polish::render_repo_settings(&repo, &ctx));
921    }
922    if path == "/settings/profile" {
923        return Some(polish::render_profile_settings(&repo, &ctx, req));
924    }
925    if path == "/commits.atom" {
926        return Some(polish::render_commits_atom(&repo, &ctx));
927    }
928    if path == "/releases.atom" {
929        return Some(polish::render_releases_atom(&repo, &ctx));
930    }
931    if let Some(rest) = path.strip_prefix("/actions/runs/") {
932        if let Some(id_str) = rest.strip_suffix("/log-partial") {
933            return Some(polish::render_action_log_partial(&repo, id_str));
934        }
935    }
936    if path == "/admin/audit/verify" {
937        let store_check = store::ForgeStore::load_shared(repo.common_dir());
938        if let Err(denied) = auth_api::enforce_admin_rbac(&store_check, req) {
939            return Some(denied);
940        }
941        return Some(admin_2fa::handle_verify_audit_chain(&repo));
942    }
943    if path == "/admin/audit.csv" || path == "/admin/audit.jsonl" {
944        let store_check = store::ForgeStore::load_shared(repo.common_dir());
945        if let Err(denied) = auth_api::enforce_admin_rbac(&store_check, req) {
946            return Some(denied);
947        }
948        return Some(polish::export_audit_log(&repo, path.ends_with(".jsonl")));
949    }
950    if path == "/admin" {
951        let store_check = store::ForgeStore::load_shared(repo.common_dir());
952        if let Err(denied) = auth_api::enforce_admin_rbac(&store_check, req) {
953            return Some(denied);
954        }
955        return Some(admin_2fa::render_admin_dashboard(&repo, &ctx, query));
956    }
957    if path == "/agents" {
958        return Some(enterprise::render_agents_dashboard(&repo, &ctx));
959    }
960    if path == "/releases" {
961        return Some(forge_extras::render_releases(&repo, &ctx));
962    }
963    if let Some(rest) = path.strip_prefix("/releases/") {
964        if let Some((id_str, filename)) = rest.split_once("/assets/") {
965            return Some(forge_extras::handle_download_asset(&repo, id_str, filename));
966        }
967    }
968    if path == "/pulls/new" {
969        return Some(forge_extras::render_new_pr(&repo, &ctx));
970    }
971    if path == "/" || path.is_empty() {
972        return Some(code::render_tree(&repo, &ctx, &ctx.default_branch, ""));
973    }
974    if path == "/search" {
975        return Some(code::render_search_partial(&repo, &ctx, query));
976    }
977    if path == "/notifications" {
978        return Some(editor::render_notifications(&repo, &ctx, query));
979    }
980    if let Some(rest) = path.strip_prefix("/edit/") {
981        let (rev, subpath) = split_rev_and_path(&repo, rest);
982        return Some(editor::render_edit_file(&repo, &ctx, rev, subpath));
983    }
984    if let Some(rev) = path.strip_prefix("/new/") {
985        if !rev.is_empty() {
986            return Some(editor::render_new_file(&repo, &ctx, rev));
987        }
988    }
989    if path == "/branches" || path == "/refs" {
990        return Some(code::render_branches(&ctx));
991    }
992    if path == "/tags" {
993        return Some(code::render_tags(&ctx));
994    }
995    if path == "/commits" {
996        return Some(code::render_commits(
997            &repo,
998            &ctx,
999            &ctx.default_branch,
1000            query,
1001        ));
1002    }
1003    if let Some(rev) = path.strip_prefix("/commits/") {
1004        return Some(code::render_commits(&repo, &ctx, rev, query));
1005    }
1006    if let Some(oid_str) = path.strip_prefix("/commit/") {
1007        return Some(diff::render_commit(&repo, &ctx, oid_str));
1008    }
1009    if path == "/compare" {
1010        return Some(diff::render_compare(&repo, &ctx, ""));
1011    }
1012    if let Some(spec) = path.strip_prefix("/compare/") {
1013        return Some(diff::render_compare(&repo, &ctx, spec));
1014    }
1015    if let Some(rest) = path.strip_prefix("/tree/") {
1016        let (rev, subpath) = split_rev_and_path(&repo, rest);
1017        return Some(code::render_tree(&repo, &ctx, rev, subpath));
1018    }
1019    if let Some(rest) = path.strip_prefix("/blob/") {
1020        let (rev, subpath) = split_rev_and_path(&repo, rest);
1021        return Some(code::render_blob(&repo, &ctx, rev, subpath));
1022    }
1023    if let Some(rest) = path.strip_prefix("/blame/") {
1024        let (rev, subpath) = split_rev_and_path(&repo, rest);
1025        return Some(code::render_blame(&repo, &ctx, rev, subpath));
1026    }
1027    if let Some(rest) = path.strip_prefix("/raw/") {
1028        let (rev, subpath) = split_rev_and_path(&repo, rest);
1029        return Some(code::render_raw(&repo, rev, subpath));
1030    }
1031    if path == "/issues" {
1032        return Some(forge::render_issues(&repo, &ctx, query));
1033    }
1034    if let Some(id_str) = path.strip_prefix("/issues/") {
1035        if id_str.chars().all(|c| c.is_ascii_digit()) && !id_str.is_empty() {
1036            return Some(forge::render_issue_detail(&repo, &ctx, id_str));
1037        }
1038    }
1039    if path == "/pulls" {
1040        return Some(forge::render_pulls(&repo, &ctx));
1041    }
1042    if let Some(branch) = path.strip_prefix("/pulls/") {
1043        if !branch.is_empty() {
1044            return Some(forge::render_pr_detail(&repo, &ctx, branch));
1045        }
1046    }
1047    if path == "/actions" {
1048        return Some(actions::render_actions(&repo, &ctx, allow_local_actions));
1049    }
1050    if let Some(rest) = path.strip_prefix("/actions/runs/") {
1051        if let Some((id_str, name)) = rest.split_once("/artifacts/") {
1052            return Some(admin_2fa::handle_download_artifact(&repo, id_str, name));
1053        }
1054        if let Some(id_str) = rest.strip_suffix("/stream") {
1055            return Some(actions::render_action_run_stream(&repo, id_str));
1056        }
1057        if rest.chars().all(|c| c.is_ascii_digit()) && !rest.is_empty() {
1058            return Some(actions::render_action_run(&repo, &ctx, rest));
1059        }
1060    }
1061    if path == "/projects" {
1062        return Some(projects_wiki::render_projects(&repo, &ctx));
1063    }
1064    if path == "/wiki" {
1065        return Some(projects_wiki::render_wiki(&repo, &ctx));
1066    }
1067    if let Some(slug) = path.strip_prefix("/wiki/") {
1068        if !slug.is_empty() && !slug.contains('/') {
1069            return Some(projects_wiki::render_wiki_page(&repo, &ctx, slug));
1070        }
1071    }
1072    if path == "/security" {
1073        return Some(forge::render_security(&repo, &ctx));
1074    }
1075    if path == "/insights" {
1076        return Some(forge::render_insights(&repo, &ctx));
1077    }
1078    if path == "/settings" {
1079        return Some(forge::render_settings(&repo, &ctx));
1080    }
1081
1082    Some(render_page(
1083        404,
1084        &ctx,
1085        ActiveTab::Code,
1086        "404 Not Found",
1087        "<div class=\"card\"><div class=\"card-body\">Page not found.</div></div>",
1088    ))
1089}
1090
1091fn is_safe_rev_candidate(cand: &str) -> bool {
1092    !cand.is_empty()
1093        && !cand.starts_with('/')
1094        && !cand.ends_with('/')
1095        && !cand.contains("..")
1096        && !cand.contains('\\')
1097}
1098
1099/// Split `<rev>/<subpath>` by resolving the longest matching branch/tag/OID prefix
1100/// so slash-containing branches (`feature/foo/src/lib.rs`, `arks/stack/abcd1234/README.md`)
1101/// resolve cleanly across `/tree/`, `/blob/`, `/blame/`, `/raw/`, `/edit/`, `/delete/`.
1102fn split_rev_and_path<'a>(repo: &Repository, rest: &'a str) -> (&'a str, &'a str) {
1103    if is_safe_rev_candidate(rest) && resolve_rev_oid(repo, rest).is_some() {
1104        return (rest, "");
1105    }
1106    for (idx, b) in rest.bytes().enumerate().rev() {
1107        if b == b'/' {
1108            let cand = &rest[..idx];
1109            if is_safe_rev_candidate(cand) && resolve_rev_oid(repo, cand).is_some() {
1110                return (cand, &rest[idx + 1..]);
1111            }
1112        }
1113    }
1114    match rest.split_once('/') {
1115        Some((r, p)) => (r, p),
1116        None => (rest, ""),
1117    }
1118}
1119
1120pub(crate) fn head_branch_label(repo: &Repository) -> String {
1121    match repo.head_target() {
1122        Ok(RefTarget::Symbolic(s)) => s.strip_prefix("refs/heads/").unwrap_or(&s).to_string(),
1123        Ok(RefTarget::Direct(o)) => o.to_hex()[..7.min(o.to_hex().len())].to_string(),
1124        Err(_) => "HEAD".into(),
1125    }
1126}
1127
1128pub(crate) fn resolve_rev_oid(repo: &Repository, rev: &str) -> Option<Oid> {
1129    if rev == "HEAD" {
1130        return repo.refs().resolve("HEAD").ok();
1131    }
1132    if let Ok(oid) = Oid::from_hex(rev) {
1133        if repo.get_object(&oid).is_ok() {
1134            return Some(oid);
1135        }
1136    }
1137    for candidate in [
1138        rev.to_string(),
1139        format!("refs/heads/{rev}"),
1140        format!("refs/tags/{rev}"),
1141    ] {
1142        if let Ok(oid) = repo.refs().resolve(&candidate) {
1143            return Some(oid);
1144        }
1145    }
1146    None
1147}
1148
1149pub(crate) fn load_commit(repo: &Repository, oid: &Oid) -> Option<Commit> {
1150    let obj = repo.get_object(oid).ok()?;
1151    if obj.kind != ObjectKind::Commit {
1152        return None;
1153    }
1154    Commit::decode(&obj.payload).ok()
1155}
1156
1157pub(crate) fn load_tree(repo: &Repository, oid: &Oid) -> Option<arks_object::Tree> {
1158    let obj = repo.get_object(oid).ok()?;
1159    if obj.kind != ObjectKind::Tree {
1160        return None;
1161    }
1162    arks_object::Tree::decode(&obj.payload, repo.oid_kind()).ok()
1163}
1164
1165pub(crate) fn load_blob(repo: &Repository, oid: &Oid) -> Option<Vec<u8>> {
1166    let obj = repo.get_object(oid).ok()?;
1167    if obj.kind != ObjectKind::Blob {
1168        return None;
1169    }
1170    Some(obj.payload)
1171}
1172
1173pub(crate) fn commit_has_sig(commit: &Commit) -> bool {
1174    commit.gpgsig.is_some()
1175}
1176
1177pub(crate) fn collect_recent_commits(
1178    repo: &Repository,
1179    start: Oid,
1180    limit: usize,
1181) -> Vec<(Oid, Commit)> {
1182    let mut out = Vec::new();
1183    let mut visited = HashSet::new();
1184    let mut cur = Some(start);
1185    while let Some(oid) = cur {
1186        if out.len() >= limit || !visited.insert(oid) {
1187            break;
1188        }
1189        let Some(commit) = load_commit(repo, &oid) else {
1190            break;
1191        };
1192        let next = commit.parents.first().copied();
1193        out.push((oid, commit));
1194        cur = next;
1195    }
1196    out
1197}
1198
1199/// Format a Unix timestamp as human-readable UTC (`YYYY-MM-DD HH:MM UTC`) plus relative age.
1200pub(crate) fn format_timestamp(ts: i64) -> String {
1201    if ts <= 0 {
1202        return "1970-01-01 00:00 UTC".into();
1203    }
1204    let secs_per_day = 86_400i64;
1205    let z = ts.div_euclid(secs_per_day) + 719_468;
1206    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
1207    let doe = (z - era * 146_097) as u64;
1208    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1209    let y = (yoe as i64) + era * 400;
1210    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1211    let mp = (5 * doy + 2) / 153;
1212    let d = doy - (153 * mp + 2) / 5 + 1;
1213    let m = if mp < 10 { mp + 3 } else { mp - 9 };
1214    let year = y + if m <= 2 { 1 } else { 0 };
1215    let rem = ts.rem_euclid(secs_per_day);
1216    let hour = rem / 3600;
1217    let min = (rem % 3600) / 60;
1218
1219    let now = store::now_unix();
1220    let rel = if now >= ts {
1221        let diff = now - ts;
1222        if diff < 60 {
1223            "just now".into()
1224        } else if diff < 3600 {
1225            format!("{}m ago", diff / 60)
1226        } else if diff < 86_400 {
1227            format!("{}h ago", diff / 3600)
1228        } else {
1229            format!("{}d ago", diff / 86_400)
1230        }
1231    } else {
1232        "upcoming".into()
1233    };
1234    format!("{year:04}-{m:02}-{d:02} {hour:02}:{min:02} UTC ({rel})")
1235}
1236
1237#[cfg(test)]
1238mod tests {
1239    use super::*;
1240    use arks_object::{RawObject, Signature, Tree, TreeEntry, TreeMode};
1241    use arks_store::ObjectStore as _;
1242
1243    #[test]
1244    fn split_rev_and_path_resolves_longest_matching_slash_branch() {
1245        let dir = tempfile::tempdir().unwrap();
1246        let bare = init_bare_repo(dir.path(), "demo", "Demo").unwrap();
1247        let mut repo = Repository::open(&bare).unwrap();
1248        let fmt = repo.object_format();
1249        let blob = repo
1250            .store_mut()
1251            .put(
1252                fmt,
1253                &RawObject::new(ObjectKind::Blob, b"fn main() {}\n".to_vec()),
1254            )
1255            .unwrap();
1256        let tree = Tree::new(vec![TreeEntry {
1257            mode: TreeMode::File,
1258            name: "README.md".into(),
1259            oid: blob,
1260        }])
1261        .unwrap();
1262        let tree_oid = repo
1263            .store_mut()
1264            .put(
1265                fmt,
1266                &RawObject::new(ObjectKind::Tree, tree.encode().unwrap()),
1267            )
1268            .unwrap();
1269        let sig = Signature {
1270            name: "dev".into(),
1271            email: "dev@example.invalid".into(),
1272            timestamp: 1_700_000_000,
1273            timezone: "+0000".into(),
1274        };
1275        let commit = Commit {
1276            tree: tree_oid,
1277            parents: Vec::new(),
1278            author: sig.clone(),
1279            committer: sig,
1280            gpgsig: None,
1281            message: "init\n".into(),
1282        };
1283        let oid = repo
1284            .store_mut()
1285            .put(
1286                fmt,
1287                &RawObject::new(ObjectKind::Commit, commit.encode().unwrap()),
1288            )
1289            .unwrap();
1290        repo.refs_mut()
1291            .update("refs/heads/main", &oid, None)
1292            .unwrap();
1293        repo.refs_mut()
1294            .update("refs/heads/feature/foo", &oid, None)
1295            .unwrap();
1296        repo.refs_mut()
1297            .update("refs/heads/arks/stack/abcd1234", &oid, None)
1298            .unwrap();
1299
1300        assert_eq!(
1301            split_rev_and_path(&repo, "feature/foo/src/lib.rs"),
1302            ("feature/foo", "src/lib.rs")
1303        );
1304        assert_eq!(
1305            split_rev_and_path(&repo, "arks/stack/abcd1234/README.md"),
1306            ("arks/stack/abcd1234", "README.md")
1307        );
1308        assert_eq!(
1309            split_rev_and_path(&repo, "feature/foo"),
1310            ("feature/foo", "")
1311        );
1312        assert_eq!(
1313            split_rev_and_path(&repo, "main/src/lib.rs"),
1314            ("main", "src/lib.rs")
1315        );
1316    }
1317}