Skip to main content

arks_server/
web_ui.rs

1//! Embedded single-binary SSR Web UI for `arks serve` (E8).
2//!
3//! Compile-time embedded stylesheet (`include_str!`), strict HTML entity escaping
4//! on every dynamic value, and `Content-Security-Policy: default-src 'self'; script-src 'none'`.
5//! Never interferes with Git smart/dumb HTTP (`info/refs`, `git-upload-pack`,
6//! `git-receive-pack`, `objects/`, `HEAD`) or Git LFS (`info/lfs/`).
7//!
8//! Spec: `sot:root/v0-2-0-scope-expansion` §2.8 (E8).
9
10use crate::http::{HttpRequest, HttpResponse};
11use crate::serve::PageHandler;
12use arks_object::{Commit, ObjectKind, Tree, TreeMode};
13use arks_oid::Oid;
14use arks_refs::RefTarget;
15use arks_repo::Repository;
16use std::collections::BTreeMap;
17use std::path::PathBuf;
18use std::sync::Arc;
19
20pub const WEB_UI_CSP: &str = "default-src 'self'; script-src 'none'";
21const STYLESHEET: &str = include_str!("web_ui.css");
22
23/// Strictly escape HTML special characters to prevent XSS.
24pub fn html_escape(input: &str) -> String {
25    let mut out = String::with_capacity(input.len());
26    for ch in input.chars() {
27        match ch {
28            '&' => out.push_str("&"),
29            '<' => out.push_str("&lt;"),
30            '>' => out.push_str("&gt;"),
31            '"' => out.push_str("&quot;"),
32            '\'' => out.push_str("&#x27;"),
33            other => out.push(other),
34        }
35    }
36    out
37}
38
39fn html_response(status: u16, title: &str, body_html: &str) -> HttpResponse {
40    let doc = format!(
41        "<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n\
42         <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n\
43         <title>{}</title>\n<link rel=\"stylesheet\" href=\"/style.css\">\n</head>\n<body>\n\
44         <header>\n  <a href=\"/\">arks</a>\n  <a href=\"/commits\">Commits</a>\n  <a href=\"/refs\">Refs</a>\n</header>\n\
45         <main>\n{body_html}\n</main>\n</body>\n</html>\n",
46        html_escape(title)
47    );
48    HttpResponse {
49        status,
50        content_type: "text/html; charset=utf-8".into(),
51        body: doc.into_bytes(),
52        www_authenticate: None,
53        extra_headers: vec![
54            ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
55            ("X-Content-Type-Options".into(), "nosniff".into()),
56        ],
57    }
58}
59
60fn css_response() -> HttpResponse {
61    HttpResponse {
62        status: 200,
63        content_type: "text/css; charset=utf-8".into(),
64        body: STYLESHEET.as_bytes().to_vec(),
65        www_authenticate: None,
66        extra_headers: vec![
67            ("Content-Security-Policy".into(), WEB_UI_CSP.into()),
68            ("X-Content-Type-Options".into(), "nosniff".into()),
69        ],
70    }
71}
72
73/// Build a [`PageHandler`] serving the embedded SSR Web UI for `git_dir`.
74pub fn web_ui_page_handler(git_dir: impl Into<PathBuf>) -> PageHandler {
75    let dir = git_dir.into();
76    Arc::new(move |req: &HttpRequest| handle_web_ui(&dir, req))
77}
78
79/// Route browser `GET` requests to the embedded SSR Web UI; returns `None` for
80/// Git smart/dumb HTTP and LFS paths so protocol traffic passes through untouched.
81pub fn handle_web_ui(git_dir: &std::path::Path, req: &HttpRequest) -> Option<HttpResponse> {
82    if req.method != "GET" {
83        return None;
84    }
85    let path = req.path.as_str();
86    if path == "/style.css" {
87        return Some(css_response());
88    }
89    // Never intercept Git smart/dumb HTTP or LFS routes.
90    if path.contains("/info/refs")
91        || path.contains("/info/lfs/")
92        || path.contains("/git-upload-pack")
93        || path.contains("/git-receive-pack")
94        || path.starts_with("/objects/")
95        || path == "/HEAD"
96    {
97        return None;
98    }
99
100    let Ok(repo) = Repository::open(git_dir) else {
101        return Some(html_response(
102            500,
103            "arks — Error",
104            "<h1>Repository unavailable</h1>",
105        ));
106    };
107
108    if path == "/" || path.is_empty() {
109        return Some(render_overview(&repo));
110    }
111    if path == "/refs" {
112        return Some(render_refs(&repo));
113    }
114    if path == "/commits" {
115        return Some(render_commits(&repo, "HEAD"));
116    }
117    if let Some(rev) = path.strip_prefix("/commits/") {
118        return Some(render_commits(&repo, rev));
119    }
120    if let Some(oid_hex) = path.strip_prefix("/commit/") {
121        return Some(render_commit_detail(&repo, oid_hex));
122    }
123    if let Some(rest) = path.strip_prefix("/tree/") {
124        let (rev, subpath) = match rest.split_once('/') {
125            Some((r, p)) => (r, p),
126            None => (rest, ""),
127        };
128        return Some(render_tree(&repo, rev, subpath));
129    }
130    if let Some(rest) = path.strip_prefix("/blob/") {
131        if let Some((rev, subpath)) = rest.split_once('/') {
132            return Some(render_blob(&repo, rev, subpath));
133        }
134        return Some(html_response(
135            404,
136            "Not Found",
137            "<h1>Blob path missing</h1>",
138        ));
139    }
140
141    None
142}
143
144fn resolve_rev_simple(repo: &Repository, rev: &str) -> Option<Oid> {
145    if rev == "HEAD" {
146        return repo.refs().resolve("HEAD").ok();
147    }
148    if let Ok(oid) = Oid::from_hex(rev) {
149        return Some(oid);
150    }
151    for candidate in [
152        rev.to_string(),
153        format!("refs/heads/{rev}"),
154        format!("refs/tags/{rev}"),
155    ] {
156        if let Ok(oid) = repo.refs().resolve(&candidate) {
157            return Some(oid);
158        }
159    }
160    None
161}
162
163fn load_commit(repo: &Repository, oid: &Oid) -> Option<Commit> {
164    let obj = repo.get_object(oid).ok()?;
165    if obj.kind != ObjectKind::Commit {
166        return None;
167    }
168    Commit::decode(&obj.payload).ok()
169}
170
171fn head_branch_label(repo: &Repository) -> String {
172    match repo.head_target() {
173        Ok(RefTarget::Symbolic(s)) => s.strip_prefix("refs/heads/").unwrap_or(&s).to_string(),
174        Ok(RefTarget::Direct(o)) => o.to_hex()[..7.min(o.to_hex().len())].to_string(),
175        Err(_) => "HEAD".into(),
176    }
177}
178
179fn render_overview(repo: &Repository) -> HttpResponse {
180    let branch = head_branch_label(repo);
181    let refs_count = repo.refs().list_refs("refs/").map(|v| v.len()).unwrap_or(0);
182    let mut html = format!(
183        "<h1>Repository <span class=\"badge\">{}</span></h1>\n\
184         <p class=\"meta\">{} refs &middot; <a href=\"/commits/{}\">Commit history</a> &middot; <a href=\"/refs\">All refs</a></p>\n",
185        html_escape(&branch),
186        refs_count,
187        html_escape(&branch),
188    );
189
190    if let Some(head_oid) = resolve_rev_simple(repo, "HEAD") {
191        if let Some(c) = load_commit(repo, &head_oid) {
192            let short = &head_oid.to_hex()[..7.min(head_oid.to_hex().len())];
193            let subj = c.message.lines().next().unwrap_or("");
194            html.push_str(&format!(
195                "<p>Latest commit <a href=\"/commit/{}\"><code>{}</code></a> — {} <span class=\"meta\">({})</span></p>\n",
196                html_escape(&head_oid.to_hex()),
197                html_escape(short),
198                html_escape(subj),
199                html_escape(&c.author.name),
200            ));
201            html.push_str(&render_tree_table(repo, &branch, &c.tree, ""));
202        }
203    } else {
204        html.push_str("<p class=\"meta\">Empty repository (no commits yet).</p>\n");
205    }
206
207    html_response(200, "arks — Repository", &html)
208}
209
210fn render_tree_table(repo: &Repository, rev: &str, tree_oid: &Oid, subpath: &str) -> String {
211    let Ok(obj) = repo.get_object(tree_oid) else {
212        return "<p>Unable to read tree.</p>".into();
213    };
214    let Ok(tree) = Tree::decode(&obj.payload, repo.oid_kind()) else {
215        return "<p>Corrupt tree.</p>".into();
216    };
217    let mut out = String::from(
218        "<table><thead><tr><th>Name</th><th>Type</th><th>OID</th></tr></thead><tbody>\n",
219    );
220    for entry in tree.entries {
221        let full = if subpath.is_empty() {
222            entry.name.clone()
223        } else {
224            format!("{subpath}/{}", entry.name)
225        };
226        let is_dir = entry.mode == TreeMode::Tree;
227        let href = if is_dir {
228            format!("/tree/{}/{}", html_escape(rev), html_escape(&full))
229        } else {
230            format!("/blob/{}/{}", html_escape(rev), html_escape(&full))
231        };
232        let kind = if is_dir { "tree" } else { "blob" };
233        let short = &entry.oid.to_hex()[..7.min(entry.oid.to_hex().len())];
234        out.push_str(&format!(
235            "<tr><td><a href=\"{href}\">{}{}</a></td><td class=\"meta\">{kind}</td><td><code>{}</code></td></tr>\n",
236            html_escape(&entry.name),
237            if is_dir { "/" } else { "" },
238            html_escape(short)
239        ));
240    }
241    out.push_str("</tbody></table>\n");
242    out
243}
244
245fn find_tree_entry(repo: &Repository, root_tree: &Oid, subpath: &str) -> Option<(TreeMode, Oid)> {
246    let mut cur_oid = *root_tree;
247    let mut cur_mode = TreeMode::Tree;
248    for part in subpath.split('/').filter(|p| !p.is_empty()) {
249        let obj = repo.get_object(&cur_oid).ok()?;
250        if obj.kind != ObjectKind::Tree {
251            return None;
252        }
253        let tree = Tree::decode(&obj.payload, repo.oid_kind()).ok()?;
254        let found = tree.entries.into_iter().find(|e| e.name == part)?;
255        cur_mode = found.mode;
256        cur_oid = found.oid;
257    }
258    Some((cur_mode, cur_oid))
259}
260
261fn render_tree(repo: &Repository, rev: &str, subpath: &str) -> HttpResponse {
262    let Some(commit_oid) = resolve_rev_simple(repo, rev) else {
263        return html_response(404, "Not Found", "<h1>Revision not found</h1>");
264    };
265    let Some(c) = load_commit(repo, &commit_oid) else {
266        return html_response(404, "Not Found", "<h1>Commit not found</h1>");
267    };
268    let Some((mode, oid)) = find_tree_entry(repo, &c.tree, subpath) else {
269        return html_response(404, "Not Found", "<h1>Path not found</h1>");
270    };
271    if mode != TreeMode::Tree {
272        return render_blob(repo, rev, subpath);
273    }
274    let heading = format!(
275        "<h1>Tree: <code>{}</code> @ <span class=\"badge\">{}</span></h1>\n",
276        html_escape(if subpath.is_empty() { "/" } else { subpath }),
277        html_escape(rev)
278    );
279    let table = render_tree_table(repo, rev, &oid, subpath);
280    html_response(
281        200,
282        &format!("arks — {subpath}"),
283        &format!("{heading}{table}"),
284    )
285}
286
287fn render_blob(repo: &Repository, rev: &str, subpath: &str) -> HttpResponse {
288    let Some(commit_oid) = resolve_rev_simple(repo, rev) else {
289        return html_response(404, "Not Found", "<h1>Revision not found</h1>");
290    };
291    let Some(c) = load_commit(repo, &commit_oid) else {
292        return html_response(404, "Not Found", "<h1>Commit not found</h1>");
293    };
294    let Some((mode, oid)) = find_tree_entry(repo, &c.tree, subpath) else {
295        return html_response(404, "Not Found", "<h1>File not found</h1>");
296    };
297    if mode == TreeMode::Tree {
298        return render_tree(repo, rev, subpath);
299    }
300    let Ok(obj) = repo.get_object(&oid) else {
301        return html_response(404, "Not Found", "<h1>Blob missing</h1>");
302    };
303    let mut html = format!(
304        "<h1>{} <span class=\"badge\">{}</span></h1>\n<p class=\"meta\">{} bytes &middot; <code>{}</code></p>\n",
305        html_escape(subpath),
306        html_escape(rev),
307        obj.payload.len(),
308        html_escape(&oid.to_hex())
309    );
310    if obj.payload.contains(&0) {
311        html.push_str("<p class=\"meta\">Binary file not displayed.</p>\n");
312    } else {
313        let text = String::from_utf8_lossy(&obj.payload);
314        html.push_str("<pre><code>");
315        for (idx, line) in text.lines().enumerate() {
316            html.push_str(&format!(
317                "<span class=\"ln\">{}</span>{}\n",
318                idx + 1,
319                html_escape(line)
320            ));
321        }
322        html.push_str("</code></pre>\n");
323    }
324    html_response(200, &format!("arks — {subpath}"), &html)
325}
326
327fn render_commits(repo: &Repository, rev: &str) -> HttpResponse {
328    let Some(mut cur) = resolve_rev_simple(repo, rev) else {
329        return html_response(404, "Not Found", "<h1>Revision not found</h1>");
330    };
331    let mut html = format!(
332        "<h1>Commits <span class=\"badge\">{}</span></h1>\n\
333         <table><thead><tr><th>Commit</th><th>Subject</th><th>Author</th></tr></thead><tbody>\n",
334        html_escape(rev)
335    );
336    for _ in 0..50 {
337        let Some(c) = load_commit(repo, &cur) else {
338            break;
339        };
340        let hex = cur.to_hex();
341        let short = &hex[..7.min(hex.len())];
342        let subj = c.message.lines().next().unwrap_or("");
343        html.push_str(&format!(
344            "<tr><td><a href=\"/commit/{}\"><code>{}</code></a></td><td>{}</td><td class=\"meta\">{}</td></tr>\n",
345            html_escape(&hex),
346            html_escape(short),
347            html_escape(subj),
348            html_escape(&c.author.name)
349        ));
350        let Some(&parent) = c.parents.first() else {
351            break;
352        };
353        cur = parent;
354    }
355    html.push_str("</tbody></table>\n");
356    html_response(200, &format!("arks — Commits ({rev})"), &html)
357}
358
359fn render_commit_detail(repo: &Repository, oid_hex: &str) -> HttpResponse {
360    let Some(oid) = resolve_rev_simple(repo, oid_hex) else {
361        return html_response(404, "Not Found", "<h1>Commit not found</h1>");
362    };
363    let Some(c) = load_commit(repo, &oid) else {
364        return html_response(404, "Not Found", "<h1>Commit not found</h1>");
365    };
366    let mut html = format!(
367        "<h1>Commit <code>{}</code></h1>\n\
368         <p class=\"meta\">Author: {} &lt;{}&gt; &middot; Committer: {}</p>\n\
369         <pre>{}</pre>\n",
370        html_escape(&oid.to_hex()),
371        html_escape(&c.author.name),
372        html_escape(&c.author.email),
373        html_escape(&c.committer.name),
374        html_escape(&c.message)
375    );
376
377    // Compute changed files vs first parent (or empty tree for root commit).
378    let cur_files: BTreeMap<String, Oid> = arks_repo::tree_blob_map(repo, &oid)
379        .unwrap_or_default()
380        .into_iter()
381        .collect();
382    let parent_files: BTreeMap<String, Oid> = c
383        .parents
384        .first()
385        .and_then(|p| arks_repo::tree_blob_map(repo, p).ok())
386        .unwrap_or_default()
387        .into_iter()
388        .collect();
389
390    html.push_str("<h2>Changed files</h2>\n<table><thead><tr><th>Status</th><th>Path</th></tr></thead><tbody>\n");
391    for (p, o) in &cur_files {
392        match parent_files.get(p) {
393            None => html.push_str(&format!(
394                "<tr><td>A</td><td><a href=\"/blob/{}/{}\">{}</a></td></tr>\n",
395                html_escape(&oid.to_hex()),
396                html_escape(p),
397                html_escape(p)
398            )),
399            Some(po) if po != o => html.push_str(&format!(
400                "<tr><td>M</td><td><a href=\"/blob/{}/{}\">{}</a></td></tr>\n",
401                html_escape(&oid.to_hex()),
402                html_escape(p),
403                html_escape(p)
404            )),
405            _ => {}
406        }
407    }
408    for p in parent_files.keys() {
409        if !cur_files.contains_key(p) {
410            html.push_str(&format!("<tr><td>D</td><td>{}</td></tr>\n", html_escape(p)));
411        }
412    }
413    html.push_str("</tbody></table>\n");
414    html_response(200, &format!("arks — Commit {oid_hex}"), &html)
415}
416
417fn render_refs(repo: &Repository) -> HttpResponse {
418    let refs = repo.refs().list_refs("refs/").unwrap_or_default();
419    let mut html = String::from(
420        "<h1>References</h1>\n<table><thead><tr><th>Ref</th><th>OID</th></tr></thead><tbody>\n",
421    );
422    for (name, oid) in refs {
423        let short = &oid.to_hex()[..7.min(oid.to_hex().len())];
424        let link_rev = name
425            .strip_prefix("refs/heads/")
426            .or_else(|| name.strip_prefix("refs/tags/"))
427            .unwrap_or(&name);
428        html.push_str(&format!(
429            "<tr><td><a href=\"/tree/{}\">{}</a></td><td><a href=\"/commit/{}\"><code>{}</code></a></td></tr>\n",
430            html_escape(link_rev),
431            html_escape(&name),
432            html_escape(&oid.to_hex()),
433            html_escape(short)
434        ));
435    }
436    html.push_str("</tbody></table>\n");
437    html_response(200, "arks — References", &html)
438}