use super::store::parse_form_urlencoded;
use super::{WEB_UI_CSP, handle_web_ui_with_actions, html_escape, redirect_see_other};
use crate::http::{HttpRequest, HttpResponse, handle_smart_http_auth_opts};
use crate::serve::PageHandler;
use arks_repo::Repository;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
fn is_valid_repo_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 80
&& !name.starts_with('.')
&& !name.contains("..")
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
}
fn resolve_repo_git_dir(root: &Path, name: &str) -> Option<PathBuf> {
let bare_name = name.trim_end_matches(".git");
if !is_valid_repo_name(bare_name) {
return None;
}
let bare = root.join(format!("{bare_name}.git"));
if bare.join("HEAD").is_file() {
return Some(bare);
}
let non_bare = root.join(bare_name).join(".git");
if non_bare.join("HEAD").is_file() {
return Some(non_bare);
}
let direct = root.join(bare_name);
if direct.join("HEAD").is_file() {
return Some(direct);
}
None
}
fn list_repos(root: &Path) -> Vec<(String, PathBuf, String)> {
let mut out = Vec::new();
let Ok(rd) = fs::read_dir(root) else {
return out;
};
for ent in rd.flatten() {
let path = ent.path();
if !path.is_dir() {
continue;
}
let raw_name = ent.file_name().to_string_lossy().into_owned();
if raw_name.starts_with('.') {
continue;
}
let git_dir = if path.join("HEAD").is_file() {
path.clone()
} else if path.join(".git").join("HEAD").is_file() {
path.join(".git")
} else {
continue;
};
let display = raw_name.trim_end_matches(".git").to_string();
let desc = fs::read_to_string(git_dir.join("description"))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty() && !s.starts_with("Unnamed repository"))
.unwrap_or_else(|| "Self-hosted Git repository".into());
out.push((display, git_dir, desc));
}
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
pub fn init_bare_repo(root: &Path, name: &str, description: &str) -> Result<PathBuf, String> {
let clean = name.trim().trim_end_matches(".git");
if !is_valid_repo_name(clean) {
return Err("Invalid repository name (use alphanumeric, '-', '_', '.')".into());
}
let target = root.join(format!("{clean}.git"));
if target.exists() {
return Err(format!("Repository '{clean}' already exists"));
}
fs::create_dir_all(target.join("objects").join("info")).map_err(|e| e.to_string())?;
fs::create_dir_all(target.join("objects").join("pack")).map_err(|e| e.to_string())?;
fs::create_dir_all(target.join("refs").join("heads")).map_err(|e| e.to_string())?;
fs::create_dir_all(target.join("refs").join("tags")).map_err(|e| e.to_string())?;
fs::write(target.join("HEAD"), "ref: refs/heads/main\n").map_err(|e| e.to_string())?;
fs::write(
target.join("config"),
"[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = true\n[http]\n\treceivepack = true\n",
)
.map_err(|e| e.to_string())?;
let desc = if description.trim().is_empty() {
format!("{clean} — served by arks")
} else {
description.trim().to_string()
};
fs::write(target.join("description"), format!("{desc}\n")).map_err(|e| e.to_string())?;
Ok(target)
}
pub fn multi_repo_page_handler(
root_dir: impl Into<PathBuf>,
allow_local_actions: bool,
) -> PageHandler {
let root = root_dir.into();
Arc::new(move |req: &HttpRequest| handle_multi_repo(&root, req, allow_local_actions))
}
pub fn handle_multi_repo(
root: &Path,
req: &HttpRequest,
allow_local_actions: bool,
) -> Option<HttpResponse> {
let path = req.path.as_str();
let host = req.host.as_deref().unwrap_or("127.0.0.1:8080");
if req.method == "GET" && (path == "/" || path.is_empty()) {
let resp = render_dashboard(root, host, req);
let global_dir = root.join(".arks-global-auth");
let gstore = super::store::ForgeStore::load(&global_dir);
if let Some((user, csrf)) = super::auth_api::resolve_session_with_csrf(&gstore, req) {
return Some(super::decorate_html_for_session(resp, &user, &csrf));
}
return Some(resp);
}
if req.method == "GET" && path == "/robots.txt" {
return Some(HttpResponse {
status: 200,
content_type: "text/plain; charset=utf-8".into(),
body: b"User-agent: *\nDisallow: /admin\nDisallow: /settings\nDisallow: /api/\n"
.to_vec(),
www_authenticate: None,
extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
});
}
if req.method == "GET" && path == "/search" {
return Some(render_cross_repo_search(root, &req.query, req));
}
if matches!(path, "/register" | "/login" | "/logout") {
let global_dir = root.join(".arks-global-auth");
let _ = fs::create_dir_all(&global_dir);
let ctx = super::RepoContext {
name: "arks Multi-Repo Forge".into(),
description: "Global multi-repository authentication".into(),
default_branch: "main".into(),
branches: Vec::new(),
tags: Vec::new(),
clone_url: format!("http://{host}/"),
has_lfs: false,
};
if req.method == "GET" && path == "/register" {
return Some(render_root_auth_form("Create Global Account", "/register"));
}
if req.method == "GET" && path == "/login" {
return Some(render_root_auth_form("Sign in (Global)", "/login"));
}
if req.method == "POST" && path == "/register" {
if super::auth_api::registration_disabled() {
return Some(super::render_page(
403,
&ctx,
super::ActiveTab::Settings,
"Registration Disabled",
"Public self-registration is disabled by operator policy (ARKS_DISABLE_REGISTRATION).",
));
}
let form = parse_form_urlencoded(&req.body);
let username = form.get("username").map(|s| s.trim()).unwrap_or("");
let password = form.get("password").map(|s| s.as_str()).unwrap_or("");
if username.is_empty() || password.len() < 4 {
return Some(super::render_page(
400,
&ctx,
super::ActiveTab::Settings,
"Invalid registration",
"Username required and password must be at least 4 characters.",
));
}
let mut gstore = super::store::ForgeStore::lock_mut(&global_dir);
if gstore.users.iter().any(|u| u.username == username) {
return Some(super::render_page(
409,
&ctx,
super::ActiveTab::Settings,
"User exists",
"Username already exists.",
));
}
let role = if gstore.users.is_empty() {
"admin"
} else {
super::auth_api::default_registration_role()
};
let now = super::store::now_unix();
gstore.users.push(super::store::UserAccount {
username: username.to_string(),
password_hash: super::auth_api::hash_user_password(username, password),
role: role.into(),
ssh_keys: Vec::new(),
created_at: now,
totp_secret_b32: None,
recovery_codes: Vec::new(),
});
let tok = super::auth_api::generate_token("arks_gsess_");
let csrf = super::auth_api::generate_token("csrf_g_");
gstore.sessions.push(super::store::SessionRecord {
token: tok.clone(),
username: username.to_string(),
csrf_token: csrf,
expires_at: now + 86400 * 30,
});
let _ = gstore.commit();
return Some(HttpResponse {
status: 303,
content_type: "text/plain; charset=utf-8".into(),
body: Vec::new(),
www_authenticate: None,
extra_headers: vec![
("Location".into(), "/".into()),
(
"Set-Cookie".into(),
super::auth_api::session_cookie_header(&tok, req, false),
),
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
],
});
}
if req.method == "POST" && path == "/login" {
let form = parse_form_urlencoded(&req.body);
let username = form.get("username").map(|s| s.trim()).unwrap_or("");
let password = form.get("password").map(String::as_str).unwrap_or("");
if super::auth_api::is_login_rate_limited(username) {
let mut resp = super::render_page(
429,
&ctx,
super::ActiveTab::Settings,
"Too Many Requests",
"<div class=\"card\"><div class=\"card-body\">Too many failed login attempts. Try again in 60 seconds.</div></div>",
);
resp.extra_headers.push(("Retry-After".into(), "60".into()));
return Some(resp);
}
let mut gstore = super::store::ForgeStore::lock_mut(&global_dir);
let Some(acct) = gstore
.users
.iter()
.find(|u| {
u.username == username
&& super::auth_api::verify_user_password(
username,
password,
&u.password_hash,
)
})
.cloned()
else {
super::auth_api::record_login_failure(username);
return Some(super::render_page(
401,
&ctx,
super::ActiveTab::Settings,
"Invalid credentials",
"<div class=\"card\"><div class=\"card-body\">Invalid username or password.</div></div>",
));
};
if let Some(ref secret) = acct.totp_secret_b32 {
let totp = form.get("totp").map(|s| s.trim()).unwrap_or("");
let totp_ok =
super::admin_2fa::verify_totp_window(secret, totp, super::store::now_unix());
let mut used_recovery = false;
if !totp_ok {
if let Some(u) = gstore.users.iter_mut().find(|u| u.username == username) {
if let Some(pos) = u
.recovery_codes
.iter()
.position(|c| super::auth_api::ct_str_eq(c, totp))
{
u.recovery_codes.remove(pos);
used_recovery = true;
}
}
}
if !totp_ok && !used_recovery {
super::auth_api::record_login_failure(username);
return Some(super::render_page(
401,
&ctx,
super::ActiveTab::Settings,
"2FA Required",
"<div class=\"card\"><div class=\"card-body\">Valid 6-digit TOTP 2FA code or recovery code required.</div></div>",
));
}
}
let now = super::store::now_unix();
let tok = super::auth_api::generate_token("arks_gsess_");
let csrf = super::auth_api::generate_token("csrf_g_");
gstore.sessions.push(super::store::SessionRecord {
token: tok.clone(),
username: username.to_string(),
csrf_token: csrf,
expires_at: now + 86400 * 30,
});
let _ = gstore.commit();
return Some(HttpResponse {
status: 303,
content_type: "text/plain; charset=utf-8".into(),
body: Vec::new(),
www_authenticate: None,
extra_headers: vec![
("Location".into(), "/".into()),
(
"Set-Cookie".into(),
super::auth_api::session_cookie_header(&tok, req, false),
),
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
],
});
}
if req.method == "POST" && path == "/logout" {
let mut gstore = super::store::ForgeStore::lock_mut(&global_dir);
let mut revoked_tokens = Vec::new();
if let Some(ref cookie_hdr) = req.cookie {
for part in cookie_hdr.split(';') {
if let Some(val) = part.trim().strip_prefix("arks_session=") {
gstore.sessions.retain(|s| s.token != val);
revoked_tokens.push(val.to_string());
}
}
}
let _ = gstore.commit();
if !revoked_tokens.is_empty() {
for (_, git_dir, _) in list_repos(root) {
let mut rstore = super::store::ForgeStore::lock_mut(&git_dir);
let before = rstore.sessions.len();
rstore
.sessions
.retain(|s| !revoked_tokens.iter().any(|t| t == &s.token));
if rstore.sessions.len() != before {
let _ = rstore.commit();
}
}
}
return Some(HttpResponse {
status: 303,
content_type: "text/plain; charset=utf-8".into(),
body: Vec::new(),
www_authenticate: None,
extra_headers: vec![
("Location".into(), "/login".into()),
(
"Set-Cookie".into(),
super::auth_api::session_cookie_header("", req, true),
),
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
],
});
}
}
if req.method == "POST" && path == "/new-repo" {
let global_dir = root.join(".arks-global-auth");
let gstore = super::store::ForgeStore::load(&global_dir);
if let Err(denied) = super::auth_api::enforce_write_rbac(&gstore, req) {
return Some(denied);
}
let form = parse_form_urlencoded(&req.body);
let name = form.get("name").map(|s| s.trim()).unwrap_or("");
let desc = form.get("description").map(|s| s.trim()).unwrap_or("");
return match init_bare_repo(root, name, desc) {
Ok(_) => {
let clean = name.trim().trim_end_matches(".git");
Some(redirect_see_other(&format!("/{clean}/")))
}
Err(e) => Some(HttpResponse {
status: 400,
content_type: "text/plain; charset=utf-8".into(),
body: format!("Failed to create repository: {e}\n").into_bytes(),
www_authenticate: None,
extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
}),
};
}
if req.method == "GET" && path == "/style.css" {
return Some(HttpResponse {
status: 200,
content_type: "text/css; charset=utf-8".into(),
body: super::STYLESHEET.as_bytes().to_vec(),
www_authenticate: None,
extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
});
}
if req.method == "GET" && path == "/favicon.svg" {
return Some(HttpResponse {
status: 200,
content_type: "image/svg+xml".into(),
body: super::FAVICON_SVG.as_bytes().to_vec(),
www_authenticate: None,
extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
});
}
if req.method == "GET" && path.starts_with("/assets/") {
if let Some((_, first_git, _)) = list_repos(root).into_iter().next() {
return handle_web_ui_with_actions(&first_git, req, allow_local_actions);
}
}
let trimmed = path.strip_prefix('/').unwrap_or(path);
let (repo_seg, rest) = match trimmed.split_once('/') {
Some((r, p)) => (r, format!("/{p}")),
None => (trimmed, "/".to_string()),
};
let git_dir = resolve_repo_git_dir(root, repo_seg)?;
sync_global_auth_into_repo(root, &git_dir);
if req.method == "POST" && rest == "/settings/repo/delete" {
let gstore = super::store::ForgeStore::load(&root.join(".arks-global-auth"));
let rbac_store = if gstore.users.is_empty() {
super::store::ForgeStore::load(&git_dir)
} else {
gstore
};
if let Err(denied) = super::auth_api::enforce_admin_rbac(&rbac_store, req) {
return Some(denied);
}
let form = parse_form_urlencoded(&req.body);
let clean = repo_seg.trim_end_matches(".git");
let confirm = form.get("confirm").map(|s| s.trim()).unwrap_or("");
if confirm != clean {
return Some(HttpResponse {
status: 400,
content_type: "text/plain; charset=utf-8".into(),
body: format!("Confirmation mismatch: type '{clean}' to delete repository.\n")
.into_bytes(),
www_authenticate: None,
extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
});
}
let _ = fs::remove_dir_all(&git_dir);
return Some(redirect_see_other("/"));
}
let mut sub_req = req.clone();
sub_req.path = rest.clone();
if rest.contains("/info/refs")
|| rest.contains("/info/lfs/")
|| rest.contains("/git-upload-pack")
|| rest.contains("/git-receive-pack")
|| rest.starts_with("/objects/")
|| rest == "/HEAD"
{
let is_write = rest.contains("/git-receive-pack")
|| (rest.contains("/info/refs") && sub_req.query.contains("git-receive-pack"))
|| (rest.contains("/info/lfs/") && sub_req.method == "PUT");
if let Err(denied) = super::auth_api::check_git_http_auth(&git_dir, &sub_req, is_write) {
return Some(denied);
}
let Ok(mut repo) = Repository::open(&git_dir) else {
return Some(HttpResponse {
status: 500,
content_type: "text/plain".into(),
body: b"repository open failed\n".to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
});
};
return match handle_smart_http_auth_opts(&mut repo, &sub_req, None, true, "http") {
Ok(resp) => Some(resp),
Err(e) => Some(HttpResponse {
status: 500,
content_type: "text/plain".into(),
body: format!("{e}\n").into_bytes(),
www_authenticate: None,
extra_headers: Vec::new(),
}),
};
}
let prefix = format!("/{}", repo_seg.trim_end_matches(".git"));
handle_web_ui_with_actions(&git_dir, &sub_req, allow_local_actions)
.map(|resp| rewrite_response_for_repo_prefix(resp, &prefix))
}
pub(crate) fn rewrite_response_for_repo_prefix(
mut resp: HttpResponse,
prefix: &str,
) -> HttpResponse {
for (k, v) in &mut resp.extra_headers {
if k.eq_ignore_ascii_case("location") {
*v = rewrite_repo_prefix_location(v, prefix);
}
}
if resp.content_type.starts_with("text/html") {
if let Ok(html) = String::from_utf8(resp.body.clone()) {
resp.body = rewrite_repo_prefix_html(&html, prefix).into_bytes();
}
}
resp
}
fn is_shared_root_asset(path: &str) -> bool {
path == "/style.css"
|| path == "/favicon.svg"
|| path.starts_with("/assets/")
|| path.starts_with("//")
}
pub(crate) fn rewrite_repo_prefix_location(loc: &str, prefix: &str) -> String {
if !loc.starts_with('/')
|| is_shared_root_asset(loc)
|| loc.starts_with(&format!("{prefix}/"))
|| loc == prefix
{
return loc.to_string();
}
format!("{prefix}{loc}")
}
pub(crate) fn rewrite_repo_prefix_html(html: &str, prefix: &str) -> String {
let mut out = html.to_string();
for attr in ["href=\"/", "action=\"/", "hx-get=\"/", "hx-post=\"/"] {
let mut rebuilt = String::with_capacity(out.len() + 256);
let mut rest = out.as_str();
while let Some(pos) = rest.find(attr) {
rebuilt.push_str(&rest[..pos]);
let after_quote = &rest[pos + attr.len() - 1..]; let end_quote = after_quote.find('"').unwrap_or(after_quote.len());
let target = &after_quote[..end_quote];
let attr_prefix = &attr[..attr.len() - 1]; rebuilt.push_str(attr_prefix);
if is_shared_root_asset(target)
|| target == prefix
|| target.starts_with(&format!("{prefix}/"))
{
rebuilt.push_str(target);
} else {
rebuilt.push_str(prefix);
rebuilt.push_str(target);
}
rest = &after_quote[end_quote..];
}
rebuilt.push_str(rest);
out = rebuilt;
}
out
}
fn render_dashboard(root: &Path, host: &str, req: &HttpRequest) -> HttpResponse {
let repos = list_repos(root);
let mut rows = String::new();
let mut visible_count = 0usize;
for (name, git_dir, desc) in &repos {
sync_global_auth_into_repo(root, git_dir);
let rstore = super::store::ForgeStore::load(git_dir);
if !super::auth_api::can_read_repo(&rstore, req) {
continue;
}
visible_count += 1;
let clone_url = format!("http://{host}/{name}.git");
let vis_badge = if rstore.visibility == "private" {
" <span class=\"badge\">private</span>"
} else {
""
};
rows.push_str(&format!(
"<tr><td><a href=\"/{}/\"><strong>{}</strong></a>{vis_badge}\
<div class=\"muted\">{}</div></td>\
<td class=\"mono mr-clone-cell\"><code>arks clone {}</code></td>\
<td class=\"mr-action-cell\"><a class=\"btn\" href=\"/{}/\">Open</a></td></tr>",
html_escape(name),
html_escape(name),
html_escape(desc),
html_escape(&clone_url),
html_escape(name),
));
}
if rows.is_empty() {
rows.push_str(
"<tr><td colspan=\"3\" class=\"muted\">No repositories yet. Create your first repository below.</td></tr>",
);
}
let html = format!(
"<!doctype html><html lang=\"en\" data-theme=\"dark\"><head><meta charset=\"utf-8\">\
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
<title>arks Multi-Repo Forge</title>\
<link rel=\"stylesheet\" href=\"/style.css\"></head><body>\
<header class=\"mr-header\">\
<div class=\"mr-header-inner\">\
<div class=\"mr-brand\">\
<a href=\"/\"><strong>arks Multi-Repo Forge</strong></a>\
<span class=\"badge badge-green\">{visible_count} repos</span>\
<a class=\"muted\" href=\"/search\">Search</a>\
<a class=\"muted\" href=\"/healthz\">Health</a>\
</div>\
<form class=\"mr-search-form\" method=\"get\" action=\"/search\">\
<input class=\"input\" type=\"search\" name=\"q\" placeholder=\"Search across repos...\" />\
<button class=\"btn\" type=\"submit\">Search</button>\
</form>\
<div class=\"mr-auth-actions\">\
<a class=\"btn\" href=\"/login\">Sign in</a>\
<a class=\"btn\" href=\"/register\">Register</a>\
</div>\
</div>\
</header>\
<main class=\"mr-main\">\
<div class=\"card\"><div class=\"card-header\"><strong>Repositories</strong></div>\
<table class=\"tree-table\">{rows}</table></div>\
<div class=\"card\"><div class=\"card-header\"><strong>New Repository</strong></div>\
<form class=\"card-body mr-new-repo-form\" method=\"post\" action=\"/new-repo\">\
<input class=\"input\" type=\"text\" name=\"name\" placeholder=\"Repository name (e.g. backend)\" required />\
<input class=\"input mr-new-repo-desc\" type=\"text\" name=\"description\" placeholder=\"Description (optional)\" />\
<button class=\"btn btn-primary\" type=\"submit\">Create Repository</button>\
</form></div>\
</main></body></html>"
);
HttpResponse {
status: 200,
content_type: "text/html; charset=utf-8".into(),
body: html.into_bytes(),
www_authenticate: None,
extra_headers: vec![
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
("X-Content-Type-Options".into(), "nosniff".into()),
],
}
}
fn sync_global_auth_into_repo(root: &Path, git_dir: &Path) {
let global_dir = root.join(".arks-global-auth");
if !global_dir.exists() {
return;
}
let gstore = super::store::ForgeStore::load(&global_dir);
let mut rstore = super::store::ForgeStore::lock_mut(git_dir);
let mut changed = false;
for u in &gstore.users {
if let Some(existing) = rstore.users.iter_mut().find(|e| e.username == u.username) {
if existing.password_hash != u.password_hash
|| existing.role != u.role
|| existing.totp_secret_b32 != u.totp_secret_b32
{
existing.password_hash = u.password_hash.clone();
existing.role = u.role.clone();
existing.totp_secret_b32 = u.totp_secret_b32.clone();
existing.recovery_codes = u.recovery_codes.clone();
changed = true;
}
} else {
rstore.users.push(u.clone());
changed = true;
}
}
let before_sessions = rstore.sessions.len();
rstore.sessions.retain(|s| {
!s.token.starts_with("arks_gsess_") || gstore.sessions.iter().any(|gs| gs.token == s.token)
});
if rstore.sessions.len() != before_sessions {
changed = true;
}
for s in gstore.sessions {
if !rstore.sessions.iter().any(|e| e.token == s.token) {
rstore.sessions.push(s);
changed = true;
}
}
for p in gstore.pats {
if !rstore.pats.iter().any(|e| e.token_hash == p.token_hash) {
rstore.pats.push(p);
changed = true;
}
}
if changed {
let _ = rstore.commit();
}
}
fn render_root_auth_form(title: &str, action: &str) -> HttpResponse {
let totp_input = if action == "/login" {
"<input class=\"input\" type=\"text\" name=\"totp\" placeholder=\"2FA TOTP or recovery code (if enabled)\" />"
} else {
""
};
let html = format!(
"<!doctype html><html lang=\"en\" data-theme=\"dark\"><head><meta charset=\"utf-8\">\
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
<title>{title} — arks</title><link rel=\"stylesheet\" href=\"/style.css\"></head><body>\
<main class=\"mr-auth-main\">\
<div class=\"card\"><div class=\"card-header\"><strong>{title}</strong></div>\
<form class=\"card-body mr-auth-form\" method=\"post\" action=\"{action}\">\
<input class=\"input\" type=\"text\" name=\"username\" placeholder=\"Username\" required />\
<input class=\"input\" type=\"password\" name=\"password\" placeholder=\"Password\" required />\
{totp_input}\
<button class=\"btn btn-primary\" type=\"submit\">{title}</button>\
</form></div>\
</main></body></html>"
);
HttpResponse {
status: 200,
content_type: "text/html; charset=utf-8".into(),
body: html.into_bytes(),
www_authenticate: None,
extra_headers: vec![
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
("X-Content-Type-Options".into(), "nosniff".into()),
],
}
}
fn render_cross_repo_search(root: &Path, query: &str, req: &HttpRequest) -> HttpResponse {
let params = parse_form_urlencoded(query.as_bytes());
let q = params.get("q").map(|s| s.trim()).unwrap_or("");
let q_low = q.to_ascii_lowercase();
let repos = list_repos(root);
let mut rows = String::new();
let mut hits = 0usize;
if !q_low.is_empty() {
for (repo_name, git_dir, _) in &repos {
sync_global_auth_into_repo(root, git_dir);
let store = super::store::ForgeStore::load(git_dir);
if !super::auth_api::can_read_repo(&store, req) {
continue;
}
for iss in &store.issues {
if iss.title.to_ascii_lowercase().contains(&q_low)
|| iss.body.to_ascii_lowercase().contains(&q_low)
{
hits += 1;
rows.push_str(&format!(
"<tr><td><span class=\"badge\">issue</span> \
<a href=\"/{}/issues/{}\"><strong>{} #{} — {}</strong></a></td></tr>",
html_escape(repo_name),
iss.id,
html_escape(repo_name),
iss.id,
html_escape(&iss.title),
));
}
}
if let Ok(repo) = Repository::open(git_dir) {
let default_br = super::head_branch_label(&repo);
if let Some(oid) = super::resolve_rev_oid(&repo, &default_br) {
if let Ok(tree) = arks_repo::commit_tree_map(&repo, &oid) {
for (path, _) in tree {
if path.to_ascii_lowercase().contains(&q_low) {
hits += 1;
rows.push_str(&format!(
"<tr><td><span class=\"badge badge-green\">file</span> \
<a href=\"/{}/blob/{}/{}\"><strong>{}/{}</strong></a></td></tr>",
html_escape(repo_name),
html_escape(&default_br),
html_escape(&path),
html_escape(repo_name),
html_escape(&path),
));
}
}
}
}
}
}
}
if rows.is_empty() {
rows.push_str("<tr><td class=\"muted\">No cross-repository matches found.</td></tr>");
}
let html = format!(
"<!doctype html><html lang=\"en\" data-theme=\"dark\"><head><meta charset=\"utf-8\">\
<title>Global Search — arks</title><link rel=\"stylesheet\" href=\"/style.css\"></head><body>\
<main class=\"mr-main\">\
<h1>Global Cross-Repo Search <span class=\"badge badge-green\">{hits} hits</span></h1>\
<form class=\"mr-search-bar\" method=\"get\" action=\"/search\">\
<input class=\"input\" type=\"text\" name=\"q\" value=\"{}\" placeholder=\"Search files & issues across all repos...\" />\
<button class=\"btn btn-primary\" type=\"submit\">Search</button>\
</form>\
<div class=\"card\"><table class=\"tree-table\">{rows}</table></div>\
</main></body></html>",
html_escape(q),
);
HttpResponse {
status: 200,
content_type: "text/html; charset=utf-8".into(),
body: html.into_bytes(),
www_authenticate: None,
extra_headers: vec![
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
("X-Content-Type-Options".into(), "nosniff".into()),
],
}
}