Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(auth): add builtin login and change-password pages for human sessions

Ruben Licio Reis1f333b2da082
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 348aa343..fd40148c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
unaffected. (#794)
### Added
+- Builtin `/web` login and change-password pages for human password sessions:
+ unauthenticated browser GETs to the wiki redirect to `{web_slug}/login`
+ (not bare JSON 401), forms call existing `POST /auth/login` /
+ `/auth/password` / `/auth/logout`, and `--web-ui-dir` custom SPAs stay
+ unchanged. (#811)
- macOS menu bar companion (`companions/ai-memory-macos`) that bundles the
`ai-memory` binary and `hooks/` tree, governs the existing LaunchAgent, and
opens the built-in web UI, `ai-memory status`, `config.toml`, the data
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index eb16e08a..dbd3de55 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -26,7 +26,10 @@ use ai_memory_mcp::{
use ai_memory_store::{
ReaderPool, Store, TokenPepper, WriterHandle, hash_session_secret, hash_token,
};
-use ai_memory_web::{WebMountSpec, normalize_prefix, split_web_routers, web_base_href};
+use ai_memory_web::{
+ HtmlAuthRedirectConfig, WebMountSpec, html_auth_redirect_mw, normalize_prefix,
+ split_web_routers, web_base_href,
+};
use ai_memory_wiki::{WatcherHandle, Wiki, migrations, run_wiki_migrations};
use anyhow::{Context, Result};
use axum::body::Body;
@@ -1404,16 +1407,34 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
base_path: &base_path,
},
)?;
+ // HTML navigational 401/403 → builtin login / change-password.
+ // Outer layer so it sees dual-auth responses; `/api/v1` stays JSON
+ // (`html_auth_redirect_mw` skips that prefix). Builtin wiki returns
+ // the cfg from split; custom SPA / web-off still builds one so the
+ // layer always has concrete login/change-password targets.
+ let html_auth = web.html_auth.unwrap_or_else(|| {
+ Arc::new(HtmlAuthRedirectConfig::from_mount(
+ &base_path,
+ &args.web_slug,
+ ))
+ });
let router = machine
.merge(healthz_router())
.merge(admin)
.merge(public_auth_router(auth_state.clone()))
.merge(session_auth_router(auth_state.clone()))
.merge(internal_auth_router(auth_state.clone()))
- .merge(web.protected.layer(axum::middleware::from_fn_with_state(
- auth_state.clone(),
- require_dual_auth,
- )))
+ .merge(
+ web.protected
+ .layer(axum::middleware::from_fn_with_state(
+ auth_state.clone(),
+ require_dual_auth,
+ ))
+ .layer(axum::middleware::from_fn_with_state(
+ html_auth,
+ html_auth_redirect_mw,
+ )),
+ )
.merge(web.public.layer(axum::middleware::from_fn_with_state(
auth_state.clone(),
expire_legacy_cookie_mw,
@@ -4099,26 +4120,121 @@ mod tests {
)
.unwrap();
let auth = Arc::new(AuthState::new(Some("secret".to_string())));
+ let html_auth = web
+ .html_auth
+ .expect("builtin wiki mount must return html_auth");
let router = apply_host_layer(
- web.protected.layer(axum::middleware::from_fn_with_state(
- auth,
- require_dual_auth,
- )),
+ web.public
+ .merge(
+ web.protected
+ .layer(axum::middleware::from_fn_with_state(
+ auth,
+ require_dual_auth,
+ ))
+ .layer(axum::middleware::from_fn_with_state(
+ html_auth,
+ html_auth_redirect_mw,
+ )),
+ ),
vec!["localhost".to_string()],
);
- let resp = router
+ // Non-HTML clients still see JSON 401.
+ let json_401 = router
+ .clone()
.oneshot(
Request::builder()
.uri("/web")
.header("Host", "localhost")
+ .header("Accept", "application/json")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
+ assert_eq!(json_401.status(), StatusCode::UNAUTHORIZED);
- assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+ // Browser navigations redirect to the public login page.
+ let html_redir = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/web")
+ .header("Host", "localhost")
+ .header("Accept", "text/html")
+ .header("sec-fetch-dest", "document")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(html_redir.status(), StatusCode::SEE_OTHER);
+ let location = html_redir
+ .headers()
+ .get(header::LOCATION)
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or_default();
+ assert!(
+ location.starts_with("/web/login?next="),
+ "expected login redirect, got {location}"
+ );
+
+ // Login HTML is public (no auth).
+ let login = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/web/login")
+ .header("Host", "localhost")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(login.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(login.into_body(), 64 * 1024)
+ .await
+ .unwrap();
+ let html = std::str::from_utf8(&body).unwrap();
+ assert!(html.contains("Sign in"), "login page body: {html}");
+ assert!(html.contains("ai-memory-base-path"), "inject base-path meta");
+
+ // Change-password HTML is public (must_change_password flow).
+ let change = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/web/change-password")
+ .header("Host", "localhost")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(change.status(), StatusCode::OK);
+ let change_body = axum::body::to_bytes(change.into_body(), 64 * 1024)
+ .await
+ .unwrap();
+ let change_html = std::str::from_utf8(&change_body).unwrap();
+ assert!(
+ change_html.contains("Change password"),
+ "change-password page body: {change_html}"
+ );
+
+ // `/api/v1` stays JSON even with an HTML Accept header.
+ let api = router
+ .oneshot(
+ Request::builder()
+ .uri("/api/v1/projects")
+ .header("Host", "localhost")
+ .header("Accept", "text/html")
+ .header("sec-fetch-dest", "document")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(api.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
diff --git a/crates/ai-memory-web/src/html_auth.rs b/crates/ai-memory-web/src/html_auth.rs
new file mode 100644
index 00000000..b6956948
--- /dev/null
+++ b/crates/ai-memory-web/src/html_auth.rs
@@ -0,0 +1,326 @@
+//! HTML auth redirect helpers for the builtin wiki browser.
+//!
+//! After [`require_dual_auth`](ai_memory_mcp::require_dual_auth) returns
+//! JSON 401/403, navigational browser GETs to the wiki should land on the
+//! builtin login / change-password pages instead. `/api/v1` stays JSON.
+
+use std::sync::Arc;
+
+use axum::extract::State;
+use axum::http::{Method, Request, StatusCode, header};
+use axum::middleware::Next;
+use axum::response::{IntoResponse, Redirect, Response};
+
+use crate::mount::normalize_prefix;
+
+/// Paths and prefixes the HTML auth redirect middleware needs.
+#[derive(Clone, Debug)]
+pub struct HtmlAuthRedirectConfig {
+ /// Normalised base path (`""` or `/wiki`).
+ pub base_path: String,
+ /// External wiki root (`""`, `/web`, or `/wiki/web`).
+ pub web_root: String,
+ /// External login path (`/web/login` or `/login` when mounted at root).
+ pub login_path: String,
+ /// External change-password path.
+ pub change_password_path: String,
+}
+
+impl HtmlAuthRedirectConfig {
+ /// Build redirect targets from the same base/slug the mount uses.
+ #[must_use]
+ pub fn from_mount(base_path: &str, web_slug: &str) -> Self {
+ let base_path = normalize_prefix(base_path);
+ let web_root = web_root(&base_path, web_slug);
+ let login_path = join_root(&web_root, "login");
+ let change_password_path = join_root(&web_root, "change-password");
+ Self {
+ base_path,
+ web_root,
+ login_path,
+ change_password_path,
+ }
+ }
+}
+
+/// `{base_path}{web_slug}` with both sides normalised; empty when both are root.
+#[must_use]
+pub(crate) fn web_root(base_path: &str, web_slug: &str) -> String {
+ format!(
+ "{}{}",
+ normalize_prefix(base_path),
+ normalize_prefix(web_slug)
+ )
+}
+
+fn join_root(web_root: &str, leaf: &str) -> String {
+ if web_root.is_empty() {
+ format!("/{leaf}")
+ } else {
+ format!("{web_root}/{leaf}")
+ }
+}
+
+/// Allow only same-origin relative paths under `web_root`.
+///
+/// Rejects protocol-relative `//`, absolute URLs (`http:` / `https:`),
+/// backslashes, and paths outside the wiki slug. Default is the wiki root.
+#[must_use]
+pub fn sanitize_next(raw: Option<&str>, web_root: &str) -> String {
+ let default = if web_root.is_empty() {
+ "/".to_string()
+ } else {
+ web_root.to_string()
+ };
+ let Some(raw) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
+ return default;
+ };
+ if raw.contains("://") || raw.starts_with("//") || raw.contains('\\') || raw.contains('\0')
+ {
+ return default;
+ }
+ if !raw.starts_with('/') {
+ return default;
+ }
+ let path = raw
+ .split_once(['?', '#'])
+ .map(|(p, _)| p)
+ .unwrap_or(raw);
+ if web_root.is_empty() {
+ // Wiki mounted at host/base root — still reject escaping to
+ // sibling host routes by requiring a single-path absolute form
+ // without `..` segments.
+ if path_has_dot_segment(path) {
+ return default;
+ }
+ return raw.to_string();
+ }
+ if path == web_root || path.starts_with(&format!("{web_root}/")) {
+ if path_has_dot_segment(path) {
+ return default;
+ }
+ return raw.to_string();
+ }
+ default
+}
+
+fn path_has_dot_segment(path: &str) -> bool {
+ path.split('/').any(|s| s == "." || s == "..")
+}
+
+/// Map JSON 401/403 on HTML navigational wiki GETs to the builtin auth pages.
+pub async fn html_auth_redirect_mw(
+ State(cfg): State<Arc<HtmlAuthRedirectConfig>>,
+ req: Request<axum::body::Body>,
+ next: Next,
+) -> Response {
+ let wants_html = is_html_navigation(&req);
+ let path = req.uri().path().to_string();
+ let full_path_and_query = {
+ let path = req.uri().path();
+ let q = req.uri().query();
+ // Reconstruct the external path: middleware runs inside the
+ // base-path nest, so prepend `base_path` for Location / next.
+ let external = if cfg.base_path.is_empty() {
+ path.to_string()
+ } else if path == "/" {
+ cfg.base_path.clone()
+ } else {
+ format!("{}{path}", cfg.base_path)
+ };
+ match q {
+ Some(q) if !q.is_empty() => format!("{external}?{q}"),
+ _ => external,
+ }
+ };
+ let is_api = is_api_v1_path(&path);
+
+ let resp = next.run(req).await;
+ if !wants_html || is_api {
+ return resp;
+ }
+ match resp.status() {
+ StatusCode::UNAUTHORIZED => {
+ let next_q = urlencoding_encode(&sanitize_next(
+ Some(&full_path_and_query),
+ &cfg.web_root,
+ ));
+ Redirect::to(&format!("{}?next={next_q}", cfg.login_path)).into_response()
+ }
+ StatusCode::FORBIDDEN => Redirect::to(&cfg.change_password_path).into_response(),
+ _ => resp,
+ }
+}
+
+fn is_api_v1_path(path: &str) -> bool {
+ path == "/api/v1" || path.starts_with("/api/v1/")
+}
+
+fn is_html_navigation(req: &Request<axum::body::Body>) -> bool {
+ if req.method() != Method::GET && req.method() != Method::HEAD {
+ return false;
+ }
+ if let Some(dest) = req
+ .headers()
+ .get("sec-fetch-dest")
+ .and_then(|v| v.to_str().ok())
+ {
+ return dest.eq_ignore_ascii_case("document");
+ }
+ req.headers()
+ .get(header::ACCEPT)
+ .and_then(|v| v.to_str().ok())
+ .is_some_and(|a| a.to_ascii_lowercase().contains("text/html"))
+}
+
+/// Minimal application/x-www-form-urlencoded encoder for the `next` query value.
+fn urlencoding_encode(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for b in s.bytes() {
+ match b {
+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
+ out.push(b as char);
+ }
+ b'/' => out.push_str("%2F"),
+ b'?' => out.push_str("%3F"),
+ b'=' => out.push_str("%3D"),
+ b'&' => out.push_str("%26"),
+ _ => {
+ use std::fmt::Write as _;
+ let _ = write!(out, "%{b:02X}");
+ }
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use axum::Router;
+ use axum::body::Body;
+ use axum::routing::get;
+ use tower::ServiceExt;
+
+ #[test]
+ fn sanitize_next_defaults_and_rejects_open_redirects() {
+ assert_eq!(sanitize_next(None, "/web"), "/web");
+ assert_eq!(sanitize_next(Some(""), "/web"), "/web");
+ assert_eq!(sanitize_next(Some("/web/w/a"), "/web"), "/web/w/a");
+ assert_eq!(
+ sanitize_next(Some("/web/search?q=x"), "/web"),
+ "/web/search?q=x"
+ );
+ assert_eq!(sanitize_next(Some("//evil.example"), "/web"), "/web");
+ assert_eq!(sanitize_next(Some("https://evil.example/"), "/web"), "/web");
+ assert_eq!(sanitize_next(Some("/other"), "/web"), "/web");
+ assert_eq!(sanitize_next(Some("/web/../admin"), "/web"), "/web");
+ assert_eq!(sanitize_next(Some("web/foo"), "/web"), "/web");
+ }
+
+ #[test]
+ fn sanitize_next_under_base_path() {
+ assert_eq!(
+ sanitize_next(Some("/wiki/web"), "/wiki/web"),
+ "/wiki/web"
+ );
+ assert_eq!(
+ sanitize_next(Some("/wiki/web/w/a"), "/wiki/web"),
+ "/wiki/web/w/a"
+ );
+ assert_eq!(sanitize_next(Some("/web"), "/wiki/web"), "/wiki/web");
+ }
+
+ #[test]
+ fn html_auth_config_paths() {
+ let cfg = HtmlAuthRedirectConfig::from_mount("", "/web");
+ assert_eq!(cfg.web_root, "/web");
+ assert_eq!(cfg.login_path, "/web/login");
+ assert_eq!(cfg.change_password_path, "/web/change-password");
+
+ let nested = HtmlAuthRedirectConfig::from_mount("/wiki", "/web");
+ assert_eq!(nested.login_path, "/wiki/web/login");
+
+ let root = HtmlAuthRedirectConfig::from_mount("", "/");
+ assert_eq!(root.web_root, "");
+ assert_eq!(root.login_path, "/login");
+ }
+
+ fn redirect_probe(status: StatusCode) -> Router {
+ let cfg = Arc::new(HtmlAuthRedirectConfig::from_mount("", "/web"));
+ Router::new()
+ .route(
+ "/wiki",
+ get(move || async move { status.into_response() }),
+ )
+ .route(
+ "/api/v1/projects",
+ get(move || async move { StatusCode::UNAUTHORIZED.into_response() }),
+ )
+ .layer(axum::middleware::from_fn_with_state(cfg, html_auth_redirect_mw))
+ }
+
+ #[tokio::test]
+ async fn html_nav_unauthorized_redirects_to_login_with_next() {
+ let resp = redirect_probe(StatusCode::UNAUTHORIZED)
+ .oneshot(
+ Request::builder()
+ .uri("/wiki")
+ .header(header::ACCEPT, "text/html")
+ .header("sec-fetch-dest", "document")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::SEE_OTHER);
+ let location = resp
+ .headers()
+ .get(header::LOCATION)
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or_default();
+ assert!(
+ location.starts_with("/web/login?next="),
+ "expected login redirect, got {location}"
+ );
+ }
+
+ #[tokio::test]
+ async fn html_nav_forbidden_redirects_to_change_password() {
+ let resp = redirect_probe(StatusCode::FORBIDDEN)
+ .oneshot(
+ Request::builder()
+ .uri("/wiki")
+ .header(header::ACCEPT, "text/html")
+ .header("sec-fetch-dest", "document")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::SEE_OTHER);
+ let location = resp
+ .headers()
+ .get(header::LOCATION)
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or_default();
+ assert_eq!(location, "/web/change-password");
+ }
+
+ #[tokio::test]
+ async fn api_v1_stays_json_even_for_html_navigation() {
+ let resp = redirect_probe(StatusCode::UNAUTHORIZED)
+ .oneshot(
+ Request::builder()
+ .uri("/api/v1/projects")
+ .header(header::ACCEPT, "text/html")
+ .header("sec-fetch-dest", "document")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+ assert!(resp.headers().get(header::LOCATION).is_none());
+ }
+}
diff --git a/crates/ai-memory-web/src/lib.rs b/crates/ai-memory-web/src/lib.rs
index aa0e3de7..6e41e207 100644
--- a/crates/ai-memory-web/src/lib.rs
+++ b/crates/ai-memory-web/src/lib.rs
@@ -12,7 +12,8 @@
//! - `GET /w/:workspace/:project` → page tree + recent activity
//! - `GET /w/:workspace/:project/p/*path` → rendered markdown + metadata
//! - `GET /search?q=…` → FTS5 hit list
-//! - `GET /static/*` → embedded CSS + logo
+//! - `GET /login` / `GET /change-password` → public human-auth HTML forms
+//! - `GET /static/*` → embedded CSS + logo (public)
//!
//! The companion `api_router` exposes the same read-only data as JSON
//! for custom frontends. It intentionally does not expose write/admin
@@ -27,12 +28,14 @@ use ai_memory_store::ReaderPool;
use ai_memory_wiki::Wiki;
use axum::Router;
+mod html_auth;
mod markdown;
pub mod mount;
mod routes;
mod state;
mod templates;
+pub use html_auth::{HtmlAuthRedirectConfig, html_auth_redirect_mw, sanitize_next};
pub use mount::{
SplitWebRouters, WebMountSpec, inject_base_href, inject_base_path_meta, normalize_prefix,
split_web_routers, web_base_href,
diff --git a/crates/ai-memory-web/src/mount.rs b/crates/ai-memory-web/src/mount.rs
index 76a2d086..88f33893 100644
--- a/crates/ai-memory-web/src/mount.rs
+++ b/crates/ai-memory-web/src/mount.rs
@@ -302,6 +302,9 @@ pub struct SplitWebRouters {
pub public: axum::Router,
/// `/api/v1` plus the builtin wiki when that is the chosen UI.
pub protected: axum::Router,
+ /// Builtin login / change-password redirect targets. `None` when web is
+ /// disabled or a custom SPA is mounted (no builtin auth pages).
+ pub html_auth: Option<Arc<crate::HtmlAuthRedirectConfig>>,
}
/// Split the web surfaces so the host can attach different auth layers.
@@ -318,6 +321,7 @@ pub fn split_web_routers(
return Ok(SplitWebRouters {
public: axum::Router::new(),
protected: axum::Router::new(),
+ html_auth: None,
});
}
let api = build_api_router(&reader, &wiki, spec.cors_origins);
@@ -336,11 +340,35 @@ pub fn split_web_routers(
return Ok(SplitWebRouters {
public,
protected: protected_api,
+ html_auth: None,
});
}
+ let auth_cfg = Arc::new(crate::HtmlAuthRedirectConfig::from_mount(
+ spec.base_path,
+ spec.web_slug,
+ ));
+ let browser_inject = Arc::new(WebInjectState {
+ base_href: spec.base_href.to_string(),
+ base_path: spec.base_path.to_string(),
+ login_path: auth_cfg.login_path.clone(),
+ });
Ok(SplitWebRouters {
- public: axum::Router::new(),
- protected: mount_builtin_browser(protected_api, reader, wiki, &slug, spec.base_href, mount),
+ public: mount_builtin_public(
+ auth_cfg.clone(),
+ &slug,
+ spec.base_href,
+ spec.base_path,
+ mount,
+ ),
+ protected: mount_builtin_browser(
+ protected_api,
+ reader,
+ wiki,
+ &slug,
+ mount,
+ browser_inject,
+ ),
+ html_auth: Some(auth_cfg),
})
}
@@ -430,6 +458,30 @@ fn mount_custom_spa(
})
}
+/// Mount public builtin auth pages + static assets at `slug`.
+fn mount_builtin_public(
+ auth_cfg: Arc<crate::HtmlAuthRedirectConfig>,
+ slug: &str,
+ base_href: &str,
+ base_path: &str,
+ mount: &str,
+) -> axum::Router {
+ let inject = Arc::new(WebInjectState {
+ base_href: base_href.to_string(),
+ base_path: base_path.to_string(),
+ login_path: auth_cfg.login_path.clone(),
+ });
+ let public = crate::routes::build_public_auth(auth_cfg).layer(
+ axum::middleware::from_fn_with_state(inject, inject_web_base_href),
+ );
+ info!(mount, base_href, "builtin public auth pages mounted");
+ if slug.is_empty() {
+ public
+ } else {
+ axum::Router::new().nest(slug, public)
+ }
+}
+
/// Mount the built-in server-rendered wiki browser at `slug` with
/// `<base href>` injection middleware. When `slug` is non-empty also
/// register the trailing-slash → canonical redirect, preserving any
@@ -439,15 +491,16 @@ fn mount_builtin_browser(
reader: ReaderPool,
wiki: Wiki,
slug: &str,
- base_href: &str,
mount: &str,
+ inject: Arc<WebInjectState>,
) -> axum::Router {
// The built-in browser emits RELATIVE asset/link URLs (`static/…`,
// `w/…`, `search`, `.`). Inject a `<base href>` into every HTML
// response so they resolve under `{base_path}{web_slug}/` — the
// same anchoring the custom SPA gets via its injected index.
+ let base_href = inject.base_href.clone();
let web_router = crate::router(reader, wiki).layer(axum::middleware::from_fn_with_state(
- Arc::new(base_href.to_string()),
+ inject,
inject_web_base_href,
));
info!(mount, base_href, "read-only wiki browser mounted");
@@ -518,12 +571,20 @@ fn custom_spa_router(dir: std::path::PathBuf, injected_index: String) -> axum::R
.route_service("/{*path}", assets)
}
-/// Response middleware: inject `<base href>` into `text/html` responses from
-/// the built-in server-rendered web browser, so its relative URLs resolve
-/// under the configured `{base_path}{web_slug}` prefix. Non-HTML responses
-/// (static assets, redirects) pass through untouched.
+/// Values injected into every builtin HTML response.
+struct WebInjectState {
+ base_href: String,
+ base_path: String,
+ login_path: String,
+}
+
+/// Response middleware: inject `<base href>` plus auth meta tags into
+/// `text/html` responses from the built-in browser / auth pages, so
+/// relative URLs and logout/login fetch paths resolve under the
+/// configured prefix. Non-HTML responses (static assets, redirects)
+/// pass through untouched.
async fn inject_web_base_href(
- State(base_href): State<Arc<String>>,
+ State(inject): State<Arc<WebInjectState>>,
req: Request<Body>,
next: Next,
) -> Response {
@@ -554,7 +615,15 @@ async fn inject_web_base_href(
};
match std::str::from_utf8(&bytes) {
Ok(html) => {
- let injected = inject_base_href(html, &base_href);
+ let with_base = inject_base_href(html, &inject.base_href);
+ let with_path = inject_base_path_meta(&with_base, &inject.base_path);
+ let injected = inject_into_head(
+ &with_path,
+ &format!(
+ "<meta name=\"ai-memory-login-path\" content=\"{}\">",
+ escape_attr(&inject.login_path)
+ ),
+ );
// Stale length from the pre-injection body; let hyper recompute.
parts.headers.remove(header::CONTENT_LENGTH);
Response::from_parts(parts, Body::from(injected))
diff --git a/crates/ai-memory-web/src/routes/login.rs b/crates/ai-memory-web/src/routes/login.rs
new file mode 100644
index 00000000..ea6eef59
--- /dev/null
+++ b/crates/ai-memory-web/src/routes/login.rs
@@ -0,0 +1,49 @@
+//! Public builtin auth pages (`/login`, `/change-password`).
+
+use std::sync::Arc;
+
+use askama::Template;
+use axum::extract::{Query, State};
+use axum::response::{Html, IntoResponse, Response};
+use serde::Deserialize;
+
+use crate::html_auth::{HtmlAuthRedirectConfig, sanitize_next};
+use crate::templates::{ChangePasswordView, LoginView};
+
+#[derive(Debug, Deserialize)]
+pub(crate) struct NextQuery {
+ #[serde(default)]
+ next: Option<String>,
+}
+
+pub(crate) async fn login(
+ State(cfg): State<Arc<HtmlAuthRedirectConfig>>,
+ Query(q): Query<NextQuery>,
+) -> Response {
+ let next = sanitize_next(q.next.as_deref(), &cfg.web_root);
+ let view = LoginView {
+ next,
+ change_password_href: cfg.change_password_path.clone(),
+ };
+ render(view)
+}
+
+pub(crate) async fn change_password(
+ State(cfg): State<Arc<HtmlAuthRedirectConfig>>,
+ Query(q): Query<NextQuery>,
+) -> Response {
+ let next = sanitize_next(q.next.as_deref(), &cfg.web_root);
+ let view = ChangePasswordView { next };
+ render(view)
+}
+
+fn render(view: impl Template) -> Response {
+ match view.render() {
+ Ok(body) => Html(body).into_response(),
+ Err(_) => (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "template render error\n",
+ )
+ .into_response(),
+ }
+}
diff --git a/crates/ai-memory-web/src/routes/mod.rs b/crates/ai-memory-web/src/routes/mod.rs
index 9f0ab677..4eca0872 100644
--- a/crates/ai-memory-web/src/routes/mod.rs
+++ b/crates/ai-memory-web/src/routes/mod.rs
@@ -5,25 +5,38 @@ use std::sync::Arc;
use axum::Router;
use axum::routing::get;
+use crate::html_auth::HtmlAuthRedirectConfig;
use crate::state::WebState;
mod api;
mod index;
+mod login;
mod page;
mod project;
mod search;
mod statics;
-/// Build the read-only web router from a shared [`WebState`].
+/// Build the read-only wiki page router (no static assets — those are public).
pub(crate) fn build(state: Arc<WebState>) -> Router {
Router::new()
.route("/", get(index::handler))
.route("/w/{workspace}/{project}", get(project::handler))
.route("/w/{workspace}/{project}/p/{*path}", get(page::handler))
.route("/search", get(search::handler))
+ .with_state(state)
+}
+
+/// Public builtin surface: login, change-password, and static assets.
+///
+/// Statics stay public so the login form can load CSS/logo without a
+/// session; wiki pages remain behind dual-auth on the protected router.
+pub(crate) fn build_public_auth(cfg: Arc<HtmlAuthRedirectConfig>) -> Router {
+ Router::new()
+ .route("/login", get(login::login))
+ .route("/change-password", get(login::change_password))
.route("/static/tailwind.css", get(statics::tailwind_css))
.route("/static/logo.png", get(statics::logo))
- .with_state(state)
+ .with_state(cfg)
}
/// Build the read-only JSON API router from a shared [`WebState`].
diff --git a/crates/ai-memory-web/src/templates.rs b/crates/ai-memory-web/src/templates.rs
index 9e20726d..9f4ea504 100644
--- a/crates/ai-memory-web/src/templates.rs
+++ b/crates/ai-memory-web/src/templates.rs
@@ -288,6 +288,27 @@ pub(crate) struct SearchView {
#[template(path = "not_found.html")]
pub(crate) struct NotFoundView {}
+// ---------------------------------------------------------------------------
+// login.html / change_password.html
+// ---------------------------------------------------------------------------
+
+/// View-model for `GET /login` (public builtin auth page).
+#[derive(Template)]
+#[template(path = "login.html")]
+pub(crate) struct LoginView {
+ /// Sanitised post-login redirect target (absolute path under the wiki root).
+ pub next: String,
+ /// Absolute path to the change-password page (for `must_change_password`).
+ pub change_password_href: String,
+}
+
+/// View-model for `GET /change-password` (public builtin auth page).
+#[derive(Template)]
+#[template(path = "change_password.html")]
+pub(crate) struct ChangePasswordView {
+ /// Sanitised post-change redirect target (absolute path under the wiki root).
+ pub next: String,
+}
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ai-memory-web/templates/_js_cookie.html b/crates/ai-memory-web/templates/_js_cookie.html
new file mode 100644
index 00000000..38148406
--- /dev/null
+++ b/crates/ai-memory-web/templates/_js_cookie.html
@@ -0,0 +1,8 @@
+function cookie(name) {
+ var prefix = encodeURIComponent(name) + "=";
+ return document.cookie
+ .split(";")
+ .map(function (v) { return v.trim(); })
+ .find(function (v) { return v.indexOf(prefix) === 0; })
+ ?.slice(prefix.length);
+}
diff --git a/crates/ai-memory-web/templates/base.html b/crates/ai-memory-web/templates/base.html
index 24fc8a64..74135c38 100644
--- a/crates/ai-memory-web/templates/base.html
+++ b/crates/ai-memory-web/templates/base.html
@@ -15,7 +15,8 @@
<span class="font-semibold text-slate-800 dark:text-slate-100 text-sm hidden sm:inline">ai-memory</span>
</a>
<div class="flex-1"></div>
- <form action="search" method="get" class="flex items-center">
+ {% block header_actions %}
+ <form action="search" method="get" class="flex items-center gap-2">
<input
name="q"
type="search"
@@ -23,6 +24,37 @@
class="w-40 sm:w-64 rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-1.5 text-sm placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
</form>
+ <button
+ type="button"
+ id="ai-memory-logout"
+ class="text-sm font-medium text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400"
+ >Log out</button>
+ <script>
+ (function () {
+ var btn = document.getElementById("ai-memory-logout");
+ if (!btn) return;
+ {% include "_js_cookie.html" %}
+ btn.addEventListener("click", function () {
+ var basePath = document
+ .querySelector('meta[name="ai-memory-base-path"]')
+ ?.getAttribute("content") || "";
+ var loginHref = document
+ .querySelector('meta[name="ai-memory-login-path"]')
+ ?.getAttribute("content") || (basePath + "/web/login");
+ fetch(basePath + "/auth/logout", {
+ method: "POST",
+ credentials: "include",
+ headers: {
+ "Accept": "application/json",
+ "X-CSRF-Token": decodeURIComponent(cookie("ai_memory_csrf") || "")
+ }
+ }).finally(function () {
+ location.assign(loginHref);
+ });
+ });
+ })();
+ </script>
+ {% endblock %}
</div>
</header>
diff --git a/crates/ai-memory-web/templates/change_password.html b/crates/ai-memory-web/templates/change_password.html
new file mode 100644
index 00000000..82b59d0e
--- /dev/null
+++ b/crates/ai-memory-web/templates/change_password.html
@@ -0,0 +1,99 @@
+{% extends "base.html" %}
+
+{% block title %}Change password — ai-memory{% endblock %}
+
+{% block header_actions %}{% endblock %}
+
+{% block content %}
+<div class="max-w-md">
+ <h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100">Change password</h1>
+ <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">You must set a new password before using the wiki.</p>
+
+ <p id="auth-error" class="mt-4 hidden text-sm text-amber-800 dark:text-amber-300" role="alert"></p>
+
+ <form id="change-password-form" class="mt-4 space-y-3" autocomplete="on" data-next="{{ next }}">
+ <div>
+ <label for="current_password" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Current password</label>
+ <input
+ id="current_password"
+ name="current_password"
+ type="password"
+ autocomplete="current-password"
+ required
+ class="w-full rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-2 text-sm placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
+ >
+ </div>
+ <div>
+ <label for="new_password" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">New password</label>
+ <input
+ id="new_password"
+ name="new_password"
+ type="password"
+ autocomplete="new-password"
+ required
+ minlength="12"
+ class="w-full rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-2 text-sm placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
+ >
+ </div>
+ <div>
+ <label for="new_password_confirmation" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Confirm new password</label>
+ <input
+ id="new_password_confirmation"
+ name="new_password_confirmation"
+ type="password"
+ autocomplete="new-password"
+ required
+ minlength="12"
+ class="w-full rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-2 text-sm placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
+ >
+ </div>
+ <button type="submit" class="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700">
+ Update password
+ </button>
+ </form>
+</div>
+<script>
+(function () {
+ var form = document.getElementById("change-password-form");
+ var err = document.getElementById("auth-error");
+ var next = form.getAttribute("data-next") || "/";
+ var basePath = document
+ .querySelector('meta[name="ai-memory-base-path"]')
+ ?.getAttribute("content") || "";
+ {% include "_js_cookie.html" %}
+ function showError(msg) {
+ err.textContent = msg;
+ err.classList.remove("hidden");
+ }
+ form.addEventListener("submit", function (e) {
+ e.preventDefault();
+ err.classList.add("hidden");
+ var body = {
+ current_password: document.getElementById("current_password").value,
+ new_password: document.getElementById("new_password").value,
+ new_password_confirmation: document.getElementById("new_password_confirmation").value
+ };
+ fetch(basePath + "/auth/password", {
+ method: "POST",
+ credentials: "include",
+ headers: {
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ "X-CSRF-Token": decodeURIComponent(cookie("ai_memory_csrf") || "")
+ },
+ body: JSON.stringify(body)
+ }).then(function (resp) {
+ return resp.json().catch(function () { return {}; }).then(function (json) {
+ if (!resp.ok) {
+ showError((json && json.error) || ("Password change failed (" + resp.status + ")"));
+ return;
+ }
+ location.assign(next);
+ });
+ }).catch(function () {
+ showError("Network error — try again.");
+ });
+ });
+})();
+</script>
+{% endblock %}
diff --git a/crates/ai-memory-web/templates/login.html b/crates/ai-memory-web/templates/login.html
new file mode 100644
index 00000000..9ad3aaad
--- /dev/null
+++ b/crates/ai-memory-web/templates/login.html
@@ -0,0 +1,87 @@
+{% extends "base.html" %}
+
+{% block title %}Sign in — ai-memory{% endblock %}
+
+{% block header_actions %}{% endblock %}
+
+{% block content %}
+<div class="max-w-md">
+ <h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100">Sign in</h1>
+ <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">Use your ai-memory username and password.</p>
+
+ <p id="auth-error" class="mt-4 hidden text-sm text-amber-800 dark:text-amber-300" role="alert"></p>
+
+ <form id="login-form" class="mt-4 space-y-3" autocomplete="on"
+ data-next="{{ next }}"
+ data-change-password="{{ change_password_href }}">
+ <div>
+ <label for="username" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Username</label>
+ <input
+ id="username"
+ name="username"
+ type="text"
+ autocomplete="username"
+ required
+ class="w-full rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-2 text-sm placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
+ >
+ </div>
+ <div>
+ <label for="password" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Password</label>
+ <input
+ id="password"
+ name="password"
+ type="password"
+ autocomplete="current-password"
+ required
+ class="w-full rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-2 text-sm placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
+ >
+ </div>
+ <button type="submit" class="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700">
+ Sign in
+ </button>
+ </form>
+</div>
+<script>
+(function () {
+ var form = document.getElementById("login-form");
+ var err = document.getElementById("auth-error");
+ var next = form.getAttribute("data-next") || "/";
+ var changePassword = form.getAttribute("data-change-password") || "change-password";
+ var basePath = document
+ .querySelector('meta[name="ai-memory-base-path"]')
+ ?.getAttribute("content") || "";
+ function showError(msg) {
+ err.textContent = msg;
+ err.classList.remove("hidden");
+ }
+ form.addEventListener("submit", function (e) {
+ e.preventDefault();
+ err.classList.add("hidden");
+ var body = {
+ username: document.getElementById("username").value,
+ password: document.getElementById("password").value
+ };
+ fetch(basePath + "/auth/login", {
+ method: "POST",
+ credentials: "include",
+ headers: { "Content-Type": "application/json", "Accept": "application/json" },
+ body: JSON.stringify(body)
+ }).then(function (resp) {
+ return resp.json().catch(function () { return {}; }).then(function (json) {
+ if (!resp.ok) {
+ showError((json && json.error) || ("Sign in failed (" + resp.status + ")"));
+ return;
+ }
+ if (json && json.must_change_password) {
+ location.assign(changePassword);
+ return;
+ }
+ location.assign(next);
+ });
+ }).catch(function () {
+ showError("Network error — try again.");
+ });
+ });
+})();
+</script>
+{% endblock %}
diff --git a/docs/frontend-api.md b/docs/frontend-api.md
index 37b3d4ca..0ed27176 100644
--- a/docs/frontend-api.md
+++ b/docs/frontend-api.md
@@ -35,7 +35,12 @@
(DNS-rebinding guard).
The custom SPA shell and its static assets are public so the login screen can
-load. Its data routes remain protected. Start with:
+load. Its data routes remain protected. When `--web-ui-dir` is **absent**, the
+builtin wiki exposes public `GET {web_slug}/login` and
+`GET {web_slug}/change-password` HTML pages that call the same `/auth/*`
+endpoints; navigational browser GETs to protected wiki routes redirect there
+instead of returning bare JSON 401/403. `/api/v1` stays JSON either way. Start
+with:
```http
GET /auth/me
diff --git a/docs/users.md b/docs/users.md
index aa88fec9..ada11cba 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -101,8 +101,11 @@ and actor-proxy bearer without logging the values. Operator runbook:
`/admin/*` and `/api/v1/*` accept a machine Bearer **or** a web session.
Custom SPA HTML at `/web` is public static; the builtin wiki browser stays
-behind auth. Once human auth becomes active, the engine expires the deprecated
-`ai_memory_auth` compatibility cookie.
+behind auth. With human auth active and no session, a browser GET to the
+builtin wiki redirects to `{web_slug}/login` (HTML form → `POST /auth/login`);
+`must_change_password` redirects to `{web_slug}/change-password`. JSON clients
+and `/api/v1` still receive JSON 401/403. Once human auth becomes active, the
+engine expires the deprecated `ai_memory_auth` compatibility cookie.
## Trusted proxy identity