//! The Axum routes that expose content and buckets outside the Leptos //! app: content-shipped assets proxied same-origin, repo info for the //! showcase, and the automation read API over KV buckets. use super::*; /// A repo-relative asset path portal is willing to proxy from the /// content repo: plain segments only - no traversal, no leading slash, /// no scheme - so `/site/` can only ever reach the content repo. pub fn is_safe_site_path(path: &str) -> bool { !path.is_empty() && !path.starts_with('/') && path.split('/').all(|seg| { !seg.is_empty() && seg != ".." && seg .chars() .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.') }) } /// A public Gitea repo's basic info - what `resolve_gitea_repo` returns /// for the prosekit editor's repo-embed node to render as a static /// card, baked in once at embed time rather than re-fetched by every /// reader (an emailed newsletter can't run JS to do that anyway). #[derive(Clone, Debug, Serialize, Deserialize)] pub struct GiteaRepoInfo { pub owner: String, pub repo: String, pub description: String, pub url: String, } #[derive(Deserialize)] #[cfg(feature = "ssr")] pub struct GiteaRepoQuery { pub owner: String, pub repo: String, } /// `GET /site/{*path}` - serves a file from the content repo's default /// branch same-origin, so content-shipped assets (the hero module, /// its stylesheet) are importable by the page: Gitea's raw endpoint /// sends no CORS headers, and an ES module import across origins is /// refused without them. Path is validated to plain segments /// (`is_safe_site_path`), the response revalidates like /pkg /// (Cache-Control: no-cache) so a content push shows up on reload. #[cfg(feature = "ssr")] pub async fn site_asset_handler( axum::extract::State(state): axum::extract::State, axum::extract::Path(path): axum::extract::Path, ) -> axum::response::Response { use axum::http::{header, StatusCode}; use axum::response::IntoResponse; if !is_safe_site_path(&path) { return (StatusCode::BAD_REQUEST, "invalid asset path").into_response(); } let url = format!("{}/{path}?ref={}", state.content_raw_base, state.content_branch); let resp = match crate::http::client().get(&url).send().await.and_then(|r| r.error_for_status()) { Ok(r) => r, Err(e) => { tracing::warn!("site asset {path}: {e}"); return (StatusCode::NOT_FOUND, "no such site asset").into_response(); } }; let bytes = match crate::http::bytes(resp, crate::http::ASSET_CAP).await { Ok(b) => axum::body::Bytes::from(b), Err(e) => return (StatusCode::BAD_GATEWAY, e.to_string()).into_response(), }; let mime = match path.rsplit('.').next() { Some("js") | Some("mjs") => "text/javascript; charset=utf-8", Some("css") => "text/css; charset=utf-8", Some("svg") => "image/svg+xml", Some("json") => "application/json", Some("png") => "image/png", Some("webp") => "image/webp", Some("avif") => "image/avif", Some("ico") => "image/x-icon", Some("woff2") => "font/woff2", _ => "application/octet-stream", }; ( [(header::CONTENT_TYPE, mime), (header::CACHE_CONTROL, "no-cache")], bytes, ) .into_response() } /// Looks up `owner/repo` on the same Gitea instance content is loaded /// from (`AppState.gitea_base`) - a raw Axum handler (mounted at /// `/gitea-repo` in `main.rs`), not a Leptos server fn, since the /// caller here is the prosekit editor's own paste-to-embed rule (see /// `prosekit-editor.js`) doing a plain `fetch`, the same reason /// `/upload` (`src/upload.rs`) is a raw handler rather than a `#[server]` /// fn. Keeping this server-resolved (rather than having the browser /// call Gitea's API directly) is consistent with every other backing /// store in this app, and sidesteps needing a CORS allowance on Gitea's /// side just for this. No auth, same as content loading - resolves /// only what's already public. #[cfg(feature = "ssr")] pub async fn gitea_repo_handler( axum::extract::State(state): axum::extract::State, axum::extract::Query(query): axum::extract::Query, ) -> Result, (axum::http::StatusCode, String)> { let is_safe_segment = |s: &str| { !s.is_empty() && s.chars() .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.') }; if !is_safe_segment(&query.owner) || !is_safe_segment(&query.repo) { return Err((axum::http::StatusCode::BAD_REQUEST, "invalid owner/repo".to_string())); } let GiteaRepoQuery { owner, repo } = query; let api_url = format!("{}/api/v1/repos/{owner}/{repo}", state.gitea_base); let body = crate::http::get_text(&api_url, crate::http::GITEA_CAP) .await .map_err(|e| (axum::http::StatusCode::BAD_GATEWAY, format!("fetching {api_url}: {e}")))?; let json: serde_json::Value = serde_json::from_str(&body).map_err(|e| { ( axum::http::StatusCode::BAD_GATEWAY, format!("parsing repo info from {api_url}: {e}"), ) })?; Ok(axum::Json(GiteaRepoInfo { owner: owner.clone(), repo: repo.clone(), description: json .get("description") .and_then(|v| v.as_str()) .unwrap_or("") .to_string(), url: json .get("html_url") .and_then(|v| v.as_str()) .map(|s| s.to_string()) .unwrap_or_else(|| format!("{}/{owner}/{repo}", state.gitea_base)), })) } /// Lists every entry in a NATS KV bucket as JSON - a raw Axum handler /// (mounted at `/automation/kv/{bucket}` in `main.rs`), for backing /// automations (e.g. an n8n workflow reading `portal_subscribers` to /// send a newsletter) that aren't a signed-in browser session and so /// can't go through `resource::get_resource`'s Kanidm-group check. /// Gated by a single shared bearer token (`AUTOMATION_READ_TOKEN`) - /// deliberately not per-caller/per-bucket scoped, since every current /// caller is a trusted internal automation, not a third party. Read /// only, matching `get_resource`'s own "reads can be public/shared, /// mutations always need real identity" split - nothing here writes. #[cfg(feature = "ssr")] pub async fn automation_kv_handler( axum::extract::State(state): axum::extract::State, axum::extract::Path(bucket): axum::extract::Path, headers: axum::http::HeaderMap, ) -> Result, (axum::http::StatusCode, String)> { let expected = std::env::var("AUTOMATION_READ_TOKEN").unwrap_or_default(); let presented = headers .get(axum::http::header::AUTHORIZATION) .and_then(|v| v.to_str().ok()) .and_then(|v| v.strip_prefix("Bearer ")) .unwrap_or(""); if expected.is_empty() || presented != expected { return Err((axum::http::StatusCode::UNAUTHORIZED, "unauthorized".to_string())); } // The token authenticates the automation service; what it may read // is the policy's to say, like every other principal. let decision = crate::access::decide_and_publish( &state.nats, &state.access.load(), &crate::access::Principal::Service { name: "automation".to_string() }, crate::access::Action::AutomationRead, &crate::access::Resource::Bucket { name: bucket.clone() }, serde_json::json!({}), ); if !decision.allow { return Err((axum::http::StatusCode::FORBIDDEN, "not authorized".to_string())); } let store = state .jetstream .get_key_value(&bucket) .await .map_err(|e| (axum::http::StatusCode::BAD_GATEWAY, format!("bucket unavailable: {e}")))?; use futures::TryStreamExt; let keys: Vec = store .keys() .await .map_err(|e| (axum::http::StatusCode::BAD_GATEWAY, e.to_string()))? .try_collect() .await .map_err(|e| (axum::http::StatusCode::BAD_GATEWAY, e.to_string()))?; let mut items = Vec::new(); for key in keys { if let Ok(Some(bytes)) = store.get(&key).await { if let Ok(value) = serde_json::from_slice::(&bytes) { items.push(value); } } } Ok(axum::Json(serde_json::Value::Array(items))) }