pub mod commit_line; pub mod commit_status; pub mod diff; pub mod find; pub mod heatmap; pub mod paging; pub mod parts; pub mod repo_list; pub mod review_thread; pub mod timeline; use std::collections::HashMap; use std::sync::OnceLock; use forge_core::ci::RunState; use forge_core::config::{BannerConfig, BannerLevel}; use forge_core::store::shell_activity::{ActorRun, ActorRuns, InboxKinds}; use forge_core::store::user_prefs::SOUND; use forge_core::token::hash_token; use forge_core::{Config, Error as CoreError, Session, User}; use hex::encode; use http::header::{ CONTENT_SECURITY_POLICY, REFERRER_POLICY, X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS, }; use http::{HeaderValue, Uri}; use sha2::{Digest, Sha256}; use topcoat::Result; use topcoat::context::{Cx, try_context}; use topcoat::cookie::{Cookies, cookies}; use topcoat::router::request::uri; use topcoat::router::response::{Response, response_headers}; use topcoat::router::{Body, Next, layer}; use topcoat::view::{Child, Unescaped, View, ViewExt, component, view}; use crate::i18n::admin::{self as ad, K as AK}; use crate::i18n::authoring::{self as au, K as AuK}; use crate::i18n::browse as br; use crate::i18n::code::{self as g, K}; use crate::i18n::link::{self as lk, K as LinkKey}; use crate::i18n::misc::{self as mi, K as MK}; use crate::i18n::orgs::{self as o, K as OK}; use crate::i18n::s; use crate::i18n::{self, Key, Lang, t}; use crate::live::LiveSeq; use crate::render::highlight::highlight_css; use crate::state::AppState; use crate::theme::Theme; pub const STYLESHEET_HREF: &str = concat!("/assets/main.css?v=", env!("FORGE_MAIN_CSS_V")); pub const FIGTREE_PRELOAD_HREF: &str = "/assets/fonts/figtree-5.3.0-latin-wght.woff2"; pub fn highlight_href() -> &'static str { static HREF: OnceLock = OnceLock::new(); HREF.get_or_init(|| { let version = encode(Sha256::digest(highlight_css_text().as_bytes())); format!("/assets/highlight.css?v={}", &version[..12]) }) } pub const NAV_SCRIPT_HREF: &str = concat!("/assets/nav.js?v=", env!("FORGE_NAV_JS_V")); const CSP: &str = "default-src 'self'; style-src 'self'; img-src 'self' data:; form-action 'self'; frame-ancestors 'none'"; static APP_CSP: OnceLock = OnceLock::new(); fn origin_of(base: &str) -> Option { let uri: Uri = base.trim().parse().ok()?; let scheme = uri.scheme_str()?; if scheme != "http" && scheme != "https" { return None; } let authority = uri.authority()?.as_str(); if authority.contains('@') { return None; } Some(format!("{scheme}://{authority}")) } fn csp_for(raw_origin: Option<&str>) -> String { match raw_origin { Some(origin) => format!( "default-src 'self'; style-src 'self'; img-src 'self' data: {origin}; form-action 'self'; frame-ancestors 'none'" ), None => CSP.to_owned(), } } fn csp_header(base_url: &str) -> HeaderValue { let policy = csp_for(origin_of(base_url).as_deref()); HeaderValue::from_str(&policy).unwrap_or_else(|_| HeaderValue::from_static(CSP)) } const TOP_LEVEL_PAGES: &[&str] = &[ "explore", "notifications", "settings", "admin", "new", "login", "logout", "register", "forgot", "review-requests", "setup", "needs-you", "verify", "reset", "org", ]; fn percent_decode(s: &str) -> String { let bytes = s.as_bytes(); let mut out = Vec::with_capacity(bytes.len()); let mut i = 0; while i < bytes.len() { if bytes[i] == b'%' && let Some(hex) = s.get(i + 1..i + 3) && hex.bytes().all(|b| b.is_ascii_hexdigit()) && let Ok(byte) = u8::from_str_radix(hex, 16) { out.push(byte); i += 3; } else { out.push(bytes[i]); i += 1; } } String::from_utf8_lossy(&out).into_owned() } fn crumb_label(part: &str) -> String { if part.len() == 40 && part.bytes().all(|b| b.is_ascii_hexdigit()) { part[..7].to_owned() } else { part.to_owned() } } fn step_label(lang: Lang, word: &str) -> String { match word { "new" => s(lang, "New", "Yeni").to_owned(), "edit" => s(lang, "Edit", "Düzenle").to_owned(), "history" => s(lang, "History", "Geçmiş").to_owned(), "revisions" => s(lang, "Revisions", "Sürümler").to_owned(), "files" => s(lang, "Files", "Dosyalar").to_owned(), "commits" => g::t(lang, K::TabCommits).to_owned(), other => crumb_label(other), } } fn repo_section_label(lang: Lang, kind: &str) -> Option { match kind { "issues" | "pulls" | "ci" | "commits" | "branches" | "tags" | "releases" | "settings" => { Some(tab_title(lang, kind, "")) } "milestones" => Some(s(lang, "Milestones", "Kilometre taşları").to_owned()), "labels" => Some(s(lang, "Labels", "Etiketler").to_owned()), _ => None, } } fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option)> { let parts: Vec = path .trim_matches('/') .split('/') .filter(|part| !part.is_empty()) .map(percent_decode) .collect(); let Some(owner) = parts.first() else { return Vec::new(); }; let titled = title.rsplit_once(" · ").map(|(_, last)| last.to_owned()); match parts .iter() .map(String::as_str) .collect::>() .as_slice() { ["org", name, rest @ ..] if *name != "new" && !rest.is_empty() => { let page = titled.unwrap_or_else(|| step_label(lang, rest[rest.len() - 1])); return vec![((*name).to_owned(), Some(user_href(name))), (page, None)]; } _ => {} } if owner.starts_with('-') || TOP_LEVEL_PAGES.contains(&owner.as_str()) { return Vec::new(); } let mut segments = vec![(owner.clone(), Some(user_href(owner)))]; if let Some(repo) = parts.get(1) { segments.push((repo.clone(), Some(repo_href(owner, repo, "", "")))); match &parts[2..] { [kind, git_ref, prefix @ ..] if matches!(kind.as_str(), "tree" | "blob") && !prefix.is_empty() => { let mut at = git_ref.clone(); for part in prefix { at.push('/'); at.push_str(part); segments.push((crumb_label(part), Some(repo_href(owner, repo, "tree", &at)))); } } [] => {} [kind, rest @ ..] => { let full = format!("{owner}/{repo}"); let mut tail = title.rsplit(" · "); let named = match tail.next() { Some(last) if last == full => None, Some(last) if last.starts_with(&format!("{full} ")) => tail.next(), last => last, } .map(str::to_owned); let section = if kind == "commit" { "commits" } else { kind.as_str() }; match (repo_section_label(lang, section), rest) { (None, [oid]) if kind == "scrub" => { let short: String = oid.chars().take(7).collect(); segments.push(( g::t(lang, K::TabCommits).to_owned(), Some(repo_href(owner, repo, "commits", "")), )); segments.push((short, Some(repo_href(owner, repo, "commit", oid)))); segments.push((step_label(lang, "files"), None)); } (None, rest) if matches!(kind.as_str(), "compare" | "search") => { let word = if kind == "compare" { s(lang, "Compare", "Karşılaştır") } else { s(lang, "Search", "Ara") }; if rest.is_empty() { segments.push((word.to_owned(), None)); } else { segments .push((word.to_owned(), Some(repo_href(owner, repo, kind, "")))); segments.push((rest.join("/"), None)); } } (None, _) | (Some(_), []) => { let page = named.unwrap_or_else(|| { parts[2..] .iter() .map(|part| crumb_label(part)) .collect::>() .join("/") }); segments.push((page, None)); } (Some(label), rest) => { segments.push((label, Some(repo_href(owner, repo, section, "")))); let item = rest[0].as_str(); let numbered = matches!(section, "issues" | "pulls") && item.bytes().all(|b| b.is_ascii_digit()); match (section, rest) { ("ci", [runs, number]) if runs == "runs" => { segments.push((format!("#{number}"), None)); } _ if numbered && rest.len() == 1 => { segments.push((format!("#{item}"), None)); } _ if numbered => { segments.push(( format!("#{item}"), Some(repo_href(owner, repo, section, item)), )); let step = if rest.iter().any(|part| part == "history") { "history" } else { rest[rest.len() - 1].as_str() }; segments.push((step_label(lang, step), None)); } ("settings", [page, more @ ..]) if !more.is_empty() && page != "-" => { let page_label = match page.as_str() { "hooks" => { i18n::integrations::t(lang, i18n::integrations::K::Webhooks) .to_owned() } other => crumb_label(other), }; segments.push(( page_label, Some(repo_href(owner, repo, section, page)), )); let last = more[more.len() - 1].as_str(); segments.push((step_label(lang, last), None)); } _ => { let page = named.unwrap_or_else(|| { step_label(lang, rest[rest.len() - 1].as_str()) }); segments.push((page, None)); } } } } } } } if let Some(last) = segments.last_mut() { last.1 = None; } segments } struct PathCrumb { label: String, href: Option, class: &'static str, } struct StripRun { pill_class: String, row_class: String, label: String, text: String, href: String, } struct LiveStrip { runs: Vec, summary_class: &'static str, summary: String, } fn live_strip(lang: Lang, runs: &ActorRuns) -> LiveStrip { let mut rows = Vec::new(); for run in &runs.running { let job = run.current_job.as_deref().unwrap_or(""); rows.push(strip_run( "hot", run, if job.is_empty() { String::new() } else { format!(" {job}") }, )); } for run in &runs.finished { let (state, word) = match run.state { RunState::Success => ("ok", mi::t(lang, MK::Passed)), RunState::Failure | RunState::Error => ("bad", mi::t(lang, MK::Failed)), RunState::Cancelled => ("off", mi::t(lang, MK::Cancelled)), _ => continue, }; rows.push(strip_run(state, run, format!(" {word}"))); } let count = |pred: fn(RunState) -> bool| { runs.finished.iter().filter(|run| pred(run.state)).count() as u64 }; let running = runs.running.len() as u64; let failed = count(|state| matches!(state, RunState::Failure | RunState::Error)); let passed = count(|state| matches!(state, RunState::Success)); let cancelled = count(|state| matches!(state, RunState::Cancelled)); let summary_class = if running > 0 { "pill hot" } else if failed > 0 { "pill bad" } else if passed > 0 { "pill ok" } else { "pill off" }; let parts = [ (running, mi::running_count as fn(Lang, u64) -> String), (failed, mi::failed_count), (passed, mi::passed_count), (cancelled, mi::cancelled_count), ]; let summary = parts .iter() .filter(|(n, _)| *n > 0) .map(|(n, phrase)| phrase(lang, *n)) .collect::>() .join(" · "); LiveStrip { runs: rows, summary_class, summary, } } fn strip_run(state: &str, run: &ActorRun, text: String) -> StripRun { StripRun { pill_class: format!("pill {state}"), row_class: format!("strip-row {state}"), label: format!("{} #{}", run.repo, run.number), text, href: repo_href(&run.owner, &run.repo, "ci", &format!("runs/{}", run.number)), } } fn count_template(phrase: &str, n: u64) -> String { phrase.replacen(&n.to_string(), "{n}", 1) } fn no_runs() -> ActorRuns { ActorRuns { running: Vec::new(), finished: Vec::new(), failing: 0, newest_failing: None, } } #[derive(Clone)] struct ProfileCorner { username: String, name: String, avatar: String, csrf: String, is_admin: bool, unread: u64, waiting: bool, } #[component] async fn profile_corner(cx: &Cx, lang: Lang, corner: ProfileCorner) -> Result { let profile_href = user_href(&corner.username); let profile_label = mi::t(lang, MK::YourProfile); let settings_label = o::t(lang, OK::Settings); let admin_label = ad::t(lang, AK::AdminArea); let logout_label = t(lang, Key::LogOut); let inbox_label = t(lang, Key::Notifications); let class = if corner.unread > 0 || corner.waiting { "corner waiting" } else { "corner" }; Ok(view! {
}) } #[component] pub async fn shell( cx: &Cx, title: &str, viewer: Option<&(User, Session)>, #[default] extra_stylesheet: Option<&str>, #[default] parents: Vec<(String, String)>, #[default] child: Child<'_>, ) -> Result { let full_title = format!("{title} \u{b7} forge"); let (unread, inbox, runs) = match viewer { Some((user, _)) => match try_context::(cx) { Some(state) => ( state.store.unread_count(&user.id).await?, state.store.inbox_kind_counts(&user.id).await?, state.store.actor_runs(&user.id, 120).await?, ), None => (0, InboxKinds::default(), no_runs()), }, None => (0, InboxKinds::default(), no_runs()), }; let signed_in = viewer.is_some(); let theme_csrf = viewer.map(|(_, session)| session.csrf_token.clone()); let back = uri(cx).path_and_query().map(|p| p.as_str().to_owned()); let lang = i18n::lang(cx, viewer.map(|(user, _)| user)); let prefs = match (viewer, try_context::(cx)) { (Some((user, _)), Some(state)) => Some(state.store.user_prefs(&user.id).await?), _ => None, }; let banner = current_banner(cx, prefs.as_ref()); let sound_attr = sound_attr(prefs.as_ref()); let banner_back = back.clone().unwrap_or_else(|| "/".to_owned()); let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss); let section = if signed_in { section_for(lang, uri(cx).path()) } else { None }; let width = page_width(uri(cx).path()); let theme_attr = crate::theme::data_theme(cx, viewer.map(|(user, _)| user)); let rel_words_attr = rel_words(lang); let rel_now_attr = now_unix().to_string(); let (stored_accent_light, stored_accent_dark, stored_base_light, stored_base_dark) = match viewer { Some((user, _)) => ( user.accent.as_str(), user.accent_dark.as_str(), user.base_light.as_str(), user.base_dark.as_str(), ), None => ( crate::accent_palette::DEFAULT, crate::accent_palette::DEFAULT, crate::accent_palette::BASE_DEFAULT, crate::accent_palette::BASE_DEFAULT, ), }; let accent_light_id = crate::accent::accent_id(stored_accent_light); let accent_dark_id = crate::accent::accent_id(stored_accent_dark); let base_light_id = crate::accent::base_id(stored_base_light); let base_dark_id = crate::accent::base_id(stored_base_dark); let custom_css = crate::accent::custom_css_href( accent_light_id, accent_dark_id, base_light_id, base_dark_id, ); let sidebar_side = match viewer { Some((user, _)) if user.sidebar_side == "right" => "right", _ => "left", }; let theme_pref = crate::theme::preference(cx, viewer.map(|(user, _)| user)); let next_theme = theme_pref.next().as_str(); let theme_state = match theme_pref { Theme::Light => mi::t(lang, MK::Light), Theme::Dark => mi::t(lang, MK::Dark), Theme::Auto => mi::t(lang, MK::MatchSystem), }; let theme_next = match theme_pref.next() { Theme::Light => MK::SwitchToLight, Theme::Dark => MK::SwitchToDark, Theme::Auto => MK::SwitchToMatchSystem, }; let switch_label = format!( "{}: {}. {}", mi::t(lang, MK::ThemeLabel), theme_state, mi::t(lang, theme_next), ); let palette_label = br::t(lang, br::K::PaletteOpen).to_owned(); let explore_label = t(lang, Key::Explore); let home_label = o::t(lang, OK::Home); let mut segments = path_segments(lang, uri(cx).path(), title); if segments.is_empty() { if let Some(section) = §ion { let first = section.items.first().map(|item| item.href.clone()); if section.title != title { segments.push((section.title.clone(), first)); } let path = uri(cx).path(); if let Some(item) = section.items.iter().find(|item| { path.strip_prefix(item.href.as_str()) .is_some_and(|below| below.starts_with('/')) }) { segments.push((item.label.to_owned(), Some(item.href.clone()))); } } segments.push((title.to_owned(), None)); } if !parents.is_empty() { let at = segments.len().saturating_sub(1); for (offset, (label, href)) in parents.into_iter().enumerate() { segments.insert(at + offset, (label, Some(href))); } } let path_attr = segments .iter() .map(|(label, _)| label.as_str()) .collect::>() .join("/"); let crumbs: Vec = segments .into_iter() .enumerate() .map(|(i, (label, href))| PathCrumb { class: if i == 0 && href.is_some() { "pathbar-seg owner" } else { "pathbar-seg" }, label, href, }) .collect(); let strip = live_strip(lang, &runs); let running_tpl = count_template(&mi::running_count(lang, 2), 2); let failed_tpl = count_template(&mi::failed_count(lang, 2), 2); let passed_tpl = count_template(&mi::passed_count(lang, 2), 2); let cancelled_tpl = count_template(&mi::cancelled_count(lang, 2), 2); let runs_label = mi::t(lang, MK::YourCiRuns); let search_for_label = mi::t(lang, MK::SearchPublicReposFor); let corner = viewer.map(|(user, session)| ProfileCorner { username: user.username.clone(), name: user .display_name .as_deref() .map(str::trim) .filter(|n| !n.is_empty()) .unwrap_or(&user.username) .to_owned(), avatar: avatar_url(&user.username, user.avatar_hash.as_deref()), csrf: session.csrf_token.clone(), is_admin: user.is_admin, unread, waiting: inbox.reviews + inbox.mentions + runs.failing > 0, }); let live_seq = try_context::(cx).map(|seq| seq.0.to_string()); Ok(view! { (full_title) if let Some(href) = &custom_css { } if let Some(href) = extra_stylesheet { }
if let Some(corner) = corner {
profile_corner(lang: lang, corner: corner)
} "forge"
(explore_label) if signed_in {
if strip.runs.len() == 1 { for run in strip.runs.iter() { (run.label.as_str())(run.text.as_str()) } } if strip.runs.len() > 1 {
(strip.summary.as_str())
}
} else {
if let Some(csrf) = theme_csrf { } if let Some(back) = back { }
(t(lang, Key::LogIn)) }
if let Some(banner) = banner {

(banner.message.as_str())

}
if let Some(section) = section { section_tabs(key: section.key, label: section.title.as_str(), items: section.items, current: section.current, live: section.live) } (child)
} .boxed()) } #[derive(Clone)] pub struct NavItem { pub key: &'static str, pub href: String, pub label: &'static str, } #[derive(Clone)] pub struct Section { pub key: &'static str, pub title: String, pub items: Vec, pub current: &'static str, pub live: &'static str, } pub fn page_width(path: &str) -> &'static str { let parts: Vec<&str> = path.trim_matches('/').split('/').collect(); match parts.as_slice() { ["settings" | "admin", ..] | ["new", ..] | ["org", "new"] | ["org", _, "settings", ..] => { "col" } [ "login" | "register" | "forgot" | "reset" | "setup" | "invite", .., ] => "col", [_, _, section, ..] => match *section { "settings" | "new" | "edit" | "fork" | "transfer" | "rename" => "col", "tree" | "blob" | "blame" | "commit" | "compare" | "ci" | "raw" | "edit-file" | "scrub" => "wide", "pulls" if parts.len() > 4 => "wide", _ => "read", }, [_, _] => "wide", _ => "read", } } pub fn admin_items(lang: Lang) -> Vec { let item = |key, href: &'static str, label| NavItem { key, href: href.to_owned(), label, }; vec![ item("users", "/admin/users", ad::t(lang, AK::Users)), item("runners", "/admin/runners", ad::t(lang, AK::Runners)), item("server", "/admin/server", ad::t(lang, AK::ServerSettings)), item("mail", "/admin/mail", ad::t(lang, AK::Mail)), item("backups", "/admin/backups", ad::t(lang, AK::Backups)), item( "health", "/admin/health", crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Health), ), item("audit", "/admin/audit", ad::t(lang, AK::AuditLog)), ] } pub fn profile_items( lang: Lang, username: &str, is_org: bool, own_profile: bool, org_member: bool, ) -> Vec { let profile = format!("/{}", enc(username)); let tab = |key: &'static str, label: &'static str| NavItem { key, href: format!("{profile}?tab={key}"), label, }; let mut items = vec![ tab("overview", o::t(lang, OK::TabOverview)), tab("repositories", o::t(lang, OK::Repositories)), ]; if !is_org { items.push(tab("stars", o::t(lang, OK::TabStars))); } if own_profile { items.push(tab("organizations", o::t(lang, OK::Organizations))); } if is_org && org_member { let org = format!("/org/{}", enc(username)); items.push(NavItem { key: "members", href: format!("{org}/members"), label: o::t(lang, OK::Members), }); items.push(NavItem { key: "teams", href: format!("{org}/teams"), label: o::t(lang, OK::Teams), }); } items } pub fn global_items(lang: Lang, can_create_org: bool) -> Vec { let item = |key: &'static str, href: &'static str, label: &'static str| NavItem { key, href: href.to_owned(), label, }; let mut items = vec![ item("explore", "/explore", t(lang, Key::Explore)), item( "notifications", "/notifications", t(lang, Key::Notifications), ), item( "reviews", "/review-requests", au::t(lang, AuK::ReviewRequests), ), item( "needs-you", "/needs-you", crate::i18n::needs::t(lang, crate::i18n::needs::K::NeedsYou), ), item("new", "/new", t(lang, Key::NewRepository)), ]; if can_create_org { items.push(item("new-org", "/org/new", o::t(lang, OK::NewOrganization))); } items } pub fn settings_items(lang: Lang) -> Vec { let pk = crate::i18n::s; let item = |key, href: &'static str, label| NavItem { key, href: href.to_owned(), label, }; vec![ item("profile", "/settings/profile", t(lang, Key::Profile)), item( "appearance", "/settings/appearance", mi::t(lang, MK::Appearance), ), item( "notifications", "/settings/notifications", t(lang, Key::Notifications), ), item("security", "/settings/security", t(lang, Key::Security)), item("keys", "/settings/keys", pk(lang, "Keys", "Anahtarlar")), ] } pub fn section_for(lang: Lang, path: &str) -> Option
{ let mut parts = path.trim_matches('/').split('/'); let first = parts.next()?; let second = parts.next().unwrap_or(""); let (key, title, items) = match first { "admin" => ( "admin", ad::t(lang, AK::AdminArea).to_owned(), admin_items(lang), ), "settings" => ( "settings", o::t(lang, OK::Settings).to_owned(), settings_items(lang), ), _ => return None, }; let second = match (first, second) { (_, "sessions") => "security", (_, "gpg" | "tokens") => "keys", ("admin", "invites") => "users", ("admin", "replication") => "backups", (_, other) => other, }; let current = items .iter() .find(|item| item.key == second) .map_or("", |item| item.key); let live = if first == "settings" { "/settings/events" } else { "" }; Some(Section { key, title, items, current, live, }) } #[component] async fn section_tabs( cx: &Cx, key: &'static str, label: &str, items: Vec, current: &str, live: &str, ) -> Result { let live = (!live.is_empty()).then_some(live); let links: Vec<(NavItem, bool)> = items .into_iter() .map(|item| { let on = item.key == current; (item, on) }) .collect(); Ok(view! { }) } pub fn display_name(lang: Lang, username: &str) -> String { if forge_core::names::normalize_name(username) == forge_core::store::user_delete::GHOST_USERNAME { i18n::deleted_user(lang).to_owned() } else { username.to_owned() } } pub fn avatar_url(username: &str, hash: Option<&str>) -> String { match hash { Some(hash) => format!("/avatars/{}?v={hash}", enc(username)), None => default_data_url(username), } } pub fn avatar_url_unknown(username: &str) -> String { format!("/avatars/{}?v=default", enc(username)) } pub fn user_href(username: &str) -> String { format!("/{}", enc(username)) } #[component] pub async fn user_link(cx: &Cx, shown: &str, login: &str) -> Result { let href = user_href(login); Ok(view! { (shown) }) } #[component] pub async fn csrf_field(cx: &Cx, token: &str) -> Result { Ok(view! { }) } #[component] pub async fn alert(cx: &Cx, message: &str) -> Result { Ok(view! { }) } #[component] pub async fn notice_line(cx: &Cx, text: &str, is_error: bool) -> Result { Ok(view! { if is_error { alert(message: text) } else {

