anvilsign in

collin/anvil

1//! Server-rendered web UI (Maud): repo list, repo overview, tree browsing, and
2//! blob viewing. Pages are plain SSR and work without JavaScript; htmx-based
3//! progressive enhancement is a follow-up.
4
5use std::collections::{
6 BTreeMap,
7 HashMap,
8};
9use std::path::PathBuf;
10use std::sync::{
11 Arc,
12 Mutex,
13 OnceLock,
14};
15
16use anvil_core::{
17 App,
18 CiRun,
19 Repository,
20 SshKey,
21 User,
22 access,
23 ci,
24 repos,
25 ssh_keys,
26 users,
27};
28use anvil_git::browse::{
29 self,
30 ChangeKind,
31 FileChange,
32};
33use axum::{
34 Form,
35 Router,
36 extract::{
37 Path,
38 Query,
39 State,
40 },
41 http::{
42 StatusCode,
43 header,
44 },
45 response::{
46 IntoResponse,
47 Redirect,
48 Response,
49 },
50 routing::{
51 get,
52 post,
53 },
54};
55use maud::{
56 DOCTYPE,
57 Markup,
58 PreEscaped,
59 html,
60};
61use similar::{
62 ChangeTag,
63 TextDiff,
64};
65use syntect::easy::HighlightLines;
66use syntect::highlighting::{
67 Theme,
68 ThemeSet,
69};
70use syntect::html::{
71 IncludeBackground,
72 styled_line_to_highlighted_html,
73};
74use syntect::parsing::SyntaxSet;
75use time::OffsetDateTime;
76
77use crate::auth::{
78 CSRF_FIELD,
79 Csrf,
80 CurrentUser,
81 verify_csrf,
82};
83
84const STYLE: &str = r#"
85:root { --fg:#1f2328; --muted:#656d76; --bg:#fff; --border:#d0d7de; --accent:#0969da; --code-bg:#f6f8fa; }
86* { box-sizing:border-box; }
87body { margin:0; font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif; color:var(--fg); background:var(--bg); }
88a { color:var(--accent); text-decoration:none; } a:hover { text-decoration:underline; }
89header.top { border-bottom:1px solid var(--border); padding:12px 0; background:var(--code-bg); }
90.container { max-width:980px; margin:0 auto; padding:0 16px; }
91header.top .container { display:flex; align-items:center; gap:12px; }
92.brand { font-weight:700; font-size:16px; color:var(--fg); }
93main { padding:24px 0; }
94h1,h2 { font-weight:600; } h1 { font-size:20px; } h2 { font-size:15px; margin:20px 0 8px; }
95.muted { color:var(--muted); }
96.repo-list { list-style:none; padding:0; margin:0; }
97.repo-list li { padding:12px 0; border-bottom:1px solid var(--border); }
98.repo-list .name { font-size:16px; font-weight:600; }
99.box { border:1px solid var(--border); border-radius:6px; overflow:hidden; }
100.box .row { display:flex; justify-content:space-between; padding:8px 16px; border-top:1px solid var(--border); }
101.box .row:first-child { border-top:0; }
102.box .row a.entry { display:flex; gap:8px; align-items:center; white-space:nowrap; }
103.box .row a.fc-msg { flex:1; margin-left:24px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; text-align:left; color:var(--muted); font-size:13px; }
104.box .row a.fc-msg:hover { color:var(--accent); }
105.box .row .fc-time { margin-left:16px; white-space:nowrap; color:var(--muted); font-size:13px; }
106.icon { width:16px; flex:none; display:inline-flex; align-items:center; justify-content:center; color:var(--muted); }
107.icon.dir { color:#54aeff; }
108table.code { border-collapse:collapse; width:100%; font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }
109table.code td { padding:0 10px; vertical-align:top; white-space:pre; }
110table.code td.ln { text-align:right; color:var(--muted); user-select:none; width:1%; border-right:1px solid var(--border); background:var(--code-bg); }
111.clone { border:1px solid var(--border); border-radius:6px; padding:12px 16px; margin:16px 0; }
112.clone-head { display:flex; align-items:center; gap:12px; margin-bottom:8px; }
113.clone-tabs { display:flex; margin-left:auto; }
114.clone-tab { font-size:12px; padding:2px 10px; border:1px solid var(--border); border-radius:0; margin-left:-1px; position:relative; background:var(--bg); color:var(--muted); cursor:pointer; }
115.clone-tab:first-child { border-radius:2em 0 0 2em; margin-left:0; }
116.clone-tab:last-child { border-radius:0 2em 2em 0; }
117.clone-tab:first-child:last-child { border-radius:2em; }
118.clone-tab.active { background:var(--accent); color:#fff; border-color:var(--accent); z-index:1; }
119.clone-cmd { display:flex; align-items:center; gap:8px; background:var(--code-bg); border:1px solid var(--border); border-radius:6px; padding:6px 10px; }
120.clone-cmd code { flex:1; font:12px ui-monospace,monospace; user-select:all; overflow-x:auto; white-space:nowrap; }
121.copy-btn { display:inline-flex; align-items:center; background:none; border:0; color:var(--muted); cursor:pointer; padding:2px; }
122.copy-btn:hover { color:var(--fg); }
123.copied-msg { display:none; color:#1a7f37; font-size:12px; }
124.clone.copied .copied-msg { display:inline; }
125.clone.copied .copy-btn { color:#1a7f37; }
126.crumbs { margin:12px 0; font:13px ui-monospace,monospace; }
127.pill { display:inline-block; background:var(--code-bg); border:1px solid var(--border); border-radius:2em; padding:1px 8px; font-size:12px; color:var(--muted); }
128.pill.active { background:var(--accent); border-color:var(--accent); color:#fff; }
129.view-toggle { margin:8px 0; }
130a.pill:hover { text-decoration:none; border-color:var(--accent); color:var(--accent); }
131.md-body { padding:8px 24px 16px; line-height:1.6; overflow-wrap:break-word; }
132.md-body h1, .md-body h2 { border-bottom:1px solid var(--border); padding-bottom:6px; }
133.md-body pre { background:var(--code-bg); border-radius:6px; padding:12px 14px; overflow-x:auto; font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }
134.md-body code { background:var(--code-bg); border-radius:4px; padding:1px 4px; font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; font-size:0.9em; }
135.md-body pre code { background:none; padding:0; font-size:inherit; }
136.md-body blockquote { border-left:4px solid var(--border); margin:0 0 12px; padding:0 14px; color:var(--muted); }
137.md-body table { border-collapse:collapse; margin:12px 0; } .md-body th, .md-body td { border:1px solid var(--border); padding:5px 10px; }
138.md-body img { max-width:100%; }
139.linkbtn { background:none; border:0; color:var(--accent); cursor:pointer; font:inherit; padding:0; }
140.linkbtn:hover { text-decoration:underline; }
141.btn { display:inline-block; background:var(--accent); color:#fff; border:1px solid var(--accent); border-radius:6px; padding:5px 12px; font-size:13px; cursor:pointer; }
142.btn:hover { text-decoration:none; opacity:.92; }
143.repo-nav { font-size:13px; }
144.repo-nav a { color:var(--muted); }
145.repo-nav a:hover { color:var(--accent); text-decoration:none; }
146.pill-group { display:inline-flex; }
147.pill-group > .pill { border-radius:0; margin-left:-1px; position:relative; }
148.pill-group > .pill:first-child { border-radius:2em 0 0 2em; margin-left:0; }
149.pill-group > .pill:last-child { border-radius:0 2em 2em 0; }
150form.stack p { margin:10px 0; } form.stack label { font-size:13px; color:var(--muted); }
151form.stack input[type=text], form.stack textarea { width:100%; max-width:480px; padding:6px 8px; border:1px solid var(--border); border-radius:6px; font:inherit; }
152form.stack .check { display:flex; gap:8px; align-items:flex-start; max-width:480px; }
153.latest-commit { display:flex; gap:10px; align-items:baseline; background:var(--code-bg); border:1px solid var(--border); border-radius:6px 6px 0 0; border-bottom:0; padding:8px 16px; }
154.latest-commit + .box { border-radius:0 0 6px 6px; }
155.commit-list { list-style:none; padding:0; margin:0; }
156.commit-list li { padding:8px 0; border-top:1px solid var(--border); display:flex; gap:12px; align-items:baseline; }
157.commit-list li:first-child { border-top:0; }
158.sha { font:12px ui-monospace,monospace; color:var(--muted); }
159.file-diff { margin:16px 0; }
160.file-diff summary.head { background:var(--code-bg); border:1px solid var(--border); border-radius:6px; padding:6px 12px; font:12px ui-monospace,monospace; cursor:pointer; display:flex; align-items:center; gap:8px; list-style:none; }
161.file-diff summary.head::-webkit-details-marker { display:none; }
162.file-diff summary.head::before { content:"\25B8"; color:var(--muted); }
163.file-diff[open] summary.head::before { content:"\25BE"; }
164.file-diff[open] summary.head { border-bottom:0; border-radius:6px 6px 0 0; }
165.file-diff .stat { margin-left:auto; white-space:nowrap; }
166.stat .plus { color:#1a7f37; } .stat .minus { color:#cf222e; }
167table.diff { border:1px solid var(--border); border-radius:0 0 6px 6px; }
168table.diff td.sign { width:1%; text-align:center; color:var(--muted); user-select:none; }
169table.diff tr.ins { background:#e6ffec; } table.diff tr.ins td.sign { color:#1a7f37; }
170table.diff tr.del { background:#ffebe9; } table.diff tr.del td.sign { color:#cf222e; }
171table.diff tr.gap td { background:var(--code-bg); color:var(--muted); text-align:center; padding:3px 10px; user-select:none; font-size:11px; }
172.badge { font-size:11px; border-radius:3px; padding:1px 6px; }
173.badge.add { background:#dafbe1; color:#1a7f37; } .badge.del { background:#ffebe9; color:#cf222e; } .badge.mod { background:#fff8c5; color:#7d4e00; }
174.st { font-size:11px; border-radius:2em; padding:1px 9px; font-weight:600; text-transform:capitalize; }
175.st.queued { background:#eaeef2; color:#656d76; } .st.running { background:#fff8c5; color:#7d4e00; }
176.st.success { background:#dafbe1; color:#1a7f37; } .st.failure, .st.error { background:#ffebe9; color:#cf222e; }
177.log { background:#0d1117; color:#e6edf3; border-radius:6px; padding:14px 16px; overflow-x:auto; font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; white-space:pre-wrap; word-break:break-word; margin:0; }
178footer { color:var(--muted); font-size:12px; padding:24px 0; border-top:1px solid var(--border); margin-top:32px; }
179details.nav-menu { position:relative; }
180details.nav-menu > summary { list-style:none; cursor:pointer; color:var(--accent); font-size:14px; }
181details.nav-menu > summary::-webkit-details-marker { display:none; }
182details.nav-menu > summary::after { content:" ▾"; font-size:10px; color:var(--muted); }
183.nav-dropdown { position:absolute; right:0; top:calc(100% + 6px); background:var(--bg); border:1px solid var(--border); border-radius:6px; min-width:130px; box-shadow:0 4px 14px rgba(0,0,0,.1); z-index:200; padding:4px 0; }
184.nav-dropdown a, .nav-dropdown button { display:block; width:100%; padding:6px 14px; font-size:13px; color:var(--fg); text-align:left; background:none; border:0; cursor:pointer; font:inherit; text-decoration:none; }
185.nav-dropdown a:hover, .nav-dropdown button:hover { background:var(--code-bg); color:var(--fg); }
186"#;
187
188/// Clipboard icon for the clone "copy" button.
189const CLIPBOARD_SVG: &str = r#"<svg viewBox="0 0 16 16" width="15" height="15" fill="currentColor" aria-hidden="true"><path d="M10 1.5H6a.5.5 0 0 0-.5.5v1H4A1.5 1.5 0 0 0 2.5 4.5v9A1.5 1.5 0 0 0 4 15h8a1.5 1.5 0 0 0 1.5-1.5v-9A1.5 1.5 0 0 0 12 3h-1.5V2a.5.5 0 0 0-.5-.5zm-3.5 1h3v1h-3v-1zM4 4.5h8v9H4v-9z"/></svg>"#;
190
191/// Filled folder icon for directory entries in the tree view.
192const FOLDER_SVG: &str = r#"<svg viewBox="0 0 16 16" width="16" height="16" fill="currentColor" 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>"#;
193
194/// Outline file icon for blob entries in the tree view.
195const FILE_SVG: &str = r#"<svg viewBox="0 0 16 16" width="16" height="16" fill="currentColor" 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>"#;
196
197/// Delegated handlers for the clone widget: protocol toggle + copy-to-clipboard.
198/// Registered once on `document`, so it survives htmx body swaps.
199const CLONE_JS: &str = r#"
200(function(){
201 function copyText(t){
202 if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(t);
203 var ta=document.createElement('textarea'); ta.value=t; ta.style.position='fixed'; ta.style.opacity='0';
204 document.body.appendChild(ta); ta.focus(); ta.select();
205 try{document.execCommand('copy')}catch(e){}
206 document.body.removeChild(ta); return Promise.resolve();
207 }
208 document.addEventListener('click', function(e){
209 var nm=e.target.closest('details.nav-menu');
210 document.querySelectorAll('details.nav-menu').forEach(function(d){ if(d!==nm) d.removeAttribute('open'); });
211 var tab=e.target.closest('.clone-tab');
212 if(tab){
213 var box=tab.closest('.clone'), cmd=box.dataset[tab.dataset.proto];
214 if(cmd){ box.querySelector('.clone-cmd code').textContent=cmd; }
215 box.querySelectorAll('.clone-tab').forEach(function(t){ t.classList.toggle('active', t===tab); });
216 return;
217 }
218 var copy=e.target.closest('.copy-btn');
219 if(copy){
220 var box=copy.closest('.clone');
221 copyText(box.querySelector('.clone-cmd code').textContent).then(function(){
222 box.classList.add('copied');
223 setTimeout(function(){ box.classList.remove('copied'); }, 1300);
224 });
225 }
226 });
227})();
228"#;
229
230/// Mount the web UI routes.
231pub fn routes(router: Router<App>) -> Router<App> {
232 router
233 .route("/", get(home))
234 .route("/-/settings", get(account_settings))
235 .route("/-/settings/keys", post(add_ssh_key))
236 .route("/-/settings/keys/{id}/delete", post(delete_ssh_key))
237 .route("/-/new", get(new_repo_form).post(new_repo_submit))
238 .route("/{username}", get(user_profile))
239 .route(
240 "/{owner}/{repo}/settings",
241 get(repo_settings).post(repo_settings_submit),
242 )
243 .route("/{owner}/{repo}", get(repo_index))
244 .route("/{owner}/{repo}/tree/{rev}", get(tree_root))
245 .route("/{owner}/{repo}/tree/{rev}/{*path}", get(tree_path))
246 .route("/{owner}/{repo}/blob/{rev}/{*path}", get(blob))
247 .route("/{owner}/{repo}/commits/{rev}", get(commits))
248 .route("/{owner}/{repo}/commit/{id}", get(commit))
249 .route("/{owner}/{repo}/ci", get(ci_runs))
250 .route("/{owner}/{repo}/ci/{id}", get(ci_run))
251 .route("/-/static/htmx.min.js", get(htmx_js))
252}
253
254/// Serve the vendored htmx script (embedded in the binary).
255async fn htmx_js() -> Response {
256 (
257 [(
258 header::CONTENT_TYPE,
259 "application/javascript; charset=utf-8",
260 )],
261 include_str!("../assets/htmx.min.js"),
262 )
263 .into_response()
264}
265
266pub(crate) fn layout(title: &str, user: Option<&User>, body: Markup) -> Markup {
267 // Attach the session's CSRF token to every htmx request as a header, so any
268 // JS-driven action carries it without a hidden field. Omitted (no attribute)
269 // when unauthenticated. The token is hex, so it needs no JSON escaping.
270 let csrf = crate::auth::current_csrf();
271 let hx_headers = (!csrf.is_empty()).then(|| format!(r#"{{"{CSRF_FIELD}": "{csrf}"}}"#));
272 html! {
273 (DOCTYPE)
274 html lang="en" {
275 head {
276 meta charset="utf-8";
277 meta name="viewport" content="width=device-width, initial-scale=1";
278 title { (title) " · anvil" }
279 style { (PreEscaped(STYLE)) }
280 }
281 body hx-boost="true" hx-headers=[hx_headers] {
282 header.top { div.container {
283 a.brand href="/" { "anvil" }
284 span style="margin-left:auto" {
285 @match user {
286 Some(u) => {
287 details.nav-menu {
288 summary { (u.username) }
289 div.nav-dropdown {
290 a href="/-/settings" { "Settings" }
291 form method="post" action="/-/logout" {
292 button type="submit" { "Sign out" }
293 }
294 }
295 }
296 }
297 None => { a href="/-/login" { "sign in" } }
298 }
299 }
300 } }
301 main { div.container { (body) } }
302 footer { div.container { "anvil — a minimal git forge" } }
303 script src="/-/static/htmx.min.js" {}
304 script { (PreEscaped(CLONE_JS)) }
305 }
306 }
307 }
308}
309
310/// Hidden CSRF token field for embedding inside a mutating `<form>`.
311pub(crate) fn csrf_input(token: &str) -> Markup {
312 html! { input type="hidden" name=(CSRF_FIELD) value=(token); }
313}
314
315pub(crate) fn not_found(message: &str) -> Response {
316 (
317 StatusCode::NOT_FOUND,
318 layout(
319 "Not found",
320 None,
321 html! { h1 { "Not found" } p.muted { (message) } },
322 ),
323 )
324 .into_response()
325}
326
327pub(crate) fn server_error(err: impl std::fmt::Display) -> Response {
328 tracing::error!("ui error: {err}");
329 (
330 StatusCode::INTERNAL_SERVER_ERROR,
331 layout("Error", None, html! { h1 { "Something went wrong" } }),
332 )
333 .into_response()
334}
335
336/// Resolve `<owner>/<repo>` to its on-disk path and metadata row, enforcing read
337/// access for `viewer`. Private repos 404 for non-owners (no existence leak).
338pub(crate) async fn resolve_repo(
339 app: &App,
340 viewer: Option<&User>,
341 owner: &str,
342 name: &str,
343) -> Result<(PathBuf, Repository), Response> {
344 let owner_user = users::find_by_username(&app.db, owner)
345 .await
346 .map_err(server_error)?
347 .ok_or_else(|| not_found("no such user"))?;
348 let repo = repos::find(&app.db, owner_user.id, name)
349 .await
350 .map_err(server_error)?
351 .ok_or_else(|| not_found("no such repository"))?;
352 if !access::can_read(&repo, viewer) {
353 return Err(not_found("no such repository"));
354 }
355 let path = anvil_core::storage::repo_path(&app.config.repositories_dir(), owner, name);
356 if !path.exists() {
357 return Err(not_found("repository not found on disk"));
358 }
359 Ok((path, repo))
360}
361
362/// `GET /` — list repositories visible to the current user.
363async fn home(State(app): State<App>, CurrentUser(user): CurrentUser) -> Result<Markup, Response> {
364 let all = repos::list_all_with_owner(&app.db)
365 .await
366 .map_err(server_error)?;
367 let repos: Vec<_> = all
368 .into_iter()
369 .filter(|r| {
370 !r.is_private
371 || user
372 .as_ref()
373 .is_some_and(|u| u.id == r.owner_id || u.is_admin)
374 })
375 .collect();
376 Ok(layout(
377 "Repositories",
378 user.as_ref(),
379 html! {
380 div style="display:flex;align-items:center" {
381 h1 style="margin-right:auto" { "Repositories" }
382 @if user.is_some() { a.btn href="/-/new" { "New repository" } }
383 }
384 @if repos.is_empty() {
385 p.muted {
386 "No repositories yet. "
387 @if user.is_some() { a href="/-/new" { "Create one" } "." }
388 @else { "Sign in to create one." }
389 }
390 } @else {
391 ul.repo-list {
392 @for r in &repos {
393 li {
394 div.name {
395 a href=(format!("/{}", r.owner)) { (r.owner) }
396 "/"
397 a href=(format!("/{}/{}", r.owner, r.name)) { (r.name) }
398 @if r.is_private { " " span.pill { "private" } }
399 }
400 @if !r.description.is_empty() { div.muted { (r.description) } }
401 }
402 }
403 }
404 }
405 },
406 ))
407}
408
409/// `GET /{username}` — a user's profile: their repositories (public to all;
410/// private only to themselves or an admin).
411async fn user_profile(
412 State(app): State<App>,
413 CurrentUser(viewer): CurrentUser,
414 Path(username): Path<String>,
415) -> Result<Markup, Response> {
416 let owner = users::find_by_username(&app.db, &username)
417 .await
418 .map_err(server_error)?
419 .ok_or_else(|| not_found("no such user"))?;
420 let visible: Vec<_> = repos::list_by_owner(&app.db, owner.id)
421 .await
422 .map_err(server_error)?
423 .into_iter()
424 .filter(|r| access::can_read(r, viewer.as_ref()))
425 .collect();
426 let is_self = viewer.as_ref().is_some_and(|u| u.id == owner.id);
427
428 Ok(layout(
429 &owner.username,
430 viewer.as_ref(),
431 html! {
432 div style="display:flex;align-items:center" {
433 h1 style="margin-right:auto" { (owner.username) }
434 @if is_self { a.btn href="/-/new" { "New repository" } }
435 }
436 h2 { "Repositories" }
437 @if visible.is_empty() {
438 p.muted { "No repositories." }
439 } @else {
440 ul.repo-list {
441 @for r in &visible {
442 li {
443 div.name {
444 a href=(format!("/{}/{}", owner.username, r.name)) { (r.name) }
445 @if r.is_private { " " span.pill { "private" } }
446 }
447 @if !r.description.is_empty() { div.muted { (r.description) } }
448 }
449 }
450 }
451 }
452 },
453 ))
454}
455
456#[derive(serde::Deserialize)]
457struct AddKeyForm {
458 #[serde(default)]
459 title: String,
460 key: String,
461 #[serde(default)]
462 csrf: String,
463}
464
465/// `GET /settings` — account settings: profile + SSH keys.
466async fn account_settings(
467 State(app): State<App>,
468 CurrentUser(user): CurrentUser,
469 csrf: Csrf,
470) -> Response {
471 let Some(user) = user else {
472 return Redirect::to("/-/login").into_response();
473 };
474 let keys = match ssh_keys::list_by_user(&app.db, user.id).await {
475 Ok(keys) => keys,
476 Err(e) => return server_error(e),
477 };
478 account_page(&user, &keys, None, &csrf.0).into_response()
479}
480
481/// `POST /settings/keys` — register an SSH public key for the current user.
482async fn add_ssh_key(
483 State(app): State<App>,
484 CurrentUser(user): CurrentUser,
485 csrf: Csrf,
486 Form(form): Form<AddKeyForm>,
487) -> Response {
488 let Some(user) = user else {
489 return Redirect::to("/-/login").into_response();
490 };
491 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
492 return resp;
493 }
494 let result = match ssh_keys::parse_public_key(&form.key) {
495 Ok((fingerprint, content)) => {
496 ssh_keys::add(&app.db, user.id, &form.title, &fingerprint, &content)
497 .await
498 .map(|_| ())
499 }
500 Err(e) => Err(e),
501 };
502 match result {
503 Ok(()) => Redirect::to("/-/settings").into_response(),
504 Err(e) => {
505 let keys = ssh_keys::list_by_user(&app.db, user.id)
506 .await
507 .unwrap_or_default();
508 (
509 StatusCode::BAD_REQUEST,
510 account_page(&user, &keys, Some(&e.to_string()), &csrf.0),
511 )
512 .into_response()
513 }
514 }
515}
516
517/// `POST /settings/keys/{id}/delete` — remove one of the current user's keys.
518async fn delete_ssh_key(
519 State(app): State<App>,
520 CurrentUser(user): CurrentUser,
521 csrf: Csrf,
522 Path(id): Path<i64>,
523 Form(form): Form<crate::auth::CsrfForm>,
524) -> Response {
525 let Some(user) = user else {
526 return Redirect::to("/-/login").into_response();
527 };
528 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
529 return resp;
530 }
531 if let Err(e) = ssh_keys::delete(&app.db, id, user.id).await {
532 return server_error(e);
533 }
534 Redirect::to("/-/settings").into_response()
535}
536
537fn account_page(user: &User, keys: &[SshKey], error: Option<&str>, csrf: &str) -> Markup {
538 layout(
539 "Account settings",
540 Some(user),
541 html! {
542 h1 { "Account settings" }
543 p.muted {
544 "Signed in as " strong { (user.username) }
545 @if !user.email.is_empty() { " · " (user.email) }
546 }
547
548 h2 { "SSH keys" }
549 p.muted { "Add a public key to clone and push over SSH." }
550 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
551 @if keys.is_empty() {
552 p.muted { "No SSH keys yet." }
553 } @else {
554 div.box {
555 @for k in keys {
556 div.row {
557 div {
558 @if !k.title.is_empty() { strong { (k.title) } " " }
559 span.sha { (k.fingerprint) }
560 div.muted style="font-size:12px" { "added " (fmt_time(k.created_at)) }
561 }
562 form method="post" action=(format!("/-/settings/keys/{}/delete", k.id)) {
563 (csrf_input(csrf))
564 button.linkbtn type="submit" { "delete" }
565 }
566 }
567 }
568 }
569 }
570
571 form.stack method="post" action="/-/settings/keys" style="margin-top:16px" {
572 (csrf_input(csrf))
573 p { label { "Title" br; input type="text" name="title" placeholder="laptop"; } }
574 p { label { "Public key" br; textarea name="key" rows="4" placeholder="ssh-ed25519 AAAA…" {} } }
575 p { button.btn type="submit" { "Add SSH key" } }
576 }
577 },
578 )
579}
580
581fn forbidden() -> Response {
582 (
583 StatusCode::FORBIDDEN,
584 layout(
585 "Forbidden",
586 None,
587 html! { h1 { "Forbidden" } p.muted { "You don't have access to this." } },
588 ),
589 )
590 .into_response()
591}
592
593#[derive(serde::Deserialize)]
594struct NewRepoForm {
595 name: String,
596 #[serde(default)]
597 description: String,
598 private: Option<String>,
599 #[serde(default)]
600 csrf: String,
601}
602
603#[derive(serde::Deserialize)]
604struct SettingsForm {
605 #[serde(default)]
606 description: String,
607 private: Option<String>,
608 #[serde(default)]
609 csrf: String,
610}
611
612/// `GET /new` — new-repository form (requires login).
613async fn new_repo_form(CurrentUser(user): CurrentUser, csrf: Csrf) -> Response {
614 let Some(user) = user else {
615 return Redirect::to("/-/login").into_response();
616 };
617 new_repo_page(&user, None, "", "", false, &csrf.0).into_response()
618}
619
620/// `POST /new` — create a repository owned by the current user.
621async fn new_repo_submit(
622 State(app): State<App>,
623 CurrentUser(user): CurrentUser,
624 csrf: Csrf,
625 Form(form): Form<NewRepoForm>,
626) -> Response {
627 let Some(user) = user else {
628 return Redirect::to("/-/login").into_response();
629 };
630 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
631 return resp;
632 }
633 let private = form.private.is_some();
634 match repos::create(
635 &app.db,
636 &app.config.repositories_dir(),
637 &user,
638 &form.name,
639 &form.description,
640 private,
641 )
642 .await
643 {
644 Ok(repo) => Redirect::to(&format!("/{}/{}", user.username, repo.name)).into_response(),
645 Err(e) => (
646 StatusCode::BAD_REQUEST,
647 new_repo_page(
648 &user,
649 Some(&e.to_string()),
650 &form.name,
651 &form.description,
652 private,
653 &csrf.0,
654 ),
655 )
656 .into_response(),
657 }
658}
659
660fn new_repo_page(
661 user: &User,
662 error: Option<&str>,
663 name: &str,
664 description: &str,
665 private: bool,
666 csrf: &str,
667) -> Markup {
668 layout(
669 "New repository",
670 Some(user),
671 html! {
672 h1 { "New repository" }
673 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
674 form.stack method="post" action="/-/new" {
675 (csrf_input(csrf))
676 p { label { "Name" br; input type="text" name="name" value=(name) placeholder="my-project" autofocus; } }
677 p { label { "Description" br; input type="text" name="description" value=(description); } }
678 p { label.check { input type="checkbox" name="private" value="on" checked[private]; span { "Private — only you can see and push to it" } } }
679 p { button.btn type="submit" { "Create repository" } }
680 }
681 p.muted { "It will be created at " code { (user.username) "/" (if name.is_empty() { "<name>" } else { name }) } "." }
682 },
683 )
684}
685
686/// Load a repo for an owner-only settings action, enforcing write access.
687async fn resolve_for_settings(
688 app: &App,
689 viewer: Option<&User>,
690 owner: &str,
691 name: &str,
692) -> Result<Repository, Response> {
693 let owner_user = users::find_by_username(&app.db, owner)
694 .await
695 .map_err(server_error)?
696 .ok_or_else(|| not_found("no such repository"))?;
697 let repo = repos::find(&app.db, owner_user.id, name)
698 .await
699 .map_err(server_error)?
700 .ok_or_else(|| not_found("no such repository"))?;
701 if !access::can_read(&repo, viewer) {
702 return Err(not_found("no such repository"));
703 }
704 if !access::can_write(&repo, viewer) {
705 return Err(forbidden());
706 }
707 Ok(repo)
708}
709
710/// `GET /{owner}/{repo}/settings` — owner-only repository settings.
711async fn repo_settings(
712 State(app): State<App>,
713 CurrentUser(user): CurrentUser,
714 csrf: Csrf,
715 Path((owner, repo)): Path<(String, String)>,
716) -> Response {
717 let meta = match resolve_for_settings(&app, user.as_ref(), &owner, &repo).await {
718 Ok(m) => m,
719 Err(resp) => return resp,
720 };
721 settings_page(user.as_ref(), &owner, &repo, &meta, None, &csrf.0).into_response()
722}
723
724/// `POST /{owner}/{repo}/settings` — update description / visibility.
725async fn repo_settings_submit(
726 State(app): State<App>,
727 CurrentUser(user): CurrentUser,
728 csrf: Csrf,
729 Path((owner, repo)): Path<(String, String)>,
730 Form(form): Form<SettingsForm>,
731) -> Response {
732 let meta = match resolve_for_settings(&app, user.as_ref(), &owner, &repo).await {
733 Ok(m) => m,
734 Err(resp) => return resp,
735 };
736 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
737 return resp;
738 }
739 if let Err(e) =
740 repos::update_settings(&app.db, meta.id, &form.description, form.private.is_some()).await
741 {
742 return server_error(e);
743 }
744 Redirect::to(&format!("/{owner}/{repo}")).into_response()
745}
746
747fn settings_page(
748 user: Option<&User>,
749 owner: &str,
750 repo: &str,
751 meta: &Repository,
752 error: Option<&str>,
753 csrf: &str,
754) -> Markup {
755 layout(
756 &format!("{owner}/{repo}: settings"),
757 user,
758 html! {
759 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · settings" }
760 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
761 form.stack method="post" action=(format!("/{owner}/{repo}/settings")) {
762 (csrf_input(csrf))
763 p { label { "Description" br; input type="text" name="description" value=(meta.description); } }
764 p { label.check { input type="checkbox" name="private" value="on" checked[meta.is_private]; span { "Private — only you can see and push to it" } } }
765 p { button.btn type="submit" { "Save changes" } }
766 }
767 },
768 )
769}
770
771fn clone_box(app: &App, owner: &str, name: &str) -> Markup {
772 let http = app.config.http_clone_url(owner, name);
773 let ssh = app
774 .config
775 .ssh
776 .enabled
777 .then(|| app.config.ssh_clone_url(owner, name));
778 html! {
779 div.clone data-http=(format!("git clone {http}")) data-ssh=[ssh.as_ref().map(|s| format!("git clone {s}"))] {
780 div.clone-head {
781 span.muted { "Clone" }
782 div.clone-tabs {
783 button.clone-tab.active type="button" data-proto="http" { "HTTP" }
784 @if ssh.is_some() {
785 button.clone-tab type="button" data-proto="ssh" { "SSH" }
786 }
787 }
788 }
789 div.clone-cmd {
790 code { "git clone " (http) }
791 button.copy-btn type="button" title="Copy to clipboard" aria-label="Copy" {
792 (PreEscaped(CLIPBOARD_SVG))
793 }
794 span.copied-msg { "Copied!" }
795 }
796 }
797 }
798}
799
800/// `GET /{owner}/{repo}` — repository overview with the root tree.
801async fn repo_index(
802 State(app): State<App>,
803 CurrentUser(user): CurrentUser,
804 Path((owner, repo)): Path<(String, String)>,
805) -> Result<Markup, Response> {
806 let (path, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
807 let overview = browse::overview(&path).map_err(server_error)?;
808
809 let can_write = access::can_write(&meta, user.as_ref());
810 let header = html! {
811 div style="display:flex;align-items:center;gap:8px" {
812 h1 style="margin-right:auto" {
813 a href=(format!("/{owner}")) { (owner) } " / " (repo)
814 @if meta.is_private { " " span.pill { "private" } }
815 }
816 span.repo-nav {
817 a href=(format!("/{owner}/{repo}/ci")) { "CI" }
818 " · "
819 a href=(format!("/{owner}/{repo}/pages")) { "Pages" }
820 @if can_write {
821 " · "
822 a href=(format!("/{owner}/{repo}/settings")) { "Settings" }
823 }
824 }
825 }
826 @if !meta.description.is_empty() { p.muted { (meta.description) } }
827 p {
828 span.pill { (overview.branches.len()) " branches" }
829 " "
830 span.pill { (overview.tags.len()) " tags" }
831 }
832 (clone_box(&app, &owner, &repo))
833 };
834
835 if overview.is_empty {
836 return Ok(layout(
837 &format!("{owner}/{repo}"),
838 user.as_ref(),
839 html! {
840 (header)
841 p.muted { "This repository is empty. Push to it to get started." }
842 },
843 ));
844 }
845
846 let rev = overview
847 .default_branch
848 .clone()
849 .unwrap_or_else(|| "HEAD".to_string());
850 let entries = browse::list_tree(&path, &rev, "").map_err(server_error)?;
851 let latest = browse::commit_log(&path, &rev, 1)
852 .map_err(server_error)?
853 .into_iter()
854 .next();
855 // Best-effort: a failed walk only costs the per-entry annotations.
856 let entry_commits =
857 browse::latest_entry_commits(&path, &rev, "", ENTRY_LOG_WALK).unwrap_or_default();
858
859 Ok(layout(
860 &format!("{owner}/{repo}"),
861 user.as_ref(),
862 html! {
863 (header)
864 p.muted {
865 "Branch: " (rev) " · "
866 a href=(format!("/{owner}/{repo}/commits/{rev}")) { "commits" }
867 }
868 @if let Some(c) = &latest {
869 div.latest-commit {
870 a.sha href=(format!("/{owner}/{repo}/commit/{}", c.id)) { (c.short) }
871 a href=(format!("/{owner}/{repo}/commit/{}", c.id)) { (c.summary) }
872 span.muted style="margin-left:auto" { (c.author) " · " (fmt_time(c.time)) }
873 }
874 }
875 (tree_table(&owner, &repo, &rev, "", &entries, &entry_commits))
876 },
877 ))
878}
879
880async fn tree_root(
881 State(app): State<App>,
882 user: CurrentUser,
883 Path((owner, repo, rev)): Path<(String, String, String)>,
884) -> Result<Markup, Response> {
885 render_tree(&app, user, &owner, &repo, &rev, "").await
886}
887
888async fn tree_path(
889 State(app): State<App>,
890 user: CurrentUser,
891 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
892) -> Result<Markup, Response> {
893 render_tree(&app, user, &owner, &repo, &rev, &path).await
894}
895
896async fn render_tree(
897 app: &App,
898 CurrentUser(user): CurrentUser,
899 owner: &str,
900 repo: &str,
901 rev: &str,
902 path: &str,
903) -> Result<Markup, Response> {
904 let (repo_path, _) = resolve_repo(app, user.as_ref(), owner, repo).await?;
905 let entries = browse::list_tree(&repo_path, rev, path).map_err(server_error)?;
906 // Best-effort: a failed walk only costs the per-entry annotations.
907 let entry_commits =
908 browse::latest_entry_commits(&repo_path, rev, path, ENTRY_LOG_WALK).unwrap_or_default();
909 Ok(layout(
910 &format!("{owner}/{repo}: {path}"),
911 user.as_ref(),
912 html! {
913 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } }
914 (breadcrumbs(owner, repo, rev, path, false))
915 (tree_table(owner, repo, rev, path, &entries, &entry_commits))
916 },
917 ))
918}
919
920/// `GET /{owner}/{repo}/blob/{rev}/{*path}` — view a file. Markdown renders
921/// by default; `?plain=1` shows the raw source (toggle links on the page).
922async fn blob(
923 State(app): State<App>,
924 CurrentUser(user): CurrentUser,
925 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
926 Query(query): Query<HashMap<String, String>>,
927) -> Result<Markup, Response> {
928 let (repo_path, _) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
929 let (oid, bytes) = browse::read_blob_with_id(&repo_path, &rev, &path)
930 .map_err(server_error)?
931 .ok_or_else(|| not_found("file not found"))?;
932
933 let markdown = is_markdown(&path) && !is_binary(&bytes);
934 let rendered = markdown && !query.contains_key("plain");
935
936 let body = if is_binary(&bytes) {
937 html! { p.muted { "Binary file (" (bytes.len()) " bytes)" } }
938 } else if rendered {
939 let text = String::from_utf8_lossy(&bytes);
940 html! { div.md-body { (render_markdown(&text)) } }
941 } else {
942 let text = String::from_utf8_lossy(&bytes);
943 let budget = app.config.http.highlight_cache_mb.saturating_mul(1 << 20);
944 let lines = cached_highlight(budget, &oid, &path, &text);
945 html! {
946 table.code {
947 @for (i, line) in lines.iter().enumerate() {
948 tr {
949 td.ln { (i + 1) }
950 td { (PreEscaped(line)) }
951 }
952 }
953 }
954 }
955 };
956
957 let blob_url = format!("/{owner}/{repo}/blob/{rev}/{path}");
958 Ok(layout(
959 &format!("{owner}/{repo}: {path}"),
960 user.as_ref(),
961 html! {
962 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } }
963 (breadcrumbs(&owner, &repo, &rev, &path, true))
964 @if markdown {
965 p.view-toggle {
966 span.pill-group {
967 @if rendered {
968 span.pill.active { "Rendered" }
969 a.pill href=(format!("{blob_url}?plain=1")) { "Source" }
970 } @else {
971 a.pill href=(blob_url) { "Rendered" }
972 span.pill.active { "Source" }
973 }
974 }
975 }
976 }
977 div.box style="overflow-x:auto" { (body) }
978 },
979 ))
980}
981
982/// Whether a path should be treated as markdown (by extension).
983fn is_markdown(path: &str) -> bool {
984 std::path::Path::new(path)
985 .extension()
986 .and_then(|e| e.to_str())
987 .is_some_and(|e| e.eq_ignore_ascii_case("md") || e.eq_ignore_ascii_case("markdown"))
988}
989
990/// Render markdown to HTML (tables, strikethrough, task lists, footnotes).
991///
992/// Repo content is untrusted, so this is a stored-XSS surface: raw HTML in the
993/// source is emitted as escaped literal text, and `javascript:`/`data:`-style
994/// link and image destinations are dropped.
995fn render_markdown(text: &str) -> Markup {
996 use pulldown_cmark::{
997 Event,
998 Options,
999 Parser,
1000 Tag,
1001 html,
1002 };
1003
1004 fn safe_url(dest: &str) -> bool {
1005 let d = dest.trim().to_ascii_lowercase();
1006 !(d.starts_with("javascript:") || d.starts_with("data:") || d.starts_with("vbscript:"))
1007 }
1008
1009 let opts = Options::ENABLE_TABLES
1010 | Options::ENABLE_STRIKETHROUGH
1011 | Options::ENABLE_TASKLISTS
1012 | Options::ENABLE_FOOTNOTES;
1013 let events = Parser::new_ext(text, opts).map(|ev| match ev {
1014 Event::Html(h) => Event::Text(h),
1015 Event::InlineHtml(h) => Event::Text(h),
1016 Event::Start(Tag::Link {
1017 link_type,
1018 dest_url,
1019 title,
1020 id,
1021 }) if !safe_url(&dest_url) => Event::Start(Tag::Link {
1022 link_type,
1023 dest_url: "".into(),
1024 title,
1025 id,
1026 }),
1027 Event::Start(Tag::Image {
1028 link_type,
1029 dest_url,
1030 title,
1031 id,
1032 }) if !safe_url(&dest_url) => Event::Start(Tag::Image {
1033 link_type,
1034 dest_url: "".into(),
1035 title,
1036 id,
1037 }),
1038 e => e,
1039 });
1040 let mut out = String::new();
1041 html::push_html(&mut out, events);
1042 PreEscaped(out)
1043}
1044
1045/// How far back the per-entry "latest commit" walk looks. Entries last touched
1046/// beyond this many commits just lose the annotation.
1047const ENTRY_LOG_WALK: usize = 400;
1048
1049/// Render a tree listing as a box of rows; directories link to `tree`, files to
1050/// `blob`. Each entry also shows the subject of (and links to) the latest
1051/// commit that touched it, when `latest` has one for it.
1052fn tree_table(
1053 owner: &str,
1054 repo: &str,
1055 rev: &str,
1056 path: &str,
1057 entries: &[browse::TreeEntry],
1058 latest: &BTreeMap<String, browse::CommitInfo>,
1059) -> Markup {
1060 let join = |name: &str| {
1061 if path.is_empty() {
1062 name.to_string()
1063 } else {
1064 format!("{path}/{name}")
1065 }
1066 };
1067 html! {
1068 div.box {
1069 @if !path.is_empty() {
1070 div.row {
1071 a.entry href=(parent_link(owner, repo, rev, path)) { span.icon { ".." } "up" }
1072 }
1073 }
1074 @for e in entries {
1075 @let child = join(&e.name);
1076 @let kind = if e.is_dir { "tree" } else { "blob" };
1077 div.row {
1078 a.entry href=(format!("/{owner}/{repo}/{kind}/{rev}/{child}")) {
1079 @if e.is_dir {
1080 span.icon.dir { (PreEscaped(FOLDER_SVG)) }
1081 } @else {
1082 span.icon { (PreEscaped(FILE_SVG)) }
1083 }
1084 (e.name) @if e.is_dir { "/" }
1085 }
1086 @if let Some(c) = latest.get(&e.name) {
1087 a.fc-msg href=(format!("/{owner}/{repo}/commit/{}", c.id)) title=(c.summary) { (c.summary) }
1088 span.fc-time { (fmt_date(c.time)) }
1089 }
1090 }
1091 }
1092 }
1093 }
1094}
1095
1096fn parent_link(owner: &str, repo: &str, rev: &str, path: &str) -> String {
1097 match path.rsplit_once('/') {
1098 Some((parent, _)) => format!("/{owner}/{repo}/tree/{rev}/{parent}"),
1099 None => format!("/{owner}/{repo}/tree/{rev}"),
1100 }
1101}
1102
1103/// Path breadcrumbs. `is_blob` marks the final component as a file.
1104fn breadcrumbs(owner: &str, repo: &str, rev: &str, path: &str, is_blob: bool) -> Markup {
1105 // Precompute (label, cumulative_path) for each path component.
1106 let mut crumbs: Vec<(String, String)> = Vec::new();
1107 let mut acc = String::new();
1108 for part in path.split('/').filter(|p| !p.is_empty()) {
1109 if !acc.is_empty() {
1110 acc.push('/');
1111 }
1112 acc.push_str(part);
1113 crumbs.push((part.to_string(), acc.clone()));
1114 }
1115 let last = crumbs.len();
1116 html! {
1117 div.crumbs {
1118 a href=(format!("/{owner}/{repo}/tree/{rev}")) { (rev) }
1119 @for (i, (label, cum)) in crumbs.iter().enumerate() {
1120 " / "
1121 @if i + 1 == last && is_blob {
1122 span { (label) }
1123 } @else {
1124 a href=(format!("/{owner}/{repo}/tree/{rev}/{cum}")) { (label) }
1125 }
1126 }
1127 }
1128 }
1129}
1130
1131/// `GET /{owner}/{repo}/commits/{rev}` — commit history.
1132async fn commits(
1133 State(app): State<App>,
1134 CurrentUser(user): CurrentUser,
1135 Path((owner, repo, rev)): Path<(String, String, String)>,
1136) -> Result<Markup, Response> {
1137 let (path, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
1138 let log = browse::commit_log(&path, &rev, 100).map_err(server_error)?;
1139
1140 // Map each commit oid to its latest run status, for inline badges. One query
1141 // for the repo's recent runs; first match wins (list is newest-first).
1142 let runs = ci::list_by_repo(&app.db, meta.id, 200)
1143 .await
1144 .unwrap_or_default();
1145 let mut status_of: HashMap<&str, &str> = HashMap::new();
1146 for r in &runs {
1147 status_of
1148 .entry(r.commit.as_str())
1149 .or_insert(r.status.as_str());
1150 }
1151
1152 Ok(layout(
1153 &format!("{owner}/{repo}: commits"),
1154 user.as_ref(),
1155 html! {
1156 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · commits" }
1157 ul.commit-list {
1158 @for c in &log {
1159 li {
1160 a.sha href=(format!("/{owner}/{repo}/commit/{}", c.id)) { (c.short) }
1161 @if let Some(st) = status_of.get(c.id.as_str()) {
1162 a href=(format!("/{owner}/{repo}/ci")) { (status_badge(st)) }
1163 }
1164 span { (c.summary) }
1165 span.muted style="margin-left:auto" { (c.author) " · " (fmt_time(c.time)) }
1166 }
1167 }
1168 }
1169 },
1170 ))
1171}
1172
1173/// `GET /{owner}/{repo}/commit/{id}` — a commit with its diff.
1174async fn commit(
1175 State(app): State<App>,
1176 CurrentUser(user): CurrentUser,
1177 Path((owner, repo, id)): Path<(String, String, String)>,
1178) -> Result<Markup, Response> {
1179 let (path, _) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
1180 let detail = browse::commit_detail(&path, &id).map_err(server_error)?;
1181 Ok(layout(
1182 &format!("{owner}/{repo}: {}", detail.info.short),
1183 user.as_ref(),
1184 html! {
1185 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · " span.sha { (detail.info.short) } }
1186 p { (detail.info.summary) }
1187 p.muted {
1188 (detail.info.author) " · " (fmt_time(detail.info.time)) " · "
1189 span.sha { (detail.info.id) }
1190 @if let Some(parent) = &detail.parent {
1191 " · parent " a.sha href=(format!("/{owner}/{repo}/commit/{parent}")) { (&parent[..parent.len().min(8)]) }
1192 }
1193 }
1194 @if detail.changes.is_empty() {
1195 p.muted { "No file changes." }
1196 }
1197 @for change in &detail.changes {
1198 (render_file_diff(change))
1199 }
1200 },
1201 ))
1202}
1203
1204/// `GET /{owner}/{repo}/ci` — recent CI runs for the repository.
1205async fn ci_runs(
1206 State(app): State<App>,
1207 CurrentUser(user): CurrentUser,
1208 Path((owner, repo)): Path<(String, String)>,
1209) -> Result<Markup, Response> {
1210 let (_, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
1211 let runs = ci::list_by_repo(&app.db, meta.id, 100)
1212 .await
1213 .map_err(server_error)?;
1214 Ok(layout(
1215 &format!("{owner}/{repo}: CI"),
1216 user.as_ref(),
1217 html! {
1218 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · CI" }
1219 @if runs.is_empty() {
1220 p.muted {
1221 "No CI runs yet. Add a " code { ".anvil/ci.yml" }
1222 " pipeline and push to trigger one."
1223 }
1224 } @else {
1225 div.box {
1226 @for r in &runs {
1227 div.row {
1228 a.entry href=(format!("/{owner}/{repo}/ci/{}", r.id)) {
1229 (status_badge(&r.status))
1230 span.sha { (short_commit(&r.commit)) }
1231 span { (r.ref_name) }
1232 }
1233 span.muted { (fmt_time(r.created_at)) }
1234 }
1235 }
1236 }
1237 }
1238 },
1239 ))
1240}
1241
1242/// `GET /{owner}/{repo}/ci/{id}` — one run's status, timing, and log output.
1243async fn ci_run(
1244 State(app): State<App>,
1245 CurrentUser(user): CurrentUser,
1246 Path((owner, repo, id)): Path<(String, String, i64)>,
1247) -> Result<Markup, Response> {
1248 let (_, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
1249 let run = ci::get(&app.db, id)
1250 .await
1251 .map_err(server_error)?
1252 .filter(|r| r.repo_id == meta.id)
1253 .ok_or_else(|| not_found("no such CI run"))?;
1254 Ok(layout(
1255 &format!("{owner}/{repo}: CI #{}", run.id),
1256 user.as_ref(),
1257 html! {
1258 h1 {
1259 a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) }
1260 " · " a href=(format!("/{owner}/{repo}/ci")) { "CI" }
1261 " · #" (run.id)
1262 }
1263 p {
1264 (status_badge(&run.status))
1265 " "
1266 a.sha href=(format!("/{owner}/{repo}/commit/{}", run.commit)) { (short_commit(&run.commit)) }
1267 " " span.muted { (run.ref_name) }
1268 }
1269 p.muted {
1270 "queued " (fmt_time(run.created_at))
1271 @if run.started_at > 0 { " · started " (fmt_time(run.started_at)) }
1272 @if run.finished_at > 0 { " · finished " (fmt_time(run.finished_at)) }
1273 @if let Some(d) = run_duration(&run) { " · took " (d) }
1274 }
1275 @if run.log.is_empty() {
1276 p.muted { "No output yet." }
1277 } @else {
1278 pre.log { (run.log) }
1279 }
1280 },
1281 ))
1282}
1283
1284/// A coloured status pill for a CI run status string.
1285fn status_badge(status: &str) -> Markup {
1286 html! { span class=(format!("st {status}")) { (status) } }
1287}
1288
1289/// First 8 hex chars of a commit oid (for compact display).
1290fn short_commit(commit: &str) -> &str {
1291 &commit[..commit.len().min(8)]
1292}
1293
1294/// Wall-clock run duration (`started`→`finished`) as a short string, if known.
1295fn run_duration(run: &CiRun) -> Option<String> {
1296 if run.started_at > 0 && run.finished_at >= run.started_at {
1297 Some(format!("{}s", run.finished_at - run.started_at))
1298 } else {
1299 None
1300 }
1301}
1302
1303/// Render one file's diff (added/deleted/modified) as a unified line diff.
1304/// A file diff bigger than this many rows starts collapsed (its header still
1305/// shows the +/− counts; clicking expands it — native `details`, no JS).
1306const DIFF_COLLAPSE_ROWS: usize = 400;
1307
1308fn render_file_diff(change: &FileChange) -> Markup {
1309 let (badge_cls, badge) = match change.kind {
1310 ChangeKind::Added => ("add", "added"),
1311 ChangeKind::Deleted => ("del", "deleted"),
1312 ChangeKind::Modified => ("mod", "modified"),
1313 };
1314 let head = |stat: Markup| {
1315 html! {
1316 summary.head {
1317 span class=(format!("badge {badge_cls}")) { (badge) }
1318 span { (change.path) }
1319 span.stat { (stat) }
1320 }
1321 }
1322 };
1323
1324 let binary = change.old.as_deref().is_some_and(is_binary)
1325 || change.new.as_deref().is_some_and(is_binary);
1326 if binary {
1327 return html! {
1328 details.file-diff open {
1329 (head(html! { span.muted { "binary" } }))
1330 div.box { div.row { span.muted { "Binary file" } } }
1331 }
1332 };
1333 }
1334
1335 let old = change
1336 .old
1337 .as_deref()
1338 .map(|b| String::from_utf8_lossy(b).into_owned())
1339 .unwrap_or_default();
1340 let new = change
1341 .new
1342 .as_deref()
1343 .map(|b| String::from_utf8_lossy(b).into_owned())
1344 .unwrap_or_default();
1345 let diff = TextDiff::from_lines(&old, &new);
1346 let (mut adds, mut dels) = (0usize, 0usize);
1347 for c in diff.iter_all_changes() {
1348 match c.tag() {
1349 ChangeTag::Insert => adds += 1,
1350 ChangeTag::Delete => dels += 1,
1351 ChangeTag::Equal => {}
1352 }
1353 }
1354 // Hunks: changed lines plus 3 lines of context, not the whole file.
1355 let groups = diff.grouped_ops(3);
1356 let rendered_rows: usize = groups
1357 .iter()
1358 .flatten()
1359 .map(|op| diff.iter_changes(op).count())
1360 .sum();
1361
1362 html! {
1363 details.file-diff open[rendered_rows <= DIFF_COLLAPSE_ROWS] {
1364 (head(html! { span.plus { "+" (adds) } " " span.minus { "−" (dels) } }))
1365 (diff_table(&diff, &groups, old.lines().count()))
1366 }
1367 }
1368}
1369
1370/// Render grouped diff hunks as a table: old/new line numbers, a +/- sign
1371/// column, and the line. Elided stretches show a "⋯ N unchanged lines" row
1372/// (including before the first hunk and after the last).
1373fn diff_table<'a>(
1374 diff: &TextDiff<'a, 'a, '_, str>,
1375 groups: &[Vec<similar::DiffOp>],
1376 old_total: usize,
1377) -> Markup {
1378 let gap_row = |n: usize| {
1379 html! {
1380 @if n > 0 {
1381 tr.gap { td colspan="4" { "⋯ " (n) " unchanged line" @if n != 1 { "s" } } }
1382 }
1383 }
1384 };
1385 // Unchanged-line gap before each group, and after the last one.
1386 let mut prev_end = 0usize; // end of the previous group, in old-file lines
1387 let mut with_gaps = Vec::with_capacity(groups.len());
1388 for group in groups {
1389 let start = group.first().map_or(prev_end, |op| op.old_range().start);
1390 with_gaps.push((start.saturating_sub(prev_end), group));
1391 prev_end = group.last().map_or(prev_end, |op| op.old_range().end);
1392 }
1393 let trailing = old_total.saturating_sub(prev_end);
1394
1395 html! {
1396 table.code.diff {
1397 @for (gap, group) in &with_gaps {
1398 (gap_row(*gap))
1399 @for op in group.iter() {
1400 @for change in diff.iter_changes(op) {
1401 @let (sign, cls) = match change.tag() {
1402 ChangeTag::Delete => ("-", "del"),
1403 ChangeTag::Insert => ("+", "ins"),
1404 ChangeTag::Equal => (" ", ""),
1405 };
1406 tr class=(cls) {
1407 td.ln { @if let Some(i) = change.old_index() { (i + 1) } }
1408 td.ln { @if let Some(i) = change.new_index() { (i + 1) } }
1409 td.sign { (sign) }
1410 td { (change.value().trim_end_matches('\n')) }
1411 }
1412 }
1413 }
1414 }
1415 (gap_row(trailing))
1416 }
1417 }
1418}
1419
1420/// Lazily-loaded syntax set and theme (pure-Rust fancy-regex backend).
1421fn highlighter() -> &'static (SyntaxSet, Theme) {
1422 static HL: OnceLock<(SyntaxSet, Theme)> = OnceLock::new();
1423 HL.get_or_init(|| {
1424 let syntaxes = SyntaxSet::load_defaults_newlines();
1425 let themes = ThemeSet::load_defaults();
1426 let theme = themes
1427 .themes
1428 .get("InspiredGitHub")
1429 .or_else(|| themes.themes.values().next())
1430 .cloned()
1431 .expect("at least one default theme");
1432 (syntaxes, theme)
1433 })
1434}
1435
1436/// [`highlight`] through a byte-budgeted LRU keyed by blob oid + extension: a
1437/// blob's rendered HTML is immutable for its object id (the extension is part
1438/// of the key because it picks the syntax), so each file is highlighted once
1439/// rather than once per request — highlighting large files is by far the most
1440/// expensive thing a page view can do. The budget is
1441/// `http.highlight_cache_mb`; `0` bypasses the cache entirely (for
1442/// RAM-constrained hosts). Concurrent misses may both compute and the last
1443/// insert wins; that's benign.
1444fn cached_highlight(budget_bytes: usize, oid: &str, path: &str, text: &str) -> Arc<Vec<String>> {
1445 if budget_bytes == 0 {
1446 return Arc::new(highlight(path, text));
1447 }
1448 struct Cache {
1449 lru: lru::LruCache<String, Arc<Vec<String>>>,
1450 bytes: usize,
1451 }
1452 fn cost(key: &str, lines: &[String]) -> usize {
1453 key.len() + lines.iter().map(String::len).sum::<usize>()
1454 }
1455 static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
1456 let cache = CACHE.get_or_init(|| {
1457 Mutex::new(Cache {
1458 lru: lru::LruCache::unbounded(),
1459 bytes: 0,
1460 })
1461 });
1462
1463 let ext = std::path::Path::new(path)
1464 .extension()
1465 .and_then(|e| e.to_str())
1466 .unwrap_or("");
1467 let key = format!("{oid}\x00{ext}");
1468 if let Some(hit) = cache.lock().expect("cache lock").lru.get(&key) {
1469 return hit.clone();
1470 }
1471
1472 let lines = Arc::new(highlight(path, text));
1473 let mut c = cache.lock().expect("cache lock");
1474 c.bytes += cost(&key, &lines);
1475 if let Some(old) = c.lru.put(key.clone(), Arc::clone(&lines)) {
1476 c.bytes -= cost(&key, &old); // concurrent miss inserted it first
1477 }
1478 // Evict oldest entries until we're back under budget. An entry larger than
1479 // the whole budget evicts itself — memory stays bounded, it just never caches.
1480 while c.bytes > budget_bytes {
1481 let Some((k, v)) = c.lru.pop_lru() else { break };
1482 c.bytes -= cost(&k, &v);
1483 }
1484 lines
1485}
1486
1487/// Syntax-highlight `text` (chosen by file extension), returning per-line HTML.
1488/// Falls back to escaped plain text for large files or on any failure.
1489fn highlight(path: &str, text: &str) -> Vec<String> {
1490 if text.len() > 512 * 1024 {
1491 return text.lines().map(escape).collect();
1492 }
1493 let (syntaxes, theme) = highlighter();
1494 let syntax = std::path::Path::new(path)
1495 .extension()
1496 .and_then(|e| e.to_str())
1497 .and_then(|ext| syntaxes.find_syntax_by_extension(ext))
1498 .or_else(|| syntaxes.find_syntax_by_first_line(text.lines().next().unwrap_or("")))
1499 .unwrap_or_else(|| syntaxes.find_syntax_plain_text());
1500
1501 let mut h = HighlightLines::new(syntax, theme);
1502 text.lines()
1503 .map(|line| match h.highlight_line(line, syntaxes) {
1504 Ok(ranges) => styled_line_to_highlighted_html(&ranges, IncludeBackground::No)
1505 .unwrap_or_else(|_| escape(line)),
1506 Err(_) => escape(line),
1507 })
1508 .collect()
1509}
1510
1511fn escape(s: &str) -> String {
1512 s.replace('&', "&amp;")
1513 .replace('<', "&lt;")
1514 .replace('>', "&gt;")
1515}
1516
1517/// Format a Unix timestamp as `YYYY-MM-DD HH:MM UTC`.
1518fn fmt_time(secs: i64) -> String {
1519 match OffsetDateTime::from_unix_timestamp(secs) {
1520 Ok(t) => format!(
1521 "{:04}-{:02}-{:02} {:02}:{:02} UTC",
1522 t.year(),
1523 u8::from(t.month()),
1524 t.day(),
1525 t.hour(),
1526 t.minute()
1527 ),
1528 Err(_) => secs.to_string(),
1529 }
1530}
1531
1532/// Format a Unix timestamp as a bare `YYYY-MM-DD` (for compact tree rows).
1533fn fmt_date(secs: i64) -> String {
1534 match OffsetDateTime::from_unix_timestamp(secs) {
1535 Ok(t) => format!("{:04}-{:02}-{:02}", t.year(), u8::from(t.month()), t.day()),
1536 Err(_) => secs.to_string(),
1537 }
1538}
1539
1540/// Heuristic: treat content with a NUL in the first 8 KiB as binary.
1541fn is_binary(bytes: &[u8]) -> bool {
1542 bytes.iter().take(8192).any(|&b| b == 0)
1543}
1544
1545#[cfg(test)]
1546mod tests {
1547 use super::*;
1548
1549 #[test]
1550 fn markdown_by_extension_only() {
1551 assert!(is_markdown("README.md"));
1552 assert!(is_markdown("docs/guide.MarkDown"));
1553 assert!(!is_markdown("main.rs"));
1554 assert!(!is_markdown("md")); // no extension
1555 }
1556
1557 // Repo content is untrusted; rendered markdown must not become stored XSS.
1558 #[test]
1559 fn rendered_markdown_neutralizes_html_and_script_urls() {
1560 let out = render_markdown(
1561 "# title\n\n<script>alert(1)</script>\n\n[x](javascript:alert(1))\n\n![y](data:text/html,evil)\n\n[ok](https://example.com)\n",
1562 )
1563 .into_string();
1564 assert!(out.contains("<h1>title</h1>"), "markdown renders: {out}");
1565 assert!(!out.contains("<script>"), "raw HTML escaped: {out}");
1566 assert!(
1567 out.contains("&lt;script&gt;"),
1568 "raw HTML kept as text: {out}"
1569 );
1570 assert!(!out.contains("javascript:"), "script URL dropped: {out}");
1571 assert!(!out.contains("data:"), "data URL dropped: {out}");
1572 assert!(
1573 out.contains(r#"href="https://example.com""#),
1574 "normal links survive: {out}"
1575 );
1576 }
1577}