mod actions;
mod admin_2fa;
mod archives;
mod auth_api;
mod code;
mod diff;
mod editor;
mod enterprise;
mod forge;
mod forge_extras;
mod highlight;
mod merge;
mod multi_repo;
mod polish;
mod projects_wiki;
pub(crate) mod store;
pub(crate) use actions::trigger_event_workflows;
pub(crate) use auth_api::check_git_http_auth;
pub(crate) use forge_extras::{
dispatch_webhook_event, is_branch_delete_protected, is_force_push_blocked,
};
pub use multi_repo::{init_bare_repo, multi_repo_page_handler};
use crate::http::{HttpRequest, HttpResponse};
use crate::serve::PageHandler;
use arks_object::{Commit, ObjectKind};
use arks_oid::Oid;
use arks_refs::RefTarget;
use arks_repo::Repository;
use std::collections::HashSet;
use std::fs;
use std::path::PathBuf;
use std::sync::Arc;
pub const WEB_UI_CSP: &str = "default-src 'self'; script-src 'self'";
pub(crate) const STYLESHEET: &str = include_str!("../web_ui.css");
const HTMX_JS: &str = include_str!("../assets/htmx.min.js");
const DIFF2HTML_JS: &str = include_str!("../assets/diff2html.min.js");
const DIFF2HTML_CSS: &str = include_str!("../assets/diff2html.min.css");
const APP_JS: &str = include_str!("../assets/app.js");
pub(crate) const FAVICON_SVG: &str = include_str!("../assets/favicon.svg");
pub(crate) const ICON_DIR: &str = "<svg class=\"icon icon-dir\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z\"/></svg>";
pub(crate) const ICON_FILE: &str = "<svg class=\"icon icon-file\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z\"/></svg>";
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ActiveTab {
Code,
Issues,
Pulls,
Actions,
Projects,
Wiki,
Security,
Insights,
Settings,
}
pub(crate) struct RepoContext {
pub name: String,
pub description: String,
pub default_branch: String,
pub branches: Vec<(String, Oid)>,
pub tags: Vec<(String, Oid)>,
pub clone_url: String,
pub has_lfs: bool,
}
impl RepoContext {
fn from_repo(repo: &Repository, host: Option<&str>) -> Self {
let common = repo.common_dir();
let name = common
.file_name()
.and_then(|s| s.to_str())
.map(|n| {
if n == ".git" {
common
.parent()
.and_then(|p| p.file_name())
.and_then(|s| s.to_str())
.unwrap_or("repository")
.to_string()
} else {
n.trim_end_matches(".git").to_string()
}
})
.unwrap_or_else(|| "repository".into());
let description = fs::read_to_string(common.join("description"))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty() && !s.starts_with("Unnamed repository"))
.unwrap_or_else(|| "Self-hosted Git repository served by arks".into());
let default_branch = head_branch_label(repo);
let all_refs = repo.refs().list_refs("refs/").unwrap_or_default();
let mut branches = Vec::new();
let mut tags = Vec::new();
for (rname, oid) in all_refs {
if let Some(b) = rname.strip_prefix("refs/heads/") {
branches.push((b.to_string(), oid));
} else if let Some(t) = rname.strip_prefix("refs/tags/") {
tags.push((t.to_string(), oid));
}
}
let clone_url = format!("http://{}/", host.unwrap_or("127.0.0.1:8080"));
let has_lfs = common.join("lfs").join("objects").is_dir();
Self {
name,
description,
default_branch,
branches,
tags,
clone_url,
has_lfs,
}
}
}
pub fn html_escape(input: &str) -> String {
let mut out = String::with_capacity(input.len());
for ch in input.chars() {
match ch {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
other => out.push(other),
}
}
out
}
pub(crate) fn render_partial(status: u16, fragment: &str) -> HttpResponse {
HttpResponse {
status,
content_type: "text/html; charset=utf-8".into(),
body: fragment.as_bytes().to_vec(),
www_authenticate: None,
extra_headers: vec![
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
("X-Content-Type-Options".into(), "nosniff".into()),
],
}
}
pub(crate) fn render_page(
status: u16,
ctx: &RepoContext,
tab: ActiveTab,
title: &str,
main_html: &str,
) -> HttpResponse {
let cls = |t: ActiveTab| if t == tab { "tab active" } else { "tab" };
let open_prs = ctx
.branches
.iter()
.filter(|(b, _)| b != &ctx.default_branch)
.count();
let arks_clone = format!("arks clone {}", ctx.clone_url);
let git_clone = format!("git clone {}", ctx.clone_url);
let title_esc = html_escape(title);
let desc_esc = html_escape(&ctx.description);
let doc = format!(
"<!doctype html>\n<html lang=\"en\" data-theme=\"dark\">\n<head>\n<meta charset=\"utf-8\">\n\
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n\
<title>{title_esc}</title>\n\
<meta property=\"og:title\" content=\"{title_esc}\">\n\
<meta property=\"og:description\" content=\"{desc_esc}\">\n\
<link rel=\"alternate\" type=\"application/atom+xml\" title=\"Commits\" href=\"/commits.atom\">\n\
<link rel=\"icon\" type=\"image/svg+xml\" href=\"/favicon.svg\">\n\
<link rel=\"stylesheet\" href=\"/assets/diff2html.min.css\">\n\
<link rel=\"stylesheet\" href=\"/style.css\">\n\
<script src=\"/assets/htmx.min.js\" defer></script>\n\
<script src=\"/assets/diff2html.min.js\" defer></script>\n\
<script src=\"/assets/app.js\" defer></script>\n\
</head>\n<body hx-boost=\"true\">\n\
<header class=\"topbar\"><div class=\"topbar-inner\">\n\
<div class=\"repo-head\">\n\
<div class=\"repo-title\"><img src=\"/favicon.svg\" width=\"26\" height=\"26\" alt=\"arks\">\
<a href=\"/\">{}</a><span class=\"badge\">arks serve</span>\
<span class=\"badge badge-green\">HTMX v2</span></div>\n\
<div class=\"head-actions\">\n\
<button type=\"button\" class=\"btn\" data-action=\"open-cmd\">Search / ⌘K</button>\n\
<a class=\"btn\" href=\"/notifications\">Notifications</a>\n\
<a class=\"btn\" href=\"/releases\">Releases</a>\n\
<a class=\"btn\" href=\"/login\">Sign in</a>\n\
<details class=\"popover\">\n\
<summary class=\"btn btn-primary\"><> Code ▾</summary>\n\
<div class=\"popover-panel right\">\n\
<div class=\"popover-head\">Clone repository</div>\n\
<div style=\"padding:10px 12px;display:flex;flex-direction:column;gap:8px\">\n\
<div class=\"btn-group\">\n\
<button type=\"button\" class=\"btn active\" data-clone-cmd=\"{}\">arks</button>\n\
<button type=\"button\" class=\"btn\" data-clone-cmd=\"{}\">git</button>\n\
</div>\n\
<div style=\"display:flex;gap:6px;align-items:center\">\n\
<code id=\"clone-cmd-text\" class=\"input\" style=\"flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap\">{}</code>\n\
<button type=\"button\" class=\"btn\" data-copy-target=\"clone-cmd-text\">Copy</button>\n\
</div>\n\
</div>\n\
</div>\n\
</details>\n\
<button type=\"button\" class=\"btn\" data-action=\"toggle-theme\">Theme</button>\n\
</div>\n\
</div>\n\
<nav class=\"tabs\">\n\
<a class=\"{}\" href=\"/\">Code</a>\n\
<a class=\"{}\" href=\"/issues\">Issues</a>\n\
<a class=\"{}\" href=\"/pulls\">Pull Requests <span class=\"counter\">{}</span></a>\n\
<a class=\"{}\" href=\"/actions\">Actions</a>\n\
<a class=\"{}\" href=\"/projects\">Projects</a>\n\
<a class=\"{}\" href=\"/wiki\">Wiki</a>\n\
<a class=\"{}\" href=\"/security\">Security</a>\n\
<a class=\"{}\" href=\"/insights\">Insights</a>\n\
<a class=\"{}\" href=\"/settings\">Settings</a>\n\
</nav>\n\
</div></header>\n\
<main>\n{main_html}\n</main>\n\
<div id=\"cmd-modal\" class=\"cmd-backdrop\">\n\
<div class=\"cmd-dialog\">\n\
<div class=\"popover-head\" style=\"display:flex;justify-content:space-between\">\n\
<span>Quick Jump (⌘K)</span>\n\
<button type=\"button\" class=\"btn\" data-action=\"close-cmd\">ESC</button>\n\
</div>\n\
<a class=\"cmd-item\" href=\"/\"><span>Code & File Tree</span><span class=\"muted\">/</span></a>\n\
<a class=\"cmd-item\" href=\"/commits/{}\"><span>Commits History</span><span class=\"muted\">/commits</span></a>\n\
<a class=\"cmd-item\" href=\"/branches\"><span>Branches</span><span class=\"muted\">{}</span></a>\n\
<a class=\"cmd-item\" href=\"/tags\"><span>Tags</span><span class=\"muted\">{}</span></a>\n\
<a class=\"cmd-item\" href=\"/releases\"><span>Releases & Assets</span><span class=\"muted\">/releases</span></a>\n\
<a class=\"cmd-item\" href=\"/pulls/new\"><span>New Pull Request</span><span class=\"muted\">/pulls/new</span></a>\n\
<a class=\"cmd-item\" href=\"/notifications\"><span>Notifications (@mentions)</span><span class=\"muted\">/notifications</span></a>\n\
<a class=\"cmd-item\" href=\"/compare\"><span>Compare Branches</span><span class=\"muted\">/compare</span></a>\n\
<a class=\"cmd-item\" href=\"/actions\"><span>Actions & Workflows</span><span class=\"muted\">/actions</span></a>\n\
<a class=\"cmd-item\" href=\"/security\"><span>Security & Signatures</span><span class=\"muted\">/security</span></a>\n\
<a class=\"cmd-item\" href=\"/insights\"><span>Insights & Contributors</span><span class=\"muted\">/insights</span></a>\n\
<a class=\"cmd-item\" href=\"/settings\"><span>Repository Settings</span><span class=\"muted\">/settings</span></a>\n\
<a class=\"cmd-item\" href=\"/settings/webhooks\"><span>Webhooks (HMAC-SHA256)</span><span class=\"muted\">/settings/webhooks</span></a>\n\
<a class=\"cmd-item\" href=\"/settings/branches\"><span>Branch Protection Rules</span><span class=\"muted\">/settings/branches</span></a>\n\
<a class=\"cmd-item\" href=\"/settings/keys\"><span>SSH Keys</span><span class=\"muted\">/settings/keys</span></a>\n\
<a class=\"cmd-item\" href=\"/settings/tokens\"><span>Personal Access Tokens</span><span class=\"muted\">/settings/tokens</span></a>\n\
</div>\n\
</div>\n\
</body>\n</html>\n",
html_escape(&ctx.name),
html_escape(&arks_clone),
html_escape(&git_clone),
html_escape(&arks_clone),
cls(ActiveTab::Code),
cls(ActiveTab::Issues),
cls(ActiveTab::Pulls),
open_prs,
cls(ActiveTab::Actions),
cls(ActiveTab::Projects),
cls(ActiveTab::Wiki),
cls(ActiveTab::Security),
cls(ActiveTab::Insights),
cls(ActiveTab::Settings),
html_escape(&ctx.default_branch),
ctx.branches.len(),
ctx.tags.len(),
);
HttpResponse {
status,
content_type: "text/html; charset=utf-8".into(),
body: doc.into_bytes(),
www_authenticate: None,
extra_headers: vec![
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
("X-Content-Type-Options".into(), "nosniff".into()),
("X-Frame-Options".into(), "DENY".into()),
("Referrer-Policy".into(), "same-origin".into()),
],
}
}
pub(crate) fn redirect_see_other(location: &str) -> HttpResponse {
HttpResponse {
status: 303,
content_type: "text/plain; charset=utf-8".into(),
body: Vec::new(),
www_authenticate: None,
extra_headers: vec![
("Location".into(), location.into()),
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
("X-Content-Type-Options".into(), "nosniff".into()),
],
}
}
fn static_asset(content_type: &str, body: &[u8], immutable: bool) -> HttpResponse {
HttpResponse {
status: 200,
content_type: content_type.into(),
body: body.to_vec(),
www_authenticate: None,
extra_headers: vec![
("X-Content-Type-Options".into(), "nosniff".into()),
(
"Cache-Control".into(),
if immutable {
"public, max-age=31536000, immutable"
} else {
"public, max-age=86400"
}
.into(),
),
],
}
}
pub fn web_ui_page_handler(git_dir: impl Into<PathBuf>) -> PageHandler {
let allow = std::env::var("ARKS_SERVE_ALLOW_LOCAL_ACTIONS")
.ok()
.as_deref()
== Some("1");
web_ui_page_handler_with_actions(git_dir, allow)
}
pub fn web_ui_page_handler_with_actions(
git_dir: impl Into<PathBuf>,
allow_local_actions: bool,
) -> PageHandler {
let dir = git_dir.into();
Arc::new(move |req: &HttpRequest| handle_web_ui_with_actions(&dir, req, allow_local_actions))
}
pub fn handle_web_ui(git_dir: &std::path::Path, req: &HttpRequest) -> Option<HttpResponse> {
handle_web_ui_with_actions(git_dir, req, false)
}
pub fn handle_web_ui_with_actions(
git_dir: &std::path::Path,
req: &HttpRequest,
allow_local_actions: bool,
) -> Option<HttpResponse> {
let resp = handle_web_ui_inner(git_dir, req, allow_local_actions)?;
if resp.content_type.starts_with("text/html") {
let store = store::ForgeStore::load_shared(git_dir);
if let Some((user, csrf)) = auth_api::resolve_session_with_csrf(&store, req) {
return Some(decorate_html_for_session(resp, &user, &csrf));
}
}
Some(resp)
}
pub(crate) fn decorate_html_for_session(
mut resp: HttpResponse,
username: &str,
csrf_token: &str,
) -> HttpResponse {
let Ok(mut html) = String::from_utf8(resp.body.clone()) else {
return resp;
};
let sign_in_btn = "<a class=\"btn\" href=\"/login\">Sign in</a>";
if html.contains(sign_in_btn) {
let signed_in = format!(
"<span class=\"badge badge-green\">@{}</span>\
<form method=\"post\" action=\"/logout\" style=\"display:inline\">\
<button class=\"btn\" type=\"submit\">Sign out</button></form>",
html_escape(username)
);
html = html.replacen(sign_in_btn, &signed_in, 1);
}
let csrf_input = format!(
"<input type=\"hidden\" name=\"_csrf\" value=\"{}\" />",
html_escape(csrf_token)
);
let mut out = String::with_capacity(html.len() + 256);
let mut rest = html.as_str();
while let Some(pos) = rest.find("<form") {
out.push_str(&rest[..pos]);
let after = &rest[pos..];
if let Some(gt) = after.find('>') {
let tag = &after[..=gt];
out.push_str(tag);
let lower_tag = tag.to_ascii_lowercase();
if lower_tag.contains("method=\"post\"") {
out.push_str(&csrf_input);
}
rest = &after[gt + 1..];
} else {
out.push_str(after);
rest = "";
}
}
out.push_str(rest);
resp.body = out.into_bytes();
resp
}
fn handle_web_ui_inner(
git_dir: &std::path::Path,
req: &HttpRequest,
allow_local_actions: bool,
) -> Option<HttpResponse> {
if !matches!(req.method.as_str(), "GET" | "POST" | "PATCH" | "DELETE") {
return None;
}
let path = req.path.as_str();
if path.contains("/info/refs")
|| path.contains("/info/lfs/")
|| path.contains("/git-upload-pack")
|| path.contains("/git-receive-pack")
|| path.starts_with("/objects/")
|| path == "/HEAD"
{
return None;
}
if req.method == "GET" {
match path {
"/style.css" => {
return Some(static_asset(
"text/css; charset=utf-8",
STYLESHEET.as_bytes(),
false,
));
}
"/assets/htmx.min.js" => {
return Some(static_asset(
"application/javascript; charset=utf-8",
HTMX_JS.as_bytes(),
true,
));
}
"/assets/diff2html.min.js" => {
return Some(static_asset(
"application/javascript; charset=utf-8",
DIFF2HTML_JS.as_bytes(),
true,
));
}
"/assets/diff2html.min.css" => {
return Some(static_asset(
"text/css; charset=utf-8",
DIFF2HTML_CSS.as_bytes(),
true,
));
}
"/assets/app.js" => {
return Some(static_asset(
"application/javascript; charset=utf-8",
APP_JS.as_bytes(),
false,
));
}
"/favicon.svg" => {
return Some(static_asset("image/svg+xml", FAVICON_SVG.as_bytes(), false));
}
_ => {}
}
}
let Ok(mut repo) = Repository::open(git_dir) else {
return Some(render_partial(500, "Repository unavailable\n"));
};
let ctx = RepoContext::from_repo(&repo, req.host.as_deref());
let query = req.query.as_str();
if let Some(api_resp) = auth_api::handle_unified_api(&repo, &ctx, req) {
return Some(api_resp);
}
if req.method == "POST" {
if path == "/register" {
return Some(auth_api::handle_register(&repo, &ctx, req));
}
if path == "/login" {
return Some(auth_api::handle_login(&repo, &ctx, req));
}
if path == "/logout" {
return Some(auth_api::handle_logout(&repo, req));
}
if path == "/login/device/code" {
return Some(auth_api::handle_device_code(&repo, &ctx));
}
if path == "/login/device" {
return Some(auth_api::handle_device_approve(&repo, &ctx, req));
}
if path == "/login/oauth/access_token" {
return Some(auth_api::handle_device_token(&repo, req));
}
let store_check = store::ForgeStore::load_shared(repo.common_dir());
if let Err(denied) = auth_api::enforce_write_rbac(&store_check, req) {
return Some(denied);
}
if store_check.archived && path != "/settings/repo" {
return Some(HttpResponse {
status: 403,
content_type: "text/plain; charset=utf-8".into(),
body: b"Forbidden: repository is archived (read-only).\n".to_vec(),
www_authenticate: None,
extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
});
}
if path == "/settings/keys" {
return Some(auth_api::handle_add_ssh_key(&repo, &ctx, req));
}
if path == "/settings/tokens" {
return Some(auth_api::handle_create_token(&repo, &ctx, req));
}
if let Some(rest) = path.strip_prefix("/settings/tokens/") {
if let Some(id_str) = rest.strip_suffix("/revoke") {
return Some(auth_api::handle_revoke_token(&repo, id_str));
}
}
if path == "/settings/webhooks" {
return Some(forge_extras::handle_create_webhook(&repo, &ctx, req));
}
if let Some(rest) = path.strip_prefix("/settings/webhooks/") {
if let Some(id_str) = rest.strip_suffix("/delete") {
return Some(forge_extras::handle_delete_webhook(&repo, id_str));
}
if let Some(id_str) = rest.strip_suffix("/test") {
return Some(forge_extras::handle_test_webhook(&repo, &ctx, id_str));
}
}
if path == "/settings/branches" {
return Some(forge_extras::handle_create_branch_rule(&repo, &ctx, req));
}
if path == "/settings/access" {
return Some(enterprise::handle_access_settings(&repo, req));
}
if path == "/notifications/mark-read" {
return Some(enterprise::handle_mark_notifications_read(&repo, req));
}
if path == "/watch" {
return Some(enterprise::handle_toggle_watch(&repo, req));
}
if let Some(rest) = path.strip_prefix("/settings/branches/") {
if let Some(pat) = rest.strip_suffix("/delete") {
return Some(forge_extras::handle_delete_branch_rule(&repo, pat));
}
}
if path == "/releases" {
return Some(forge_extras::handle_create_release(&repo, &ctx, req));
}
if let Some(rest) = path.strip_prefix("/releases/") {
if let Some(id_str) = rest.strip_suffix("/assets") {
return Some(forge_extras::handle_upload_asset(&repo, &ctx, id_str, req));
}
}
if path == "/pulls/new" {
return Some(forge_extras::handle_create_pr(&repo, &ctx, req));
}
if path == "/issues" {
return Some(forge::handle_create_issue(&repo, &ctx, req));
}
if let Some(rest) = path.strip_prefix("/issues/") {
if let Some((id_str, c_rest)) = rest.split_once("/comments/") {
if let Some(idx_str) = c_rest.strip_suffix("/edit") {
return Some(forge::handle_edit_issue_comment(
&repo, id_str, idx_str, req,
));
}
if let Some(idx_str) = c_rest.strip_suffix("/delete") {
return Some(forge::handle_delete_issue_comment(&repo, id_str, idx_str));
}
}
if let Some(id_str) = rest.strip_suffix("/comment") {
return Some(forge::handle_issue_comment(&repo, &ctx, id_str, req));
}
if let Some(id_str) = rest.strip_suffix("/edit") {
return Some(forge::handle_edit_issue(&repo, id_str, req));
}
if let Some(id_str) = rest.strip_suffix("/delete") {
return Some(forge::handle_delete_issue(&repo, id_str));
}
if let Some(id_str) = rest.strip_suffix("/react") {
return Some(polish::handle_issue_react(&repo, id_str, req));
}
if let Some(id_str) = rest.strip_suffix("/state") {
return Some(forge::handle_issue_state(&repo, &ctx, id_str));
}
if let Some(id_str) = rest.strip_suffix("/meta") {
return Some(forge::handle_issue_meta(&repo, &ctx, id_str, req));
}
}
if let Some(rest) = path.strip_prefix("/pulls/") {
if let Some(branch) = rest.strip_suffix("/edit") {
return Some(forge::handle_edit_pr(&repo, branch, req));
}
if let Some(branch) = rest.strip_suffix("/draft") {
return Some(polish::handle_toggle_pr_draft(&repo, branch));
}
if let Some(branch) = rest.strip_suffix("/reviewers") {
return Some(polish::handle_assign_pr_reviewers(&repo, branch, req));
}
if let Some(branch) = rest.strip_suffix("/state") {
return Some(polish::handle_toggle_pr_state(&repo, branch));
}
if let Some(branch) = rest.strip_suffix("/inline-comment") {
return Some(forge_extras::handle_inline_comment(
&repo, &ctx, branch, req,
));
}
if let Some((branch_part, id_part)) = rest.rsplit_once("/inline-comment/") {
if let Some(id_str) = id_part.strip_suffix("/resolve") {
return Some(forge_extras::handle_resolve_inline(
&repo,
branch_part,
id_str,
));
}
}
if let Some(branch) = rest.strip_suffix("/review") {
return Some(forge_extras::handle_pr_review_verdict(&repo, branch, req));
}
if let Some(branch) = rest.strip_suffix("/comment") {
return Some(forge::handle_pr_comment(&repo, branch, req));
}
if let Some(branch) = rest.strip_suffix("/merge") {
return Some(forge::handle_pr_merge(&mut repo, &ctx, branch, req));
}
if let Some(branch) = rest.strip_suffix("/delete-branch") {
return Some(forge::handle_pr_delete_branch(&mut repo, &ctx, branch));
}
}
if path == "/actions/run" {
return Some(actions::handle_run_workflow(
&repo,
&ctx,
req,
allow_local_actions,
));
}
if let Some(rest) = path.strip_prefix("/actions/runs/") {
if let Some(id_str) = rest.strip_suffix("/cancel") {
return Some(actions::handle_cancel_workflow_run(
&repo,
&ctx,
id_str,
allow_local_actions,
));
}
if let Some(id_str) = rest.strip_suffix("/rerun") {
return Some(polish::handle_rerun_workflow(
&repo,
&ctx,
id_str,
req,
allow_local_actions,
));
}
if let Some(id_str) = rest.strip_suffix("/artifacts") {
return Some(admin_2fa::handle_upload_artifact(&repo, &ctx, id_str, req));
}
}
if path == "/settings/repo" {
return Some(polish::handle_repo_settings(&repo, req));
}
if path == "/settings/profile/password" {
return Some(polish::handle_change_password(&repo, &ctx, req));
}
if path == "/settings/profile/sessions/revoke" {
return Some(polish::handle_revoke_other_sessions(&repo, req));
}
if path == "/agents/leases/unlock" {
return Some(polish::handle_force_unlock_lease(&repo, req));
}
if path == "/markdown/preview" {
return Some(polish::handle_markdown_preview(req));
}
if path == "/settings/2fa" {
return Some(admin_2fa::handle_enable_2fa(&repo, &ctx, req));
}
if path == "/settings/2fa/disable" {
return Some(admin_2fa::handle_disable_2fa(&repo, &ctx, req));
}
if path == "/settings/secrets" {
return Some(actions::handle_upsert_secret(&repo, req));
}
if let Some(rest) = path.strip_prefix("/settings/secrets/") {
if let Some(name) = rest.strip_suffix("/delete") {
return Some(actions::handle_delete_secret(&repo, name));
}
}
if let Some(rest) = path.strip_prefix("/admin/users/") {
if let Some(username) = rest.strip_suffix("/role") {
if let Err(denied) = auth_api::enforce_admin_rbac(&store_check, req) {
return Some(denied);
}
return Some(admin_2fa::handle_admin_update_role(&repo, username, req));
}
}
if let Some(rest) = path.strip_prefix("/edit/") {
let (rev, subpath) = split_rev_and_path(rest);
return Some(editor::handle_save_file(&mut repo, &ctx, rev, subpath, req));
}
if let Some(rest) = path.strip_prefix("/delete/") {
let (rev, subpath) = split_rev_and_path(rest);
return Some(editor::handle_delete_file(
&mut repo, &ctx, rev, subpath, req,
));
}
if let Some(rev) = path.strip_prefix("/upload/") {
if !rev.is_empty() {
return Some(editor::handle_upload_file(&mut repo, &ctx, rev, req));
}
}
if let Some(rev) = path.strip_prefix("/new/") {
if !rev.is_empty() {
return Some(editor::handle_create_file(&mut repo, &ctx, rev, req));
}
}
if path == "/branches/create" {
return Some(editor::handle_create_branch(&mut repo, &ctx, req));
}
if path == "/tags/create" {
return Some(editor::handle_create_tag(&mut repo, &ctx, req));
}
if path == "/projects/cards" {
return Some(projects_wiki::handle_create_card(&repo, &ctx, req));
}
if let Some(rest) = path.strip_prefix("/projects/cards/") {
if let Some(id_str) = rest.strip_suffix("/move") {
return Some(projects_wiki::handle_move_card(&repo, &ctx, id_str, req));
}
if let Some(id_str) = rest.strip_suffix("/delete") {
return Some(projects_wiki::handle_delete_card(&repo, &ctx, id_str));
}
}
if path == "/wiki" {
return Some(projects_wiki::handle_upsert_wiki(&repo, &ctx, None, req));
}
if let Some(rest) = path.strip_prefix("/wiki/") {
if let Some(slug) = rest.strip_suffix("/delete") {
return Some(projects_wiki::handle_delete_wiki(&repo, &ctx, slug));
}
if !rest.is_empty() && !rest.contains('/') {
return Some(projects_wiki::handle_upsert_wiki(
&repo,
&ctx,
Some(rest),
req,
));
}
}
return Some(render_page(
405,
&ctx,
ActiveTab::Code,
"405 Method Not Allowed",
"<div class=\"card\"><div class=\"card-body\">Method not allowed for this route.</div></div>",
));
}
if path == "/robots.txt" {
return Some(HttpResponse {
status: 200,
content_type: "text/plain; charset=utf-8".into(),
body: b"User-agent: *\nDisallow: /admin\nDisallow: /settings\n".to_vec(),
www_authenticate: None,
extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
});
}
if path == "/login" {
return Some(auth_api::render_login(&repo, &ctx));
}
if path == "/register" {
return Some(auth_api::render_register(&repo, &ctx));
}
if path == "/login/device" {
return Some(auth_api::render_device_approve(&repo, &ctx));
}
let vis_store = store::ForgeStore::load_shared(repo.common_dir());
if let Err(denied) = auth_api::enforce_read_visibility(&vis_store, req) {
return Some(denied);
}
if path == "/settings/keys" {
return Some(auth_api::render_ssh_keys(&repo, &ctx, req));
}
if path == "/settings/tokens" {
return Some(auth_api::render_tokens(&repo, &ctx, req));
}
if path == "/settings/webhooks" {
return Some(forge_extras::render_webhooks(&repo, &ctx));
}
if path == "/settings/branches" {
return Some(forge_extras::render_branch_rules(&repo, &ctx));
}
if path == "/settings/access" {
return Some(enterprise::render_access_settings(&repo, &ctx));
}
if path == "/settings/2fa" {
return Some(admin_2fa::render_2fa_settings(&repo, &ctx, req));
}
if path == "/settings/secrets" {
return Some(actions::render_secrets_settings(&repo, &ctx));
}
if let Some(file) = path.strip_prefix("/archive/") {
if !file.is_empty() {
return Some(archives::handle_archive_download(&repo, &ctx.name, file));
}
}
if let Some(rest) = path.strip_prefix("/commit/") {
if let Some(rev) = rest.strip_suffix(".patch") {
return Some(archives::handle_commit_patch(&repo, rev, true));
}
if let Some(rev) = rest.strip_suffix(".diff") {
return Some(archives::handle_commit_patch(&repo, rev, false));
}
}
if let Some(rest) = path.strip_prefix("/pulls/") {
if let Some(branch) = rest.strip_suffix(".patch") {
return Some(archives::handle_pr_patch(
&repo,
&ctx.default_branch,
branch,
true,
));
}
if let Some(branch) = rest.strip_suffix(".diff") {
return Some(archives::handle_pr_patch(
&repo,
&ctx.default_branch,
branch,
false,
));
}
}
if path == "/settings/repo" {
return Some(polish::render_repo_settings(&repo, &ctx));
}
if path == "/settings/profile" {
return Some(polish::render_profile_settings(&repo, &ctx, req));
}
if path == "/commits.atom" {
return Some(polish::render_commits_atom(&repo, &ctx));
}
if path == "/releases.atom" {
return Some(polish::render_releases_atom(&repo, &ctx));
}
if let Some(rest) = path.strip_prefix("/actions/runs/") {
if let Some(id_str) = rest.strip_suffix("/log-partial") {
return Some(polish::render_action_log_partial(&repo, id_str));
}
}
if path == "/admin/audit/verify" {
let store_check = store::ForgeStore::load_shared(repo.common_dir());
if let Err(denied) = auth_api::enforce_admin_rbac(&store_check, req) {
return Some(denied);
}
return Some(admin_2fa::handle_verify_audit_chain(&repo));
}
if path == "/admin/audit.csv" || path == "/admin/audit.jsonl" {
let store_check = store::ForgeStore::load_shared(repo.common_dir());
if let Err(denied) = auth_api::enforce_admin_rbac(&store_check, req) {
return Some(denied);
}
return Some(polish::export_audit_log(&repo, path.ends_with(".jsonl")));
}
if path == "/admin" {
let store_check = store::ForgeStore::load_shared(repo.common_dir());
if let Err(denied) = auth_api::enforce_admin_rbac(&store_check, req) {
return Some(denied);
}
return Some(admin_2fa::render_admin_dashboard(&repo, &ctx, query));
}
if path == "/agents" {
return Some(enterprise::render_agents_dashboard(&repo, &ctx));
}
if path == "/releases" {
return Some(forge_extras::render_releases(&repo, &ctx));
}
if let Some(rest) = path.strip_prefix("/releases/") {
if let Some((id_str, filename)) = rest.split_once("/assets/") {
return Some(forge_extras::handle_download_asset(&repo, id_str, filename));
}
}
if path == "/pulls/new" {
return Some(forge_extras::render_new_pr(&repo, &ctx));
}
if path == "/" || path.is_empty() {
return Some(code::render_tree(&repo, &ctx, &ctx.default_branch, ""));
}
if path == "/search" {
return Some(code::render_search_partial(&repo, &ctx, query));
}
if path == "/notifications" {
return Some(editor::render_notifications(&repo, &ctx, query));
}
if let Some(rest) = path.strip_prefix("/edit/") {
let (rev, subpath) = split_rev_and_path(rest);
return Some(editor::render_edit_file(&repo, &ctx, rev, subpath));
}
if let Some(rev) = path.strip_prefix("/new/") {
if !rev.is_empty() {
return Some(editor::render_new_file(&repo, &ctx, rev));
}
}
if path == "/branches" || path == "/refs" {
return Some(code::render_branches(&ctx));
}
if path == "/tags" {
return Some(code::render_tags(&ctx));
}
if path == "/commits" {
return Some(code::render_commits(
&repo,
&ctx,
&ctx.default_branch,
query,
));
}
if let Some(rev) = path.strip_prefix("/commits/") {
return Some(code::render_commits(&repo, &ctx, rev, query));
}
if let Some(oid_str) = path.strip_prefix("/commit/") {
return Some(diff::render_commit(&repo, &ctx, oid_str));
}
if path == "/compare" {
return Some(diff::render_compare(&repo, &ctx, ""));
}
if let Some(spec) = path.strip_prefix("/compare/") {
return Some(diff::render_compare(&repo, &ctx, spec));
}
if let Some(rest) = path.strip_prefix("/tree/") {
let (rev, subpath) = split_rev_and_path(rest);
return Some(code::render_tree(&repo, &ctx, rev, subpath));
}
if let Some(rest) = path.strip_prefix("/blob/") {
let (rev, subpath) = split_rev_and_path(rest);
return Some(code::render_blob(&repo, &ctx, rev, subpath));
}
if let Some(rest) = path.strip_prefix("/blame/") {
let (rev, subpath) = split_rev_and_path(rest);
return Some(code::render_blame(&repo, &ctx, rev, subpath));
}
if let Some(rest) = path.strip_prefix("/raw/") {
let (rev, subpath) = split_rev_and_path(rest);
return Some(code::render_raw(&repo, rev, subpath));
}
if path == "/issues" {
return Some(forge::render_issues(&repo, &ctx, query));
}
if let Some(id_str) = path.strip_prefix("/issues/") {
if id_str.chars().all(|c| c.is_ascii_digit()) && !id_str.is_empty() {
return Some(forge::render_issue_detail(&repo, &ctx, id_str));
}
}
if path == "/pulls" {
return Some(forge::render_pulls(&repo, &ctx));
}
if let Some(branch) = path.strip_prefix("/pulls/") {
if !branch.is_empty() {
return Some(forge::render_pr_detail(&repo, &ctx, branch));
}
}
if path == "/actions" {
return Some(actions::render_actions(&repo, &ctx, allow_local_actions));
}
if let Some(rest) = path.strip_prefix("/actions/runs/") {
if let Some((id_str, name)) = rest.split_once("/artifacts/") {
return Some(admin_2fa::handle_download_artifact(&repo, id_str, name));
}
if let Some(id_str) = rest.strip_suffix("/stream") {
return Some(actions::render_action_run_stream(&repo, id_str));
}
if rest.chars().all(|c| c.is_ascii_digit()) && !rest.is_empty() {
return Some(actions::render_action_run(&repo, &ctx, rest));
}
}
if path == "/projects" {
return Some(projects_wiki::render_projects(&repo, &ctx));
}
if path == "/wiki" {
return Some(projects_wiki::render_wiki(&repo, &ctx));
}
if let Some(slug) = path.strip_prefix("/wiki/") {
if !slug.is_empty() && !slug.contains('/') {
return Some(projects_wiki::render_wiki_page(&repo, &ctx, slug));
}
}
if path == "/security" {
return Some(forge::render_security(&repo, &ctx));
}
if path == "/insights" {
return Some(forge::render_insights(&repo, &ctx));
}
if path == "/settings" {
return Some(forge::render_settings(&repo, &ctx));
}
Some(render_page(
404,
&ctx,
ActiveTab::Code,
"404 Not Found",
"<div class=\"card\"><div class=\"card-body\">Page not found.</div></div>",
))
}
fn split_rev_and_path(rest: &str) -> (&str, &str) {
match rest.split_once('/') {
Some((r, p)) => (r, p),
None => (rest, ""),
}
}
pub(crate) fn head_branch_label(repo: &Repository) -> String {
match repo.head_target() {
Ok(RefTarget::Symbolic(s)) => s.strip_prefix("refs/heads/").unwrap_or(&s).to_string(),
Ok(RefTarget::Direct(o)) => o.to_hex()[..7.min(o.to_hex().len())].to_string(),
Err(_) => "HEAD".into(),
}
}
pub(crate) fn resolve_rev_oid(repo: &Repository, rev: &str) -> Option<Oid> {
if rev == "HEAD" {
return repo.refs().resolve("HEAD").ok();
}
if let Ok(oid) = Oid::from_hex(rev) {
if repo.get_object(&oid).is_ok() {
return Some(oid);
}
}
for candidate in [
rev.to_string(),
format!("refs/heads/{rev}"),
format!("refs/tags/{rev}"),
] {
if let Ok(oid) = repo.refs().resolve(&candidate) {
return Some(oid);
}
}
None
}
pub(crate) fn load_commit(repo: &Repository, oid: &Oid) -> Option<Commit> {
let obj = repo.get_object(oid).ok()?;
if obj.kind != ObjectKind::Commit {
return None;
}
Commit::decode(&obj.payload).ok()
}
pub(crate) fn load_tree(repo: &Repository, oid: &Oid) -> Option<arks_object::Tree> {
let obj = repo.get_object(oid).ok()?;
if obj.kind != ObjectKind::Tree {
return None;
}
arks_object::Tree::decode(&obj.payload, repo.oid_kind()).ok()
}
pub(crate) fn load_blob(repo: &Repository, oid: &Oid) -> Option<Vec<u8>> {
let obj = repo.get_object(oid).ok()?;
if obj.kind != ObjectKind::Blob {
return None;
}
Some(obj.payload)
}
pub(crate) fn commit_has_sig(commit: &Commit) -> bool {
commit.gpgsig.is_some()
}
pub(crate) fn collect_recent_commits(
repo: &Repository,
start: Oid,
limit: usize,
) -> Vec<(Oid, Commit)> {
let mut out = Vec::new();
let mut visited = HashSet::new();
let mut cur = Some(start);
while let Some(oid) = cur {
if out.len() >= limit || !visited.insert(oid) {
break;
}
let Some(commit) = load_commit(repo, &oid) else {
break;
};
let next = commit.parents.first().copied();
out.push((oid, commit));
cur = next;
}
out
}
pub(crate) fn format_timestamp(ts: i64) -> String {
if ts <= 0 {
return "1970-01-01 00:00 UTC".into();
}
let secs_per_day = 86_400i64;
let z = ts.div_euclid(secs_per_day) + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097) as u64;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = (yoe as i64) + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let year = y + if m <= 2 { 1 } else { 0 };
let rem = ts.rem_euclid(secs_per_day);
let hour = rem / 3600;
let min = (rem % 3600) / 60;
let now = store::now_unix();
let rel = if now >= ts {
let diff = now - ts;
if diff < 60 {
"just now".into()
} else if diff < 3600 {
format!("{}m ago", diff / 60)
} else if diff < 86_400 {
format!("{}h ago", diff / 3600)
} else {
format!("{}d ago", diff / 86_400)
}
} else {
"upcoming".into()
};
format!("{year:04}-{m:02}-{d:02} {hour:02}:{min:02} UTC ({rel})")
}