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