(text)

} }) } #[component] pub async fn empty_state( cx: &Cx, title: &str, #[default] hint: Option<&str>, #[default] child: Child<'_>, ) -> Result { Ok(view! {

(title)

if let Some(hint) = hint {

(hint)

}
(child)
}) } pub fn user_facing_message(err: &CoreError) -> Option { match err { CoreError::InvalidName(m) | CoreError::Invalid(m) | CoreError::Conflict(m) => { Some(m.clone()) } _ => None, } } #[layer("/")] pub async fn security_headers(cx: &Cx, body: Body, next: Next<'_>) -> Result { let headers = response_headers(cx); headers.append(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); headers.append(REFERRER_POLICY, HeaderValue::from_static("same-origin")); headers.append(X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); let csp = match try_context::(cx) { Some(state) => APP_CSP .get_or_init(|| csp_header(&state.config.user_content_base_url)) .clone(), None => HeaderValue::from_static(CSP), }; headers.append(CONTENT_SECURITY_POLICY, csp); next.run(cx, body).await } pub fn enc(s: &str) -> String { let mut out = String::with_capacity(s.len()); for b in s.bytes() { if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b'/') { out.push(char::from(b)); } else { out.push_str(&format!("%{b:02X}")); } } out } pub fn repo_href(owner: &str, repo: &str, section: &str, rest: &str) -> String { let mut href = format!("/{}/{}", enc(owner), enc(repo)); if !section.is_empty() { href.push('/'); href.push_str(section); } let rest = rest.trim_matches('/'); if !rest.is_empty() { href.push('/'); href.push_str(&enc(rest)); } href } pub use forge_core::time::{civil_from_days, days_from_civil, iso_time, now_unix}; pub fn query_value(cx: &Cx, key: &str) -> Option { let query = uri(cx).query()?; form_urlencoded::parse(query.as_bytes()) .find(|(name, _)| name == key) .map(|(_, value)| value.into_owned()) } pub fn take_notice_cookie( cx: &Cx, cookie: &str, notices: &[(&str, K, bool)], ) -> Option<(K, bool)> { let jar = cookies(cx); let value = jar.get(cookie)?.value().to_owned(); jar.remove(topcoat::cookie::Cookie::build((cookie.to_owned(), "")).path("/")); notices .iter() .find(|(word, _, _)| *word == value) .map(|(_, key, is_error)| (*key, *is_error)) } pub fn relative_time(lang: Lang, unix: i64, now: i64) -> String { use i18n::TimeUnit; let ahead = unix > now; let secs = if ahead { unix.saturating_sub(now) } else { now.saturating_sub(unix) }; let (n, unit) = match secs { 0..60 if ahead => (1, TimeUnit::Minute), 0..60 => return i18n::just_now(lang).to_owned(), 60..3_600 => (secs / 60, TimeUnit::Minute), 3_600..86_400 => (secs / 3_600, TimeUnit::Hour), 86_400..2_592_000 => (secs / 86_400, TimeUnit::Day), 2_592_000..31_536_000 => (secs / 2_592_000, TimeUnit::Month), _ => (secs / 31_536_000, TimeUnit::Year), }; if ahead { i18n::from_now(lang, n, unit) } else { i18n::ago(lang, n, unit) } } pub fn rel_words(lang: Lang) -> String { use i18n::TimeUnit; let units = [ TimeUnit::Minute, TimeUnit::Hour, TimeUnit::Day, TimeUnit::Month, TimeUnit::Year, ]; let mut words = vec![i18n::just_now(lang).to_owned()]; for unit in units { for n in [1, 2] { words.push(i18n::ago(lang, n, unit).replacen(&n.to_string(), "{n}", 1)); } } for unit in units { for n in [1, 2] { words.push(i18n::from_now(lang, n, unit).replacen(&n.to_string(), "{n}", 1)); } } words.join("|") } #[component] pub async fn rel_time(cx: &Cx, lang: Lang, stamp: &str) -> Result { let label = forge_core::time::stamp_to_unix(stamp) .map_or_else(String::new, |unix| relative_time(lang, unix, now_unix())); Ok(view! { }) } #[component] pub async fn rel_time_or_never(cx: &Cx, lang: Lang, stamp: Option<&str>) -> Result { Ok(view! { if let Some(stamp) = stamp { rel_time(lang: lang, stamp: stamp) } else { (t(lang, Key::Never)) } }) } #[component] pub async fn added_status( cx: &Cx, lang: Lang, added: Option<&str>, used: Option<&str>, ) -> Result { let sep = if added.is_some() && used.is_some() { " · " } else { "" }; Ok(view! { if let Some(stamp) = added { (i18n::dated_label(lang, Key::Added)) " " rel_time(lang: lang, stamp: stamp) } (sep) if let Some(stamp) = used { (i18n::dated_label(lang, Key::LastUsed)) " " rel_time(lang: lang, stamp: stamp) } }) } pub fn short_oid(oid: &str) -> &str { oid.get(..7).unwrap_or(oid) } pub fn human_size(lang: Lang, bytes: u64) -> String { let decimal = |value: f64| { let text = format!("{value:.1}"); match lang { Lang::En => text, Lang::Tr => text.replace('.', ","), } }; if bytes < 1024 { match lang { Lang::En if bytes == 1 => "1 byte".to_owned(), Lang::En => format!("{bytes} bytes"), Lang::Tr => format!("{bytes} bayt"), } } else if bytes < 1024 * 1024 { format!("{} KiB", decimal(bytes as f64 / 1024.0)) } else if bytes < 1024 * 1024 * 1024 { format!("{} MiB", decimal(bytes as f64 / (1024.0 * 1024.0))) } else if bytes < 1024 * 1024 * 1024 * 1024 { format!("{} GiB", decimal(bytes as f64 / (1024.0 * 1024.0 * 1024.0))) } else { format!( "{} TiB", decimal(bytes as f64 / (1024.0 * 1024.0 * 1024.0 * 1024.0)) ) } } fn tab_class(on: bool) -> &'static str { if on { "tab active" } else { "tab" } } fn tab_more_class(on: bool) -> &'static str { if on { "tab-more-link is-current" } else { "tab-more-link" } } #[component] pub async fn repo_tabs( cx: &Cx, owner: String, repo: String, default_branch: String, active: String, can_admin: bool, lang: Lang, #[default] open_issues: Option, #[default] open_pulls: Option, ) -> Result { let home = repo_href(&owner, &repo, "", ""); let issues = repo_href(&owner, &repo, "issues", ""); let issues_count = open_issues.filter(|n| *n > 0).map(|n| n.to_string()); let pulls = repo_href(&owner, &repo, "pulls", ""); let pulls_count = open_pulls.filter(|n| *n > 0).map(|n| n.to_string()); let commits = repo_href(&owner, &repo, "commits", &default_branch); let branches = repo_href(&owner, &repo, "branches", ""); let tags = repo_href(&owner, &repo, "tags", ""); let releases = repo_href(&owner, &repo, "releases", ""); let ci = repo_href(&owner, &repo, "ci", ""); let more_on = matches!( active.as_str(), "commits" | "branches" | "tags" | "releases" ); let code_on = active == "code" || more_on; let settings = repo_href(&owner, &repo, "settings", ""); Ok(view! { } .boxed()) } #[derive(Clone)] pub struct RefLink { pub name: String, pub href: String, pub current: bool, pub default: bool, pub updated: i64, } pub const REF_SHOWN: usize = 8; const BRANCH_ICON: &str = r#""#; const TAG_ICON: &str = r#""#; #[component] async fn ref_group( cx: &Cx, lang: Lang, kind: &'static str, heading: &'static str, links: Vec, now: i64, ) -> Result { let count = links.len(); let icon = if kind == "tags" { TAG_ICON } else { BRANCH_ICON }; let head_id = format!("ref-head-{kind}"); Ok(view! { if count > 0 {
(heading) (count)
} }) } #[component] pub async fn ref_selector( cx: &Cx, lang: Lang, label: &'static str, current: String, branches: Vec, tags: Vec, branches_href: String, tags_href: String, ) -> Result { let is_tag = !branches.iter().any(|b| b.current) && tags.iter().any(|t| t.current); let none = branches.is_empty() && tags.is_empty(); let now = now_unix(); Ok(view! {
(current.as_str())
ref_group(lang: lang, kind: "branches", heading: g::t(lang, K::BranchesTitle), links: branches, now: now) ref_group(lang: lang, kind: "tags", heading: g::t(lang, K::TagsTitle), links: tags, now: now)
}) } #[derive(Clone)] pub struct When { pub iso: String, pub absolute: String, pub relative: String, } impl When { pub fn new(lang: Lang, stamp: &str, tz: &str, now: i64) -> Self { let unix = stamp_unix(stamp); Self { iso: iso_time(unix), absolute: forge_core::tz::format_in_tz(unix, tz), relative: relative_time(lang, unix, now), } } } pub fn stamp_unix(stamp: &str) -> i64 { let field = |range: std::ops::Range| { stamp .get(range) .and_then(|digits| digits.parse::().ok()) }; let (Some(y), Some(mo), Some(d), Some(h), Some(mi), Some(s)) = ( field(0..4), field(5..7), field(8..10), field(11..13), field(14..16), field(17..19), ) else { return 0; }; days_from_civil(y, mo, d) * 86_400 + h * 3_600 + mi * 60 + s } pub fn highlight_css_text() -> &'static str { highlight_css() } pub const PALETTE: [&str; 8] = [ "#5E7D63", "#4A6750", "#3F5F46", "#4E6E68", "#3E6B63", "#5B6B4E", "#56705F", "#4F6A55", ]; pub fn default_svg(username: &str) -> String { let digest = Sha256::digest(username.as_bytes()); let color = PALETTE[usize::from(digest[0]) % PALETTE.len()]; let letter = username .chars() .next() .map_or_else(|| "?".to_owned(), |c| c.to_uppercase().collect()); let letter = xml_escape(&letter); format!( r##"{letter}"## ) } pub fn default_data_url(username: &str) -> String { let svg = default_svg(username); let mut out = String::with_capacity(svg.len() + 40); out.push_str("data:image/svg+xml,"); for byte in svg.bytes() { if byte.is_ascii_alphanumeric() || b" -_.~/=:;,'()".contains(&byte) { out.push(char::from(byte)); } else { out.push_str(&format!("%{byte:02X}")); } } out } fn xml_escape(text: &str) -> String { let mut out = String::with_capacity(text.len()); for c in text.chars() { match c { '&' => out.push_str("&"), '<' => out.push_str("<"), '>' => out.push_str(">"), '"' => out.push_str("""), '\'' => out.push_str("'"), other => out.push(other), } } out } pub const BANNER_COOKIE: &str = "forge_banner"; pub const BANNER_PREF: &str = "banner_dismissed"; #[derive(Debug, Clone, PartialEq, Eq)] pub struct BannerView { pub message: String, pub warning: bool, pub hash: String, pub expires: Option, } pub fn banner_hash(message: &str, level: BannerLevel) -> String { hash_token(&format!("{}\n{message}", level.as_str()))[..16].to_owned() } pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Option { if !config.active_at(now) { return None; } let message = config.message.trim().to_owned(); let hash = banner_hash(&message, config.level); if dismissed == Some(hash.as_str()) { return None; } Some(BannerView { message, warning: config.level == BannerLevel::Warning, hash, expires: config.expires_unix(), }) } pub fn current_banner(cx: &Cx, prefs: Option<&HashMap>) -> Option { let state = try_context::(cx)?; let live = state.live(); if live.banner.message.trim().is_empty() { return None; } let dismissed = match prefs { Some(prefs) => prefs.get(BANNER_PREF).cloned(), None => cookies(cx).get(BANNER_COOKIE).map(|c| c.value().to_owned()), }; view_for(&live.banner, now_unix(), dismissed.as_deref()) } pub fn tab_title(lang: Lang, active: &str, repo: &str) -> String { match active { "issues" => g::t(lang, K::TabIssues).to_owned(), "pulls" => g::t(lang, K::TabPulls).to_owned(), "ci" => g::t(lang, K::TabCi).to_owned(), "commits" => g::t(lang, K::TabCommits).to_owned(), "branches" => g::t(lang, K::BranchesTitle).to_owned(), "tags" => g::t(lang, K::TagsTitle).to_owned(), "releases" => g::t(lang, K::TabReleases).to_owned(), "settings" => g::t(lang, K::TabSettings).to_owned(), _ => repo.to_owned(), } } pub fn sound_attr(prefs: Option<&HashMap>) -> Option<&'static str> { let stored = prefs.and_then(|p| p.get(SOUND))?; (stored == "on").then_some("on") } pub fn https_clone_url(config: &Config, owner: &str, name: &str) -> String { format!( "{}/{owner}/{name}.git", config.base_url.trim_end_matches('/') ) } pub fn ssh_clone_url(config: &Config, owner: &str, name: &str) -> String { let host = &config.ssh_public_host; if config.ssh_public_port == 22 { format!("git@{host}:{owner}/{name}.git") } else { format!( "ssh://git@{host}:{}/{owner}/{name}.git", config.ssh_public_port ) } } #[cfg(test)] mod tests { use super::*; #[test] fn live_strip_is_one_pill_for_one_run_and_a_summary_for_more() { let run = |state, number| ActorRun { owner: "tahinli".into(), repo: "proj".into(), number, git_ref: "main".into(), state, created_at: String::new(), finished_at: None, jobs_total: 0, jobs_done: 0, current_job: None, }; let many = ActorRuns { running: vec![run(RunState::Running, 3)], finished: vec![run(RunState::Failure, 2), run(RunState::Cancelled, 1)], failing: 0, newest_failing: None, }; let strip = live_strip(Lang::En, &many); assert_eq!(strip.runs.len(), 3); assert_eq!(strip.summary, "1 running · 1 failed · 1 cancelled"); assert_eq!(strip.summary_class, "pill hot"); let alone = ActorRuns { running: Vec::new(), finished: vec![run(RunState::Cancelled, 1)], failing: 0, newest_failing: None, }; let one = live_strip(Lang::En, &alone); assert_eq!(one.runs.len(), 1); assert_eq!(one.runs[0].pill_class, "pill off"); assert_eq!(one.runs[0].text, " cancelled"); } #[test] fn repo_href_builds_each_form() { assert_eq!(repo_href("tahinli", "demo", "", ""), "/tahinli/demo"); assert_eq!( repo_href("tahinli", "demo", "tree", "feature/x/src"), "/tahinli/demo/tree/feature/x/src" ); assert_eq!( repo_href("tahinli", "demo", "tree", "main/"), "/tahinli/demo/tree/main" ); } #[test] fn path_segments_follow_the_request_path() { assert_eq!( path_segments(Lang::En, "/tahinli/forge/blob/main/src/main.rs", "main.rs"), vec![ ("tahinli".to_owned(), Some("/tahinli".to_owned())), ("forge".to_owned(), Some("/tahinli/forge".to_owned())), ( "src".to_owned(), Some("/tahinli/forge/tree/main/src".to_owned()) ), ("main.rs".to_owned(), None), ] ); assert_eq!( path_segments(Lang::En, "/tahinli/forge", "tahinli/forge"), vec![ ("tahinli".to_owned(), Some("/tahinli".to_owned())), ("forge".to_owned(), None), ] ); let (last, _) = path_segments(Lang::En, "/tahinli/forge/issues", "tahinli/forge · Issues").remove(2); assert_eq!(last, "Issues"); let crumbs = path_segments(Lang::En, "/tahinli/forge/commits/main", "tahinli/forge"); assert_eq!( crumbs[2], ( "Commits".to_owned(), Some("/tahinli/forge/commits".to_owned()) ) ); assert_eq!(crumbs[3], ("main".to_owned(), None)); let crumbs = path_segments(Lang::En, "/tahinli/forge/issues/4/edit", "tahinli/forge"); let labels: Vec<&str> = crumbs.iter().map(|(label, _)| label.as_str()).collect(); assert_eq!(labels, ["tahinli", "forge", "Issues", "#4", "Edit"]); assert_eq!(crumbs[3].1.as_deref(), Some("/tahinli/forge/issues/4")); assert!(path_segments(Lang::En, "/explore", "Explore").is_empty()); assert!(path_segments(Lang::En, "/", "Home").is_empty()); let (last, _) = path_segments( Lang::En, "/tahinli/forge/commit/0123456789abcdef0123456789abcdef01234567", "tahinli/forge", ) .remove(3); assert_eq!(last, "0123456"); } #[test] fn csp_allows_the_raw_origin_for_images_and_falls_back_otherwise() { let origin = origin_of("https://raw.forge.test:8443/some/path/"); assert_eq!(origin.as_deref(), Some("https://raw.forge.test:8443")); let csp = csp_for(origin.as_deref()); assert!(csp.contains("img-src 'self' data: https://raw.forge.test:8443;")); assert!(csp.contains("form-action 'self'; frame-ancestors 'none'")); assert_eq!(origin_of("not a url"), None); assert_eq!(origin_of("ftp://files.test"), None); assert_eq!(origin_of("https://user:pw@files.test"), None); assert_eq!(csp_for(None), CSP); } }