use super::store::{ForgeStore, parse_form_urlencoded, parse_labels_csv};
use super::{
ActiveTab, RepoContext, WEB_UI_CSP, collect_recent_commits, format_timestamp, html_escape,
redirect_see_other, render_page, resolve_rev_oid,
};
use crate::http::{HttpRequest, HttpResponse};
use arks_repo::Repository;
use std::fs;
pub fn render_repo_settings(repo: &Repository, ctx: &RepoContext) -> HttpResponse {
let store = ForgeStore::load(repo.common_dir());
let checked = if store.archived { " checked" } else { "" };
let badge = if store.archived {
"<span class=\"badge\">Archived (read-only)</span>"
} else {
"<span class=\"badge badge-green\">Active</span>"
};
let body = format!(
"<div class=\"toolbar\"><a href=\"/settings\">← Settings</a> <strong>Repository Settings</strong> {badge}</div>\
<div class=\"card\"><div class=\"card-header\"><strong>General</strong></div>\
<form class=\"card-body\" method=\"post\" action=\"/settings/repo\" style=\"display:flex;flex-direction:column;gap:10px\">\
<label>Description</label>\
<input class=\"input\" type=\"text\" name=\"description\" value=\"{}\" />\
<label><input type=\"checkbox\" name=\"archived\" value=\"1\"{checked} /> Archive repository (read-only: blocks git push and Web UI writes)</label>\
<button class=\"btn btn-primary\" type=\"submit\">Save Repository Settings</button>\
</form></div>\
<div class=\"card\"><div class=\"card-header\"><strong>Danger Zone — Delete Repository</strong></div>\
<form class=\"card-body\" method=\"post\" action=\"/settings/repo/delete\" style=\"display:flex;gap:8px;flex-wrap:wrap\">\
<input class=\"input\" type=\"text\" name=\"confirm\" placeholder=\"Type repository name to confirm\" required />\
<button class=\"btn\" type=\"submit\">Delete Repository</button>\
</form></div>",
html_escape(&ctx.description)
);
render_page(
200,
ctx,
ActiveTab::Settings,
&format!("Repo Settings — {}", ctx.name),
&body,
)
}
pub fn handle_repo_settings(repo: &Repository, req: &HttpRequest) -> HttpResponse {
let form = parse_form_urlencoded(&req.body);
if let Some(desc) = form.get("description") {
let _ = fs::write(
repo.common_dir().join("description"),
format!("{}\n", desc.trim()),
);
}
let mut store = ForgeStore::load(repo.common_dir());
store.archived = form.get("archived").map(String::as_str) == Some("1");
let _ = store.save(repo.common_dir());
let actor = super::auth_api::resolve_actor(&store, req)
.map(|(u, _)| u)
.unwrap_or_else(|| "operator".into());
super::admin_2fa::record_audit(
repo.common_dir(),
&actor,
"repo.settings_updated",
if store.archived {
"archived=true"
} else {
"archived=false"
},
);
redirect_see_other("/settings/repo")
}
pub fn render_profile_settings(
repo: &Repository,
ctx: &RepoContext,
req: &HttpRequest,
) -> HttpResponse {
let store = ForgeStore::load(repo.common_dir());
let actor = super::auth_api::resolve_actor(&store, req).map(|(u, _)| u);
let user_label = actor.as_deref().unwrap_or("anonymous");
let sessions: Vec<_> = store
.sessions
.iter()
.filter(|s| actor.as_deref() == Some(s.username.as_str()))
.collect();
let sess_count = sessions.len();
let body = format!(
"<div class=\"toolbar\"><a href=\"/settings\">← Settings</a> <strong>Profile (@{})</strong></div>\
<div class=\"card\"><div class=\"card-header\"><strong>Change Password</strong></div>\
<form class=\"card-body\" method=\"post\" action=\"/settings/profile/password\" style=\"display:flex;flex-direction:column;gap:10px;max-width:420px\">\
<input class=\"input\" type=\"password\" name=\"current_password\" placeholder=\"Current password\" required />\
<input class=\"input\" type=\"password\" name=\"new_password\" placeholder=\"New password (min 4 chars)\" required />\
<button class=\"btn btn-primary\" type=\"submit\">Update Password</button>\
</form></div>\
<div class=\"card\"><div class=\"card-header\"><strong>Active Sessions ({sess_count})</strong></div>\
<form class=\"card-body\" method=\"post\" action=\"/settings/profile/sessions/revoke\">\
<p class=\"muted\">Revoke all other active browser sessions for this account.</p>\
<button class=\"btn\" type=\"submit\">Revoke Other Sessions</button>\
</form></div>",
html_escape(user_label)
);
render_page(
200,
ctx,
ActiveTab::Settings,
&format!("Profile — {}", ctx.name),
&body,
)
}
pub fn handle_change_password(
repo: &Repository,
ctx: &RepoContext,
req: &HttpRequest,
) -> HttpResponse {
let form = parse_form_urlencoded(&req.body);
let current = form
.get("current_password")
.map(String::as_str)
.unwrap_or("");
let next = form.get("new_password").map(String::as_str).unwrap_or("");
if next.len() < 4 {
return render_page(
400,
ctx,
ActiveTab::Settings,
"Invalid password",
"New password must be at least 4 characters.",
);
}
let mut store = ForgeStore::load(repo.common_dir());
let Some((user, _)) = super::auth_api::resolve_actor(&store, req) else {
return render_page(
401,
ctx,
ActiveTab::Settings,
"Unauthorized",
"Sign in first.",
);
};
let Some(acct) = store.users.iter_mut().find(|u| u.username == user) else {
return render_page(
404,
ctx,
ActiveTab::Settings,
"Not found",
"Account not found.",
);
};
if !super::auth_api::verify_user_password(&user, current, &acct.password_hash) {
return render_page(
403,
ctx,
ActiveTab::Settings,
"Wrong password",
"Current password does not match.",
);
}
acct.password_hash = super::auth_api::hash_user_password(&user, next);
let _ = store.save(repo.common_dir());
super::admin_2fa::record_audit(repo.common_dir(), &user, "user.password_changed", &user);
redirect_see_other("/settings/profile")
}
pub fn handle_revoke_other_sessions(repo: &Repository, req: &HttpRequest) -> HttpResponse {
let mut store = ForgeStore::load(repo.common_dir());
let current_sid = req.cookie.as_deref().and_then(|raw| {
raw.split(';')
.find_map(|p| p.trim().strip_prefix("arks_session="))
.map(String::from)
});
if let Some((user, _)) = super::auth_api::resolve_actor(&store, req) {
store
.sessions
.retain(|s| s.username != user || current_sid.as_deref() == Some(s.token.as_str()));
let _ = store.save(repo.common_dir());
super::admin_2fa::record_audit(repo.common_dir(), &user, "user.sessions_revoked", &user);
}
redirect_see_other("/settings/profile")
}
pub fn handle_toggle_pr_draft(repo: &Repository, branch: &str) -> HttpResponse {
let mut store = ForgeStore::load(repo.common_dir());
if let Some(pr) = store
.pull_requests
.iter_mut()
.find(|p| p.head_branch == branch)
{
pr.draft = !pr.draft;
let _ = store.save(repo.common_dir());
}
redirect_see_other(&format!("/pulls/{branch}"))
}
pub fn handle_assign_pr_reviewers(
repo: &Repository,
branch: &str,
req: &HttpRequest,
) -> HttpResponse {
let form = parse_form_urlencoded(&req.body);
let reviewers = parse_labels_csv(form.get("reviewers").map(String::as_str).unwrap_or(""));
let mut store = ForgeStore::load(repo.common_dir());
if let Some(pr) = store
.pull_requests
.iter_mut()
.find(|p| p.head_branch == branch)
{
pr.reviewers = reviewers;
let _ = store.save(repo.common_dir());
}
redirect_see_other(&format!("/pulls/{branch}"))
}
pub fn handle_toggle_pr_state(repo: &Repository, branch: &str) -> HttpResponse {
let mut store = ForgeStore::load(repo.common_dir());
if let Some(pr) = store
.pull_requests
.iter_mut()
.find(|p| p.head_branch == branch)
{
pr.state = if pr.state == "closed" {
"open".into()
} else {
"closed".into()
};
let _ = store.save(repo.common_dir());
}
redirect_see_other(&format!("/pulls/{branch}"))
}
pub fn handle_force_unlock_lease(repo: &Repository, req: &HttpRequest) -> HttpResponse {
let form = parse_form_urlencoded(&req.body);
let name = form.get("lease").map(|s| s.trim()).unwrap_or("");
if !name.is_empty() && !name.contains('/') && !name.contains('\\') && !name.contains("..") {
let lease_path = repo.common_dir().join("arks-leases").join(name);
if lease_path.is_file() {
let _ = fs::remove_file(&lease_path);
let store = ForgeStore::load(repo.common_dir());
let actor = super::auth_api::resolve_actor(&store, req)
.map(|(u, _)| u)
.unwrap_or_else(|| "operator".into());
super::admin_2fa::record_audit(repo.common_dir(), &actor, "lease.force_unlocked", name);
}
}
redirect_see_other("/agents")
}
pub fn render_action_log_partial(repo: &Repository, id_str: &str) -> HttpResponse {
let Ok(id) = id_str.parse::<u64>() else {
return HttpResponse {
status: 404,
content_type: "text/html; charset=utf-8".into(),
body: b"<div>Invalid run ID</div>".to_vec(),
www_authenticate: None,
extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
};
};
let store = ForgeStore::load(repo.common_dir());
let Some(run) = store.workflow_runs.iter().find(|r| r.id == id) else {
return HttpResponse {
status: 404,
content_type: "text/html; charset=utf-8".into(),
body: b"<div>Run not found</div>".to_vec(),
www_authenticate: None,
extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
};
};
let disk_log = fs::read_to_string(
repo.common_dir()
.join("arks-forge")
.join("logs")
.join(format!("run-{id}.log")),
)
.ok();
let log_text = disk_log.as_deref().unwrap_or(&run.log);
let poll_attr = if run.status == "running" {
format!(
" hx-get=\"/actions/runs/{id}/log-partial\" hx-trigger=\"every 2s\" hx-swap=\"outerHTML\""
)
} else {
String::new()
};
let html = format!(
"<div id=\"run-log-box\"{poll_attr}><span class=\"badge\">{}</span>\
<pre class=\"mono\" style=\"white-space:pre-wrap\">{}</pre></div>",
html_escape(&run.status),
html_escape(log_text),
);
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()),
("Cache-Control".into(), "no-store".into()),
],
}
}
pub fn handle_rerun_workflow(
repo: &Repository,
ctx: &RepoContext,
id_str: &str,
req: &HttpRequest,
allow_local_actions: bool,
) -> HttpResponse {
let Ok(id) = id_str.parse::<u64>() else {
return redirect_see_other("/actions");
};
let store = ForgeStore::load(repo.common_dir());
let Some(wf) = store
.workflow_runs
.iter()
.find(|r| r.id == id)
.map(|r| r.workflow.clone())
else {
return redirect_see_other("/actions");
};
let mut synth = req.clone();
synth.body = format!("workflow={wf}").into_bytes();
super::actions::handle_run_workflow(repo, ctx, &synth, allow_local_actions)
}
pub fn handle_issue_react(repo: &Repository, id_str: &str, req: &HttpRequest) -> HttpResponse {
let Ok(id) = id_str.parse::<u64>() else {
return redirect_see_other("/issues");
};
let form = parse_form_urlencoded(&req.body);
let emoji = match form.get("emoji").map(|s| s.trim()) {
Some("+1" | "thumbsup") => "+1",
Some("heart") => "heart",
Some("rocket") => "rocket",
Some("eyes") => "eyes",
_ => return redirect_see_other(&format!("/issues/{id}")),
};
let mut store = ForgeStore::load(repo.common_dir());
let actor = super::auth_api::resolve_actor(&store, req)
.map(|(u, _)| u)
.unwrap_or_else(|| "anonymous".into());
if let Some(issue) = store.issues.iter_mut().find(|i| i.id == id) {
let entry = issue.reactions.entry(emoji.to_string()).or_default();
if let Some(pos) = entry.iter().position(|u| u == &actor) {
entry.remove(pos);
} else {
entry.push(actor);
}
let _ = store.save(repo.common_dir());
}
redirect_see_other(&format!("/issues/{id}"))
}
pub fn handle_markdown_preview(req: &HttpRequest) -> HttpResponse {
let form = parse_form_urlencoded(&req.body);
let raw = form.get("body").map(String::as_str).unwrap_or("");
let html = super::code::render_safe_markdown(raw);
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())],
}
}
pub fn render_commits_atom(repo: &Repository, ctx: &RepoContext) -> HttpResponse {
let mut entries = String::new();
if let Some(oid) = resolve_rev_oid(repo, &ctx.default_branch) {
for (c_oid, c) in collect_recent_commits(repo, oid, 20) {
let subject = c.message.lines().next().unwrap_or("(no subject)");
entries.push_str(&format!(
"<entry><id>urn:arks:commit:{c_oid}</id><title>{}</title>\
<author><name>{}</name></author>\
<updated>{}</updated>\
<link href=\"/commit/{c_oid}\"/></entry>\n",
html_escape(subject),
html_escape(&c.author.name),
html_escape(&format_timestamp(c.author.timestamp)),
));
}
}
let xml = format!(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
<feed xmlns=\"http://www.w3.org/2005/Atom\">\n\
<title>{} — Commits</title>\n\
<id>urn:arks:repo:{}:commits</id>\n\
{entries}</feed>\n",
html_escape(&ctx.name),
html_escape(&ctx.name),
);
HttpResponse {
status: 200,
content_type: "application/atom+xml; charset=utf-8".into(),
body: xml.into_bytes(),
www_authenticate: None,
extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
}
}
pub fn render_releases_atom(repo: &Repository, ctx: &RepoContext) -> HttpResponse {
let store = ForgeStore::load(repo.common_dir());
let mut entries = String::new();
for r in store.releases.iter().rev().take(20) {
entries.push_str(&format!(
"<entry><id>urn:arks:release:{}</id><title>{} ({})</title>\
<author><name>{}</name></author>\
<updated>{}</updated>\
<summary>{}</summary></entry>\n",
r.id,
html_escape(&r.title),
html_escape(&r.tag),
html_escape(&r.author),
html_escape(&format_timestamp(r.created_at)),
html_escape(&r.notes),
));
}
let xml = format!(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
<feed xmlns=\"http://www.w3.org/2005/Atom\">\n\
<title>{} — Releases</title>\n\
<id>urn:arks:repo:{}:releases</id>\n\
{entries}</feed>\n",
html_escape(&ctx.name),
html_escape(&ctx.name),
);
HttpResponse {
status: 200,
content_type: "application/atom+xml; charset=utf-8".into(),
body: xml.into_bytes(),
www_authenticate: None,
extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
}
}
pub fn export_audit_log(repo: &Repository, as_jsonl: bool) -> HttpResponse {
let store = ForgeStore::load(repo.common_dir());
if as_jsonl {
let mut out = String::new();
for a in &store.audit_log {
if let Ok(line) = serde_json::to_string(a) {
out.push_str(&line);
out.push('\n');
}
}
HttpResponse {
status: 200,
content_type: "application/x-ndjson; charset=utf-8".into(),
body: out.into_bytes(),
www_authenticate: None,
extra_headers: vec![
(
"Content-Disposition".into(),
"attachment; filename=\"audit.jsonl\"".into(),
),
("X-Content-Type-Options".into(), "nosniff".into()),
],
}
} else {
let mut out = String::from("id,actor,action,target,created_at\n");
for a in &store.audit_log {
let esc = |s: &str| format!("\"{}\"", s.replace('"', "\"\""));
out.push_str(&format!(
"{},{},{},{},{}\n",
a.id,
esc(&a.actor),
esc(&a.action),
esc(&a.target),
a.created_at
));
}
HttpResponse {
status: 200,
content_type: "text/csv; charset=utf-8".into(),
body: out.into_bytes(),
www_authenticate: None,
extra_headers: vec![
(
"Content-Disposition".into(),
"attachment; filename=\"audit.csv\"".into(),
),
("X-Content-Type-Options".into(), "nosniff".into()),
],
}
}
}