Skip to content

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

Rust

fix(auth): let a browser and the Mac app into a fresh token install

AkitaOnRails25594224fb39
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 83893b95..606a9132 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -350,7 +350,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
server's credential. The Docker wrapper hands a host command (`install-hooks`,
`mcp-bridge`, `run`) the token of a server initialized on its volume as an
owner-only file that `install-hooks` copies from the volume, never on a
- command line.
+ command line. With no human accounts the built-in web UI answers a browser
+ with a Basic sign-in prompt instead of redirecting to a login form that
+ could not succeed: any username, and the token file's contents as the
+ password. `ai-memory setup` prints that URL and the file to read, never the
+ token. The macOS menu bar app reads the token from its data dir when none is
+ saved in Settings, so an install it initialized turns green without pasting
+ anything.
- Changed `ai-memory-wikisync` files to carry a small frontmatter (`title`,
plus `tags`, `pinned` and a non-default `tier` when set) above the body,
so metadata survives a round trip. The first run after upgrading rewrites
diff --git a/companions/ai-memory-macos/Sources/AIMemoryMenu/AppModel.swift b/companions/ai-memory-macos/Sources/AIMemoryMenu/AppModel.swift
index 121a6c46..aaf643ac 100644
--- a/companions/ai-memory-macos/Sources/AIMemoryMenu/AppModel.swift
+++ b/companions/ai-memory-macos/Sources/AIMemoryMenu/AppModel.swift
@@ -15,6 +15,8 @@ final class AppModel {
var isBusy = false
var runtimeMissing = false
var tokenConfigured = false
+ /// `init` wrote a bearer into the data dir; used when Settings has none.
+ var dataDirTokenPresent = false
var lastHTTPStatus: Int?
@ObservationIgnored private var tokenStore: any TokenStore
@@ -34,6 +36,7 @@ final class AppModel {
self.tokenStore = tokenStore
self.runner = runner
self.tokenConfigured = tokenStore.read()?.isEmpty == false
+ self.dataDirTokenPresent = DataDirToken.read(dataDir: settings.resolvedDataDir) != nil
startPolling()
}
@@ -70,6 +73,10 @@ final class AppModel {
report != nil
}
+ private var effectiveToken: String? {
+ DataDirToken.effective(saved: tokenStore.read(), dataDir: dataDir)
+ }
+
var dataDir: URL {
settings.resolvedDataDir
}
@@ -99,7 +106,7 @@ final class AppModel {
launchd = controller.state()
lastHTTPStatus = nil
do {
- report = try await health.fetch(baseURL: settings.serverURL, token: tokenStore.read())
+ report = try await health.fetch(baseURL: settings.serverURL, token: effectiveToken)
fetchFailed = false
lastError = nil
} catch {
@@ -129,6 +136,7 @@ final class AppModel {
}
runtimeMissing = RuntimeLayout.resolve() == nil
tokenConfigured = tokenStore.read()?.isEmpty == false
+ dataDirTokenPresent = DataDirToken.read(dataDir: dataDir) != nil
}
func installAndStart() async {
@@ -207,7 +215,7 @@ final class AppModel {
let runtime = try self.requireRuntime()
let result = try BundledCLI(runtime: runtime, runner: self.runner).status(
serverURL: self.settings.serverURL,
- token: self.tokenStore.read(),
+ token: self.effectiveToken,
dataDir: self.settings.dataDirOverride
)
self.statusOutput = result.combinedOutput
diff --git a/companions/ai-memory-macos/Sources/AIMemoryMenu/SettingsView.swift b/companions/ai-memory-macos/Sources/AIMemoryMenu/SettingsView.swift
index 690fa0d3..0effb3bb 100644
--- a/companions/ai-memory-macos/Sources/AIMemoryMenu/SettingsView.swift
+++ b/companions/ai-memory-macos/Sources/AIMemoryMenu/SettingsView.swift
@@ -18,7 +18,11 @@ struct SettingsView: View {
.onChange(of: serverURL) { _, _ in scheduleSave() }
.onSubmit { persist() }
SecureField(
- model.tokenConfigured ? "Bearer token (saved in Keychain)" : "Bearer token (optional)",
+ model.tokenConfigured
+ ? "Bearer token (saved in Keychain)"
+ : model.dataDirTokenPresent
+ ? "Bearer token (using auth-tokens/default)"
+ : "Bearer token (optional)",
text: $token
)
.onChange(of: token) { _, _ in scheduleSave() }
diff --git a/companions/ai-memory-macos/Sources/AIMemoryMenuCore/TokenStore.swift b/companions/ai-memory-macos/Sources/AIMemoryMenuCore/TokenStore.swift
index 5a7efd48..c954eb49 100644
--- a/companions/ai-memory-macos/Sources/AIMemoryMenuCore/TokenStore.swift
+++ b/companions/ai-memory-macos/Sources/AIMemoryMenuCore/TokenStore.swift
@@ -104,3 +104,31 @@ public struct KeychainTokenStore: TokenStore, Sendable {
public enum KeychainError: Error, Equatable, Sendable {
case unhandled(OSStatus)
}
+
+/// The root bearer `ai-memory init` writes on a fresh data dir
+/// (`<data_dir>/auth-tokens/default`, owner-only). The app reads it when the
+/// Keychain holds no token, so an install it initialized is authorized
+/// without pasting anything; a token saved in Settings still wins.
+public enum DataDirToken {
+ public static func path(dataDir: URL) -> URL {
+ dataDir.appending(path: "auth-tokens/default")
+ }
+
+ public static func read(dataDir: URL, fileManager: FileManager = .default) -> String? {
+ guard let data = fileManager.contents(atPath: path(dataDir: dataDir).path),
+ let text = String(data: data, encoding: .utf8)
+ else {
+ return nil
+ }
+ let token = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ return token.isEmpty ? nil : token
+ }
+
+ /// The Keychain token when one is saved, else the data dir's token file.
+ public static func effective(saved: String?, dataDir: URL, fileManager: FileManager = .default) -> String? {
+ if let saved, !saved.isEmpty {
+ return saved
+ }
+ return read(dataDir: dataDir, fileManager: fileManager)
+ }
+}
diff --git a/companions/ai-memory-macos/Tests/AIMemoryMenuTests/DataDirTokenTests.swift b/companions/ai-memory-macos/Tests/AIMemoryMenuTests/DataDirTokenTests.swift
new file mode 100644
index 00000000..724f9ebd
--- /dev/null
+++ b/companions/ai-memory-macos/Tests/AIMemoryMenuTests/DataDirTokenTests.swift
@@ -0,0 +1,43 @@
+import Foundation
+import Testing
+@testable import AIMemoryMenuCore
+
+struct DataDirTokenTests {
+ private func makeDataDir() throws -> URL {
+ let dir = FileManager.default.temporaryDirectory
+ .appending(path: "ai-memory-menu-token-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(
+ at: dir.appending(path: "auth-tokens"),
+ withIntermediateDirectories: true
+ )
+ return dir
+ }
+
+ @Test func readsTheTokenInitWroteAndTrimsIt() throws {
+ let dir = try makeDataDir()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ try Data("aim-root-test-token\n".utf8).write(to: DataDirToken.path(dataDir: dir))
+
+ #expect(DataDirToken.read(dataDir: dir) == "aim-root-test-token")
+ #expect(DataDirToken.effective(saved: nil, dataDir: dir) == "aim-root-test-token")
+ #expect(DataDirToken.effective(saved: "", dataDir: dir) == "aim-root-test-token")
+ }
+
+ @Test func aSavedTokenWinsOverTheFile() throws {
+ let dir = try makeDataDir()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ try Data("from-file".utf8).write(to: DataDirToken.path(dataDir: dir))
+
+ #expect(DataDirToken.effective(saved: "from-keychain", dataDir: dir) == "from-keychain")
+ }
+
+ @Test func aMissingOrBlankFileGivesNoToken() throws {
+ let dir = try makeDataDir()
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ #expect(DataDirToken.read(dataDir: dir) == nil)
+ try Data(" \n".utf8).write(to: DataDirToken.path(dataDir: dir))
+ #expect(DataDirToken.read(dataDir: dir) == nil)
+ #expect(DataDirToken.effective(saved: nil, dataDir: dir) == nil)
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 55bcd2d5..02c8a1c8 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -6111,8 +6111,10 @@ mod tests {
.unwrap();
assert_eq!(json_401.status(), StatusCode::UNAUTHORIZED);
- // Browser navigations redirect to the public login page.
- let html_redir = router
+ // With a bearer and no human accounts there is no login form that
+ // could succeed, so a browser navigation gets the Basic challenge,
+ // not a redirect to the login page.
+ let html_challenge = router
.clone()
.oneshot(
Request::builder()
@@ -6125,16 +6127,33 @@ mod tests {
)
.await
.unwrap();
- assert_eq!(html_redir.status(), StatusCode::SEE_OTHER);
- let location = html_redir
+ assert_eq!(html_challenge.status(), StatusCode::UNAUTHORIZED);
+ assert!(html_challenge.headers().get(header::LOCATION).is_none());
+ let challenge = html_challenge
.headers()
- .get(header::LOCATION)
+ .get(header::WWW_AUTHENTICATE)
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
- assert!(
- location.starts_with("/web/login?next="),
- "expected login redirect, got {location}"
- );
+ assert!(challenge.starts_with("Basic "), "challenge: {challenge}");
+
+ // The token as the Basic password opens the wiki.
+ use base64::Engine as _;
+ let basic = base64::engine::general_purpose::STANDARD.encode("root:secret");
+ let signed_in = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/web")
+ .header("Host", "localhost")
+ .header("Accept", "text/html")
+ .header("sec-fetch-dest", "document")
+ .header("Authorization", format!("Basic {basic}"))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(signed_in.status(), StatusCode::OK);
// Login HTML is public (no auth).
let login = router
diff --git a/crates/ai-memory-cli/src/commands/setup.rs b/crates/ai-memory-cli/src/commands/setup.rs
index f36c0138..6d193aa8 100644
--- a/crates/ai-memory-cli/src/commands/setup.rs
+++ b/crates/ai-memory-cli/src/commands/setup.rs
@@ -406,6 +406,9 @@ async fn execute(
} else {
println!("auth: bearer token (owner-only file; never printed)");
}
+ if let Some(hint) = web_sign_in_hint(&config, &endpoint) {
+ println!("{hint}");
+ }
if problems.is_empty() {
println!(
"ai-memory is set up. Restart your agents so they load the new hooks and MCP entry."
@@ -421,6 +424,20 @@ async fn execute(
)
}
+/// How a browser signs in to the web UI on a token-file install. With no
+/// human accounts the server answers `/web` with a Basic challenge, and the
+/// token file's contents are the password. The token itself is never printed.
+fn web_sign_in_hint(config: &Config, endpoint: &ServerEndpoint) -> Option<String> {
+ let file = config.auth.token_file.as_ref().filter(|file| file.loaded)?;
+ Some(format!(
+ "web UI: {} (the service runs with --enable-web); when the browser asks \
+ for a username and password, use any username and the contents of {} \
+ as the password",
+ endpoint.build_url("/web"),
+ file.path.display()
+ ))
+}
+
async fn wait_until_reachable(endpoint: &ServerEndpoint, timeout: Duration) -> bool {
let deadline = Instant::now() + timeout;
loop {
@@ -565,6 +582,27 @@ async fn memory_status(config: &Config) -> Result<()> {
mod tests {
use super::*;
+ /// A token-file install learns how to open the web UI: the URL and the
+ /// file to read, never the token. An inline or absent token prints no hint.
+ #[test]
+ fn web_hint_names_the_token_file_and_never_the_token() {
+ let endpoint = ServerEndpoint::from_pair(Some("http://127.0.0.1:49374".to_owned()), None);
+ let mut config = Config::default();
+ assert_eq!(web_sign_in_hint(&config, &endpoint), None);
+
+ config.auth.bearer_token = Some("inline-root-token".to_owned());
+ assert_eq!(web_sign_in_hint(&config, &endpoint), None);
+
+ let file = PathBuf::from("/data/auth-tokens/default");
+ config
+ .auth
+ .adopt_token_file(file.clone(), "file-root-token".to_owned());
+ let hint = web_sign_in_hint(&config, &endpoint).expect("token-file install gets a hint");
+ assert!(hint.contains("http://127.0.0.1:49374/web"), "{hint}");
+ assert!(hint.contains(&file.display().to_string()), "{hint}");
+ assert!(!hint.contains("file-root-token"), "{hint}");
+ }
+
fn spec(home: &Path) -> user_service::ServiceSpec {
user_service::ServiceSpec {
exe: PathBuf::from("/opt/ai-memory/ai-memory"),
diff --git a/crates/ai-memory-web/src/html_auth.rs b/crates/ai-memory-web/src/html_auth.rs
index 004e20fb..43d3dd38 100644
--- a/crates/ai-memory-web/src/html_auth.rs
+++ b/crates/ai-memory-web/src/html_auth.rs
@@ -2,7 +2,9 @@
//!
//! 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.
+//! builtin login / change-password pages instead. `/api/v1` stays JSON, and
+//! a Basic challenge (a bearer-only server with no human accounts) reaches
+//! the browser unchanged.
use std::sync::Arc;
@@ -144,6 +146,12 @@ pub async fn html_auth_redirect_mw(
return resp;
}
match resp.status() {
+ // A server with a bearer token and no human accounts (every fresh
+ // install) has no login form that could succeed, so it answers with
+ // a Basic challenge instead: the browser prompts, and the token from
+ // `auth-tokens/default` signs in as the password. Redirecting that
+ // 401 to the login page would leave the browser with no way in.
+ StatusCode::UNAUTHORIZED if offers_basic_challenge(&resp) => resp,
StatusCode::UNAUTHORIZED => {
let next_q =
urlencoding_encode(&sanitize_next(Some(&full_path_and_query), &cfg.web_root));
@@ -156,6 +164,20 @@ pub async fn html_auth_redirect_mw(
}
}
+fn offers_basic_challenge(resp: &Response) -> bool {
+ resp.headers()
+ .get_all(header::WWW_AUTHENTICATE)
+ .iter()
+ .filter_map(|v| v.to_str().ok())
+ .any(|v| {
+ v.split(',').any(|part| {
+ part.trim_start()
+ .get(..6)
+ .is_some_and(|s| s.eq_ignore_ascii_case("basic "))
+ })
+ })
+}
+
fn is_api_v1_path(path: &str) -> bool {
path == "/api/v1" || path.starts_with("/api/v1/")
}
@@ -286,6 +308,48 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn html_nav_basic_challenge_reaches_the_browser() {
+ let cfg = Arc::new(HtmlAuthRedirectConfig::from_mount("", "/web"));
+ let router = Router::new()
+ .route(
+ "/wiki",
+ get(|| async {
+ (
+ StatusCode::UNAUTHORIZED,
+ [(
+ header::WWW_AUTHENTICATE,
+ "Basic realm=\"ai-memory\", Bearer realm=\"ai-memory\"",
+ )],
+ )
+ .into_response()
+ }),
+ )
+ .layer(axum::middleware::from_fn_with_state(
+ cfg,
+ html_auth_redirect_mw,
+ ));
+ let resp = router
+ .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::UNAUTHORIZED);
+ assert!(resp.headers().get(header::LOCATION).is_none());
+ let challenge = resp
+ .headers()
+ .get(header::WWW_AUTHENTICATE)
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or_default();
+ assert!(challenge.starts_with("Basic "), "challenge: {challenge}");
+ }
+
#[tokio::test]
async fn html_nav_forbidden_redirects_to_change_password() {
let resp = redirect_probe(StatusCode::FORBIDDEN)