Add prosekit rich-text field, Gitea repo embeds, automation KV read endpoint; fix apex/www session-cookie mismatch on /auth/callback
Deploy / deploy (push) Successful in 29s
Deploy / deploy (push) Successful in 29s
- type: prosekit requirement kind, backed by public/prosekit-editor.js
(ProseMirror via prosekit, loaded from esm.sh, no bundler) - mirrors
its HTML into a paired hidden input so it reuses the existing
RwSignal/on:input wiring.
- Pasting a project.uhhm.no/<owner>/<repo> URL in the editor embeds a
repo card, resolved server-side via a new /gitea-repo handler
(content::gitea_repo_handler) so the browser never needs Gitea API
CORS.
- New /automation/kv/{bucket} handler, bearer-token gated
(AUTOMATION_READ_TOKEN), for backing automations (n8n) to read a
NATS KV bucket without a browser session.
- Fix: a login started on one of apex/www set its session cookie
there, but Kanidm's redirect_uri is fixed to PUBLIC_URL - landing
the callback on a different, empty session ("no login in
progress"). Caddy now redirects www -> apex so every visit stays on
one canonical host.
This commit is contained in:
+154
-7
@@ -143,6 +143,24 @@ impl Requirement {
|
||||
}
|
||||
}
|
||||
|
||||
/// Extracts `scheme://host` from a repo's normal browser URL (e.g.
|
||||
/// `https://project.uhhm.no/uhhm/questions` -> `https://project.uhhm.no`)
|
||||
/// - the Gitea API base every helper in this module builds requests
|
||||
/// against, including ones (like `resolve_gitea_repo`) that have
|
||||
/// nothing to do with content loading, just the same Gitea instance.
|
||||
#[cfg(feature = "ssr")]
|
||||
pub fn gitea_api_base(repo_url: &str) -> anyhow::Result<String> {
|
||||
let parsed = url::Url::parse(repo_url)
|
||||
.map_err(|e| anyhow::anyhow!("parsing repo url {repo_url}: {e}"))?;
|
||||
Ok(format!(
|
||||
"{}://{}",
|
||||
parsed.scheme(),
|
||||
parsed
|
||||
.host_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("no host in repo url {repo_url}"))?
|
||||
))
|
||||
}
|
||||
|
||||
/// Fetches every `*.yaml` file under `subdir` in a Gitea repo as a
|
||||
/// `Question`, keyed by its own `id`. `repo_url` is the repo's normal
|
||||
/// browser URL (e.g. `https://project.uhhm.no/uhhm/questions`) - the
|
||||
@@ -158,13 +176,7 @@ pub async fn load_questions_from_gitea(
|
||||
) -> anyhow::Result<std::collections::HashMap<String, Question>> {
|
||||
let parsed = url::Url::parse(repo_url)
|
||||
.map_err(|e| anyhow::anyhow!("parsing content repo url {repo_url}: {e}"))?;
|
||||
let api_base = format!(
|
||||
"{}://{}",
|
||||
parsed.scheme(),
|
||||
parsed
|
||||
.host_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("no host in content repo url {repo_url}"))?
|
||||
);
|
||||
let api_base = gitea_api_base(repo_url)?;
|
||||
let mut segments = parsed
|
||||
.path_segments()
|
||||
.ok_or_else(|| anyhow::anyhow!("no path in content repo url {repo_url}"))?;
|
||||
@@ -261,3 +273,138 @@ pub async fn watch_for_reload(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
|
||||
/// 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<crate::server::AppState>,
|
||||
axum::extract::Query(query): axum::extract::Query<GiteaRepoQuery>,
|
||||
) -> Result<axum::Json<GiteaRepoInfo>, (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 client = openidconnect::reqwest::Client::new();
|
||||
let api_url = format!("{}/api/v1/repos/{owner}/{repo}", state.gitea_base);
|
||||
let body = client
|
||||
.get(&api_url)
|
||||
.send()
|
||||
.await
|
||||
.and_then(|r| r.error_for_status())
|
||||
.map_err(|e| (axum::http::StatusCode::BAD_GATEWAY, format!("fetching {api_url}: {e}")))?
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
(
|
||||
axum::http::StatusCode::BAD_GATEWAY,
|
||||
format!("reading repo info from {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<crate::server::AppState>,
|
||||
axum::extract::Path(bucket): axum::extract::Path<String>,
|
||||
headers: axum::http::HeaderMap,
|
||||
) -> Result<axum::Json<serde_json::Value>, (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()));
|
||||
}
|
||||
|
||||
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<String> = 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::<serde_json::Value>(&bytes) {
|
||||
items.push(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(axum::Json(serde_json::Value::Array(items)))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user