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