Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(mcp): let the bridge read the stored hook key instead of an inline token
Felipe Neves Ricardof59a5b1299dc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ec3ddd56..69ca4849 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,17 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]+### Fixed+- Let `ai-memory mcp-bridge` send the key `install-hooks --apply --auth-token`+ stored in `<data_dir>/auth-token` when no bearer is configured, ahead of the+ loopback root token discovery, so a remote+ client whose hooks hold a native API key wires the MCP bridge without+ copying the key. `install-mcp --apply --auth-token` now stores the key there+ for the Claude Code (`--session-aware`) and Muse bridge entries and leaves+ it out of the harness config, where it outlived a key rotation; existing+ entries keep working. `uninstall --only hooks` keeps the stored key while+ such a bridge entry remains. ([#1490](https://github.com/akitaonrails/ai-memory/issues/1490))+## [3.1.2] - 2026-10-20### Fixeddiff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex 6125900b..5f6b3b3b 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -30,6 +30,7 @@ use crate::commands::render_shared::{bearer_header_value, hook_embedded_exe_path, shell_quote, yaml_single_quote,};use crate::config::{Config, DEFAULT_MCP_URL};+use crate::local_auth::HookCredential;const GEMINI_MCP_TIMEOUT_MS: u64 = 5000;@@ -110,6 +111,7 @@ pub(crate) fn run_with_opencode_dialect(// inferred literal from an old entry is ignored then too, since it would// re-embed a stale credential.let token_file = config.auth.token_file_path();+ let token_given = args.auth_token.is_some();let auth_token = args.auth_token.or_else(|| config.auth.renderable_bearer_token().map(str::to_owned))@@ -136,6 +138,31 @@ pub(crate) fn run_with_opencode_dialect({route_file_token(&mut args, token_file)?;}+ // An explicit `--auth-token` for an entry that runs `mcp-bridge` goes where+ // the hooks keep theirs, `<data_dir>/auth-token`, and the bridge reads it+ // from there when nothing else is configured. Inline in the harness config+ // it would sit outside the data dir's protection and outlive a rotation,+ // the reasons #552 moved the hooks' copy. The entry then names that data+ // dir, so the bridge reads the file the key went into. Only `--apply`+ // stores, as with `install-hooks`: a printed snippet is the operator's to+ // place. The key stays inline, as before, whenever the bridge would not+ // reach it: a bearer this config is configured with would win over it, a+ // different key already stored belongs to the hooks, the store failed, or+ // this is the Docker helper, whose data dir the host-side bridge cannot+ // open.+ let bridge_carries_token = matches!(args.client, McpClient::Muse)+ || (args.client == McpClient::ClaudeCode && args.session_aware);+ if args.apply+ && token_given+ && bridge_carries_token+ && config.auth.configured_bearer_token().is_none()+ && config.runtime_env.host_cwd().is_none()+ && let Some(token) = args.auth_token.as_deref()+ && store_bridge_key(&config.data_dir, token)+ {+ args.auth_token = None;+ args.bridge_data_dir = Some(config.data_dir.clone());+ }validate_args(&args)?;if args.apply {return apply_to_config_file(&args);@@ -208,6 +235,53 @@ fn route_file_token(args: &mut InstallMcpArgs, token_file: &Path) -> Result<()>Ok(())}+/// Store `token` in `<data_dir>/auth-token` for the bridge, the file and+/// format `install-hooks --apply` uses. `false` when the bridge would not read+/// this key from there: a different key is already stored (it belongs to the+/// install's hooks and is left alone), the hooks sign in with OIDC, or the+/// write failed. The caller then keeps the key in the entry.+fn store_bridge_key(data_dir: &Path, token: &str) -> bool {+ // The hooks present an OIDC `auth.json` only while no key is stored, so+ // storing one here would quietly switch them to this key.+ if crate::config::read_hook_auth_token(data_dir).is_none()+ && ai_memory_llm::OidcToken::load(&data_dir.join("auth.json"))+ .ok()+ .flatten()+ .is_some()+ {+ eprintln!(+ "[ai-memory] this install's hooks sign in with OIDC; keeping the --auth-token key \+ in the MCP entry, as before, so they keep doing so"+ );+ return false;+ }+ match crate::local_auth::seed_hook_credential(data_dir, token) {+ Ok(HookCredential::Seeded | HookCredential::Current) => {+ eprintln!(+ "[ai-memory] stored the bridge's key in {}; the MCP entry carries no token",+ crate::config::hook_auth_token_path_in(data_dir).display()+ );+ true+ }+ Ok(HookCredential::KeptOther) => {+ eprintln!(+ "[ai-memory] warning: {} already holds a different key for this install's \+ hooks; keeping the --auth-token key in the MCP entry, as before",+ crate::config::hook_auth_token_path_in(data_dir).display()+ );+ false+ }+ Err(e) => {+ eprintln!(+ "[ai-memory] warning: could not store the key under {} ({e:#}); keeping it in \+ the MCP entry, as before",+ data_dir.display()+ );+ false+ }+ }+}+/// The bare command name, resolved through `PATH`. Inside a container the/// Docker wrapper on the host intercepts `mcp-bridge`, so the entry must name/// the wrapper rather than the container's own binary.@@ -984,6 +1058,20 @@ pub(crate) fn existing_entry_is_session_aware(is_stdio && runs_bridge}+/// True when Claude Code or Muse still holds an ai-memory bridge entry under+/// `name` in its default config file. `install-mcp --apply --auth-token`+/// writes those two without the key, which the bridge then reads from+/// `<data_dir>/auth-token`, so an uninstall that keeps such an entry must keep+/// that file. Unreadable files answer `false`, as for the session-aware check.+pub(crate) fn bridge_entry_remains(name: &str) -> bool {+ existing_entry_is_session_aware(McpClient::ClaudeCode, None, name)+ || mcp_config_path(McpClient::Muse)+ .ok()+ .and_then(|path| existing_entry_endpoint(McpClient::Muse, &path, name).ok())+ .flatten()+ .is_some()+}+/// Mutate the resolved client config file in place. Idempotent —/// re-runs that produce the same content are reported as no-op.fn apply_to_config_file(args: &InstallMcpArgs) -> Result<()> {@@ -1575,10 +1663,12 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {if args.session_aware {entry.insert("type".into(), json!("stdio"));entry.insert("command".into(), json!(bridge_command()));- entry.insert(- "args".into(),- json!(["mcp-bridge", "--server-url", base_url]),- );+ let mut argv = vec![json!("mcp-bridge"), json!("--server-url"), json!(base_url)];+ if let Some(data_dir) = &args.bridge_data_dir {+ argv.push(json!("--data-dir"));+ argv.push(json!(data_dir.to_string_lossy()));+ }+ entry.insert("args".into(), serde_json::Value::Array(argv));if let Some(token) = &args.auth_token {entry.insert("env".into(), json!({"AI_MEMORY_AUTH_TOKEN": token}));}@@ -1829,7 +1919,8 @@ fn build_mcp_entry_zcode(args: &InstallMcpArgs) -> Result<serde_json::Value> {/// the install's data dir (`--data-dir`, when [`InstallMcpArgs::bridge_data_dir`]/// is set) and the bridge reads its bearer from that install's config/// (`[auth].bearer_token_file`) at launch; a token given explicitly is-/// passed in `env` the way Claude Code's session-aware entry carries it. `mode` is written+/// passed in `env` the way Claude Code's session-aware entry carries it,+/// unless `--apply` stored it in that data dir for the bridge. `mode` is written/// explicitly because Muse defaults it to `required`, which aborts the whole/// run when the server cannot start; ai-memory augments a session and must/// never gate it.@@ -4296,6 +4387,102 @@ mod tests {assert!(!text.contains(FILE_TOKEN), "{text}");}+ /// An explicit `--auth-token` for an entry that runs the bridge is stored+ /// in `<data_dir>/auth-token`, where the bridge reads it, and the entry+ /// names that data dir instead of carrying the key. Controls, each of+ /// which keeps the key inline as before and stores nothing new: the print+ /// path, a bearer the config already resolves (it would win over the+ /// stored key), a different key already stored for the hooks, hooks that+ /// sign in with OIDC, the Docker helper, and an HTTP entry, whose literal+ /// header is documented.+ #[test]+ fn an_explicit_key_for_a_bridge_is_stored_instead_of_written_inline() {+ const KEY: &str = "aim_explicit_key";+ let tmp = tempfile::tempdir().unwrap();+ let config_in = |name: &str| Config {+ data_dir: tmp.path().join(name),+ ..Config::default()+ };+ let install = |config: &Config, client: McpClient, apply: bool| -> String {+ let file = config.data_dir.with_extension(format!("{client:?}.json"));+ let mut args = args_for(client);+ args.apply = apply;+ args.config_file = Some(file.clone());+ args.session_aware = client == McpClient::ClaudeCode;+ args.auth_token = Some(KEY.into());+ run_with_opencode_dialect(config, args, None).unwrap();+ std::fs::read_to_string(&file).unwrap_or_default()+ };+ let stored = |config: &Config| crate::config::read_hook_auth_token(&config.data_dir);++ for client in [McpClient::ClaudeCode, McpClient::Muse] {+ let config = config_in(&format!("stored-{client:?}"));+ let text = install(&config, client, true);+ assert!(+ !text.contains(KEY),+ "{client:?} entry still carries the key: {text}"+ );+ assert!(!text.contains("AI_MEMORY_AUTH_TOKEN"), "{client:?}: {text}");+ assert!(text.contains("--data-dir"), "{client:?}: {text}");+ assert!(+ text.contains(config.data_dir.to_string_lossy().as_ref()),+ "{client:?} entry must name the dir the key went into: {text}"+ );+ assert_eq!(stored(&config).as_deref(), Some(KEY), "{client:?}");+ // The shell hooks read the header file of the same pair.+ assert_eq!(+ std::fs::read_to_string(crate::config::hook_auth_header_path_in(&config.data_dir))+ .unwrap(),+ format!("Authorization: Bearer {KEY}\n")+ );+ }++ let printed = config_in("printed");+ install(&printed, McpClient::ClaudeCode, false);+ assert_eq!(+ stored(&printed),+ None,+ "a printed snippet must store nothing"+ );++ let mut configured = config_in("configured");+ configured.auth.bearer_token = Some("configured-bearer".into());+ assert!(install(&configured, McpClient::ClaudeCode, true).contains(KEY));+ assert_eq!(stored(&configured), None);++ let other = config_in("other");+ crate::config::store_hook_auth_token(&other.data_dir, "aim_hooks_key").unwrap();+ assert!(install(&other, McpClient::ClaudeCode, true).contains(KEY));+ assert_eq!(stored(&other).as_deref(), Some("aim_hooks_key"));++ let oidc = config_in("oidc");+ let response = ai_memory_llm::OidcTokenResponse {+ access_token: "oidc-access".into(),+ refresh_token: Some("oidc-refresh".into()),+ expires_in: None,+ };+ std::fs::create_dir_all(&oidc.data_dir).unwrap();+ ai_memory_llm::OidcToken::from_token_response(&response, "iss", "cid", "ep", None)+ .unwrap()+ .save(&oidc.data_dir.join("auth.json"))+ .unwrap();+ assert!(install(&oidc, McpClient::ClaudeCode, true).contains(KEY));+ assert_eq!(+ stored(&oidc),+ None,+ "OIDC hooks must not be switched to the key"+ );++ let mut docker = config_in("docker");+ docker.runtime_env = crate::config::RuntimeEnv::with_host_cwd_for_tests("/host/repo");+ assert!(install(&docker, McpClient::ClaudeCode, true).contains(KEY));+ assert_eq!(stored(&docker), None);++ let http = config_in("http");+ assert!(install(&http, McpClient::Cursor, true).contains(&format!("Bearer {KEY}")));+ assert_eq!(stored(&http), None);+ }+#[test]fn mcp_server_url_defaults_to_configured_server_url() {let config = Config {diff --git a/crates/ai-memory-cli/src/commands/mcp_bridge.rs b/crates/ai-memory-cli/src/commands/mcp_bridge.rsindex bd0c7df1..574b7386 100644--- a/crates/ai-memory-cli/src/commands/mcp_bridge.rs+++ b/crates/ai-memory-cli/src/commands/mcp_bridge.rs@@ -21,10 +21,20 @@//! that session's id, and forwarding it would steer this client's unscoped//! calls through another session's active-project pointer.//!-//! Either way the bridge authenticates with the bearer `Config::load`-//! resolved (`AI_MEMORY_AUTH_TOKEN`, `[auth].bearer_token`, or the file-//! `[auth].bearer_token_file` names), so a harness config that launches it-//! carries no token and no token reaches its command line.+//! Either way the bridge authenticates with a configured bearer+//! (`AI_MEMORY_AUTH_TOKEN`, `[auth].bearer_token`, or the file+//! `[auth].bearer_token_file` names). With none of those, it sends the key+//! `install-hooks --apply --auth-token` stored for this install's hooks in+//! `<data_dir>/auth-token`, so a client whose hooks hold a native API key+//! reaches the server as the same user, and only then the root token+//! `Config::load` discovers on a loopback install, so a host running both the+//! server and a client never sends root over a stored user key. That fallback+//! is the bridge's alone:+//! `Config::load` never reads the file, so `serve` neither requires nor+//! accepts the key because it is stored there. `install-mcp --apply` relies on+//! it to write an entry without the key when the key was given explicitly; an+//! entry written before that, or by the print path, still carries it in+//! `AI_MEMORY_AUTH_TOKEN`, which wins.use std::collections::HashMap;@@ -250,6 +260,29 @@ fn bridge_base_url<'a>(flag: Option<&'a str>, configured: &'a str) -> &'a str {.unwrap_or(configured)}+/// The bearer the bridge sends: a configured one (`AI_MEMORY_AUTH_TOKEN`,+/// `[auth].bearer_token`, `[auth].bearer_token_file`), else the key stored for+/// this install's hooks in `<data_dir>/auth-token`, else the root token+/// `Config::load` discovered on a loopback install. The stored key outranks+/// discovery so a host that runs the server and a client sends the user's key+/// rather than root.+fn bridge_bearer(config: &Config) -> Option<String> {+ let usable = |token: &str| !token.trim().is_empty();+ config+ .auth+ .configured_bearer_token()+ .filter(|token| usable(token))+ .map(str::to_owned)+ .or_else(|| crate::config::read_hook_auth_token(&config.data_dir))+ .or_else(|| {+ config+ .auth+ .bearer_token+ .clone()+ .filter(|token| usable(token))+ })+}+/// Run the stdio bridge, session-aware or session-less (see the module docs).////// # Errors@@ -263,10 +296,11 @@ pub async fn run(config: &Config, args: McpBridgeArgs) -> Result<()> {args.server_url.as_deref(),&config.server_url,));+ let bearer = bridge_bearer(config);let transport = StreamableHttpClientTransport::from_config(upstream_config(&server_url,session_id,- config.auth.bearer_token.as_deref(),+ bearer.as_deref(),)?);// Connecting before serving stdio means a refused credential (401) or an@@ -286,11 +320,12 @@ pub async fn run(config: &Config, args: McpBridgeArgs) -> Result<()> {} else {""},- if config.auth.bearer_token.is_some() {+ if bearer.is_some() {""} else {" (sent without a bearer token; the bridge reads it from \- AI_MEMORY_AUTH_TOKEN, [auth].bearer_token or [auth].bearer_token_file)"+ AI_MEMORY_AUTH_TOKEN, [auth].bearer_token, [auth].bearer_token_file \+ or the key `install-hooks --apply --auth-token` stored in the data dir)"})});@@ -615,4 +650,58 @@ mod tests {assert_bridge_round_trip(false).await;assert_bridge_round_trip(true).await;}++ /// The stored hook key is the bridge's last resort: a configured bearer+ /// (env, inline key, token file) outranks it, a blank one does not, and+ /// with neither the bridge sends nothing.+ #[test]+ fn bridge_bearer_puts_the_stored_hook_key_below_a_configured_bearer() {+ let tmp = tempfile::tempdir().unwrap();+ let mut config = Config {+ data_dir: tmp.path().to_path_buf(),+ ..Config::default()+ };+ assert_eq!(bridge_bearer(&config), None);++ crate::config::store_hook_auth_token(tmp.path(), "aim_stored").unwrap();+ assert_eq!(bridge_bearer(&config).as_deref(), Some("aim_stored"));++ config.auth.bearer_token = Some("configured".into());+ assert_eq!(bridge_bearer(&config).as_deref(), Some("configured"));++ config.auth.bearer_token = Some(" ".into());+ assert_eq!(bridge_bearer(&config).as_deref(), Some("aim_stored"));+ }++ /// Adversarial: on a host that runs the server and a client from one data+ /// dir, `Config::load` discovers the root token, and a user's key is+ /// stored for the hooks. The bridge must send the user's key, never root.+ /// Control: without a stored key, discovery still authenticates the bridge.+ #[test]+ fn a_stored_user_key_outranks_the_discovered_root_token() {+ let tmp = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(tmp.path().join("auth-tokens")).unwrap();+ std::fs::write(+ tmp.path().join("auth-tokens").join("default"),+ "root-token\n",+ )+ .unwrap();+ let load = || {+ Config::load_with_runtime_env(+ None,+ Some(tmp.path().to_path_buf()),+ RuntimeEnv::default(),+ )+ .unwrap()+ };++ let discovered = load();+ assert_eq!(discovered.auth.bearer_token.as_deref(), Some("root-token"));+ assert_eq!(bridge_bearer(&discovered).as_deref(), Some("root-token"));++ crate::config::store_hook_auth_token(tmp.path(), "aim_user_key").unwrap();+ let both = load();+ assert_eq!(both.auth.bearer_token.as_deref(), Some("root-token"));+ assert_eq!(bridge_bearer(&both).as_deref(), Some("aim_user_key"));+ }}diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex c2230eeb..2579a02b 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -835,13 +835,21 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {uninstall_plugins(&plugins, &user_service::SystemRunner);- // Removing the hooks removes the only readers of the stored bearer, so- // leaving it on disk would strand a live credential (#552). An uninstall- // that keeps the hooks (`--only mcp|instructions|skills`) keeps it: the- // native hook, the shell hooks and the generated TypeScript integrations- // (the Pi one also bridges MCP) all still read it. Best-effort: an- // unremovable file must not fail a teardown that otherwise succeeded.- if hooks_removed && let Err(error) = crate::config::clear_hook_auth_token(&config.data_dir) {+ // Removing the hooks removes the readers of the stored bearer, so leaving+ // it on disk would strand a live credential (#552). An uninstall that+ // keeps the hooks (`--only mcp|instructions|skills`) keeps it: the native+ // hook, the shell hooks and the generated TypeScript integrations (the Pi+ // one also bridges MCP) all still read it. So does `--only hooks` while a+ // Claude Code or Muse bridge entry remains, since the bridge reads the same+ // file and `install-mcp --apply --auth-token` leaves the key out of those+ // entries. Best-effort: an unremovable file must not fail a teardown that+ // otherwise succeeded.+ let bridge_keeps_key = args.only == Some(crate::cli::UninstallOnly::Hooks)+ && install_mcp::bridge_entry_remains(name.as_deref().unwrap_or("ai-memory"));+ if hooks_removed+ && !bridge_keeps_key+ && let Err(error) = crate::config::clear_hook_auth_token(&config.data_dir)+ {eprintln!("ai-memory uninstall warning: could not remove the stored auth token under {}: {error}",config.data_dir.display()diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex d924a019..c33299e3 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -1120,6 +1120,9 @@ pub(crate) struct ResolvedTokenFile {/// missing or blank leaves [`AuthSettings::bearer_token`] unset, and/// `serve` refuses to start rather than run open.pub(crate) loaded: bool,+ /// Whether [`discover_root_token`] found it rather than the config naming+ /// it, so a credential this install chose can outrank it.+ pub(crate) discovered: bool,}impl AuthSettings {@@ -1144,6 +1147,16 @@ impl AuthSettings {self.token_file.as_ref().map(|file| file.path.as_path())}+ /// The bearer the environment, the inline key or `[auth].bearer_token_file`+ /// supplied, leaving out a root token only [`discover_root_token`] found.+ #[must_use]+ pub(crate) fn configured_bearer_token(&self) -> Option<&str> {+ if self.token_file.as_ref().is_some_and(|file| file.discovered) {+ return None;+ }+ self.bearer_token.as_deref()+ }+/// The configured token file when it could not supply a token.#[must_use]pub(crate) fn missing_token_file(&self) -> Option<&Path> {@@ -1158,7 +1171,11 @@ impl AuthSettings {/// re-renders wiring in the same process.pub(crate) fn adopt_token_file(&mut self, path: PathBuf, token: String) {self.bearer_token = Some(token);- self.token_file = Some(ResolvedTokenFile { path, loaded: true });+ self.token_file = Some(ResolvedTokenFile {+ path,+ loaded: true,+ discovered: false,+ });}}@@ -1205,6 +1222,7 @@ fn apply_bearer_token_file(auth: &mut AuthSettings, ctx: &TokenFileContext<'_>)auth.token_file = Some(ResolvedTokenFile {path,loaded: token.is_some(),+ discovered: false,});auth.bearer_token = token;Ok(())@@ -1243,7 +1261,11 @@ fn discover_root_token(auth: &mut AuthSettings, ctx: &TokenFileContext<'_>) {if profile_named_default {return;}- auth.token_file = Some(ResolvedTokenFile { path, loaded: true });+ auth.token_file = Some(ResolvedTokenFile {+ path,+ loaded: true,+ discovered: true,+ });auth.bearer_token = Some(token);}@@ -3586,6 +3608,41 @@ mod tests {assert!(read_hook_auth_token(&dd).is_none());clear_hook_auth_token(&dd).expect("clearing twice must not error");}++ /// Adversarial: the stored hook key is a client credential, read by the+ /// hooks and, as a last resort, by `mcp-bridge`. `Config::load` must never+ /// adopt it, or `serve` on the same data dir would start requiring that+ /// key and accepting it as its bearer. Control: a key named by+ /// `[auth].bearer_token_file` is adopted.+ #[test]+ fn config_load_never_adopts_the_stored_hook_key() {+ let tmp = TempDir::new().unwrap();+ let dd = tmp.path().join("data");+ store_hook_auth_token(&dd, "aim_hook_key").unwrap();+ let config_path = dd.join("config.toml");+ std::fs::write(&config_path, "bind = \"127.0.0.1:49921\"\n").unwrap();+ let cfg = Config::load_with_runtime_env(+ Some(&config_path),+ Some(dd.clone()),+ RuntimeEnv::default(),+ )+ .unwrap();+ assert_eq!(cfg.auth.bearer_token, None);+ assert!(cfg.auth.token_file_path().is_none());++ std::fs::write(+ &config_path,+ "bind = \"127.0.0.1:49921\"\n[auth]\nbearer_token_file = \"auth-token\"\n",+ )+ .unwrap();+ let cfg = Config::load_with_runtime_env(+ Some(&config_path),+ Some(dd.clone()),+ RuntimeEnv::default(),+ )+ .unwrap();+ assert_eq!(cfg.auth.bearer_token.as_deref(), Some("aim_hook_key"));+ }use super::*;use rstest::rstest;use secrecy::{ExposeSecret, SecretString};diff --git a/crates/ai-memory-cli/tests/suite/removal.rs b/crates/ai-memory-cli/tests/suite/removal.rsindex 84ceb5af..0b5404c0 100644--- a/crates/ai-memory-cli/tests/suite/removal.rs+++ b/crates/ai-memory-cli/tests/suite/removal.rs@@ -2312,6 +2312,57 @@ fn uninstall_keeps_the_hook_bearer_unless_hooks_are_removed() {}}+/// `install-mcp --apply --auth-token` for Claude Code stores the key where the+/// hooks keep theirs and writes the bridge entry without it, so the stored+/// key is the bridge's too: `--only hooks` keeps it while that entry remains,+/// and the full uninstall still removes it.+#[test]+fn an_explicit_bridge_key_is_stored_and_outlives_only_hooks_removal() {+ const KEY: &str = "aim_bridge_key_0123456789";+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();+ let run = |args: &[&str]| {+ let output = command_with_home(home.path())+ .args(args)+ .current_dir(project.path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{args:?}: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ };+ run(&[+ "install-mcp",+ "--client",+ "claude-code",+ "--session-aware",+ "--auth-token",+ KEY,+ "--apply",+ ]);+ run(&["install-hooks", "--agent", "claude-code", "--apply"]);+ let claude = std::fs::read_to_string(home.path().join(".claude.json")).unwrap();+ assert!(+ !claude.contains(KEY),+ "the key stayed in ~/.claude.json: {claude}"+ );+ assert!(claude.contains("mcp-bridge"), "{claude}");+ let stored = home.path().join(".ai-memory-data").join("auth-token");+ assert_eq!(std::fs::read_to_string(&stored).unwrap().trim(), KEY);++ run(&["uninstall", "--only", "hooks", "--apply", "--yes"]);+ assert!(+ stored.exists(),+ "--only hooks stranded the bridge without its key"+ );++ run(&["uninstall", "--apply", "--yes"]);+ assert!(!stored.exists(), "the full uninstall must remove the key");+}+/// Meta Muse Code: `install-mcp` and `install-hooks` both merge into/// `$XDG_CONFIG_HOME/muse/settings.json` around the user's own server and/// hook, keeping `schema_version` and unknown keys, the MCP entry goes underdiff --git a/docs/deploy.md b/docs/deploy.mdindex 0dc32507..26504c5f 100644--- a/docs/deploy.md+++ b/docs/deploy.md@@ -138,7 +138,12 @@ install-mcp --client <name> --auth-token <token>` prints the exactsnippet for every client in the [README Support Matrix](../README.md#support-matrix);run `ai-memory install-mcp --help` for the current accepted values. The agentCLI sends an `Authorization: Bearer <token>` header on every call; ai-memory's-middleware validates with a constant-time comparison.+middleware validates with a constant-time comparison. For Claude Code, prefer+the session-aware bridge: `ai-memory install-mcp --client claude-code+--session-aware --apply --auth-token <token>` keeps the token in+`<data_dir>/auth-token` instead of `~/.claude.json`, and after+`install-hooks --apply --auth-token <token>` the same command works without+`--auth-token`, since the bridge reads the key the hooks hold.**Encrypted transport.** Plain HTTP on the LAN means anyone with apacket capture can read the bearer token (and native `aim_` keys oncediff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 8737f4ff..9189fbf6 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -28,6 +28,17 @@ Warp, Cline, Kilo Code, Goose, Qwen Code and OpenHuman have no> its `PATH`; the Docker wrapper keeps the bare `ai-memory`. ZCode keeps> HTTP entries only and is refused. Passing `--auth-token` explicitly (or> `AI_MEMORY_AUTH_TOKEN`) keeps the HTTP snippets below, header included.+> The two entries that run the bridge with an explicit key are the+> exception: `install-mcp --apply --auth-token <key>` for Claude Code with+> `--session-aware`, and for Muse, stores the key in `<data_dir>/auth-token`,+> the file `install-hooks --apply --auth-token` writes, and writes the entry+> with `--data-dir` and no key. The bridge reads that file whenever no+> bearer is configured, ahead of the root token it discovers on a loopback+> install, so a client whose hooks already hold a key needs no+> `--auth-token` here at all, and rotating the key with `install-hooks` also+> rotates the bridge's. The key stays in the entry, as before, when the+> config already resolves a bearer, a different key is stored, the hooks+> sign in with OIDC, or the snippet is only printed.> **Transport is stateless by default.** Since v0.1.2 the HTTP transport> answers each request independently (plain JSON, no `Mcp-Session-Id`diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex e6a60960..d7cd6370 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -96,7 +96,7 @@ means the boundary is not built yet.| 11k | Server-side tool drop list (#1241) | `ai-memory-hooks/src/drop_list.rs` `IngestDropList::matches`, checked in `router.rs` `admit_hook` and the `handle_hook_batch` loop right after the client capture protocol and before the rate limiter, the ingest semaphore, the sanitizer and storage; lists from `[ingest] drop_tool_use_id_prefixes` / `drop_tool_names`, validated once in `Config::load` (at most 64 entries of 128 printable characters each). Only tool events match: a tool-call id by prefix, a tool name exactly, both read through the per-agent mapping `capture_policy::tool_payload_fields` that tool metadata uses (generic Claude-style fields for an agent without one; Factory Droid sends no tool-call id, so only its tool name can match; Meta Muse Code sends its provider call id in `tool_use_id`, and CodeBuddy Code Claude Code's `tool_use_id`, so both can). A drop answers 202 and counts as `dropped_by_policy`; the matched value is never logged | `router.rs` `the_ingest_drop_list_drops_before_any_capacity_is_spent` (with the semaphore exhausted a listed event still answers 202; control: an unlisted one gets 429) and `the_ingest_drop_list_applies_to_hook_batches` (listed items acknowledged as policy drops, the unlisted item ingested); `drop_list.rs` unit tests (prefix only at the start, names only exact, non-tool events never match, bounds refused; `each_agent_is_matched_on_its_own_tool_fields` matches OpenCode `callID`, Hermes `extra.tool_call_id`, Antigravity `toolCall.name`, Muse and CodeBuddy `tool_use_id` and CodeBuddy `tool_name`, with same-agent controls kept, and fails when only the generic fields are read). Both router tests fail with `matches` forced to `false` | STRONG. The list applies to every project on the server; it narrows what is stored and never widens access || 11l | Marketplace plugin front door: a plugin-launched event gets exactly the native hook's capture policy, scope and server routing, is captured once beside settings-file hooks, and sends nothing without the binary (#1166) | `plugins/*/scripts/ai-memory-hook` (rendered from `crates/ai-memory-cli/templates/plugin/ai-memory-hook.sh` by `render_plugins.rs`) has no capture logic: it only finds the binary (an `ai_memory_bin` option is honoured only as an absolute path, so a checkout cannot plant a relative one) and runs `ai-memory hook` with `AI_MEMORY_HOOK_ORIGIN=<agent>-plugin`, `hook` first so the Docker wrapper routes it, omitting `--server-url` when the option is empty (a pre-3.0 binary's usage error, exit 2 before it reads stdin, is retried once against the default local server with a stderr hint), and without a binary drains stdin, prints `{}` (guidance on `session-start` only) and exits 0; `hook.rs` `is_dropped_plugin_copy` + `plugin_origin.rs` `drops_plugin_event` drop a plugin copy when the user `settings.json` (honouring `CLAUDE_CONFIG_DIR`) or the checkout's `.claude/settings.local.json` carries an ai-memory hook for the same event (`install_hooks::hooks_file_delivers_ai_memory_event`); a Droid-launched copy (`droid-plugin`) is checked against the one file Droid reads hooks from (`~/.factory/hooks.json`, else the `hooks` key of `~/.factory/settings.json`); a Muse-launched copy (`muse-plugin`, recognized by `MUSE_PLUGIN_ID` with `MUSE_SESSION_ID`) is checked against the `hooks` key of `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`, and its subagent events are dropped; both drop a folderless session (no `cwd`, or a Claude desktop `scratch-workspaces` cwd); Codex plugin events are never de-duplicated (an untrusted settings hook is skipped silently, so dropping could lose the event); the drift test keeps every plugin hook on the native path (no `hooks/<agent>/*.sh`, no credential in any plugin file) | CLI `tests/suite/plugins.rs` through the committed launcher and the real binary: `ignore_paths_hold_through_the_plugin` (ignored path never spooled; public-file control kept), `allowlist_mode_holds_through_the_plugin` (unmarked checkout emits nothing, prompts included; marked control captured), `marker_scope_routes_plugin_events`, `server_profiles_route_plugin_events` (profile URL and token, never the plugin's URL), `a_settings_hook_for_the_same_event_drops_the_plugin_copy` (user and project settings; unwired-event and no-settings controls), `a_droid_hook_for_the_same_event_drops_the_droid_plugin_copy` (Droid `hooks.json`; no-Droid-hook, Claude-settings-only, unwired-event and folderless controls), `a_muse_hook_for_the_same_event_drops_the_muse_plugin_copy` (Muse `settings.json`; no-Muse-hook, Claude-settings-only and unwired-event controls; subagent and folderless events dropped), `plugin_origin.rs` `muse_plugin_copy_is_dropped_when_muse_settings_hooks_deliver_the_event` (a matcher-narrowed hook does not count) and `test_plugin_launcher.sh` (an inherited `MUSE_SESSION_ID` without `MUSE_PLUGIN_ID` stays `claude-code`), `folderless_sessions_are_not_captured_through_the_plugin`, `without_a_binary_nothing_is_sent_and_the_agent_is_not_blocked`, `foreign_hosts_are_attributed_or_ignored`, `committed_plugins_match_the_renderer`, `plugin_tree_carries_no_credentials`; `plugin_origin.rs` unit tests (`codex_plugin_events_are_never_deduplicated_against_settings`, `droid_settings_hooks_count_only_while_hooks_json_is_absent`, `only_a_catch_all_matcher_suppresses_the_plugin_copy`: a settings hook narrowed by a matcher never drops the plugin copy); `hook.rs` `plugin_copy_is_dropped_only_with_the_plugin_origin`; `tests/hooks/test_plugin_launcher.sh` (a relative `ai_memory_bin` planted in the checkout is never run; PATH control); `tests/e2e/claude_plugin_smoke.py` (real `claude -p`: settings hook plus plugin give one `user-prompt`) | STRONG. Verified 2026-10-13: removing the `is_dropped_plugin_copy` guard fails the de-duplication and folderless tests (and the smoke reports `user-prompt x2`); disabling the native `Drop` disposition or the allowlist gate fails the `ignore_paths` and allowlist tests through the launcher. Not covered: tool events from a live model turn (no credential in CI), Windows Git Bash, Cowork and the desktop Code tab (see `docs/design-marketplace-plugins.md`) || 11m | The server never opens a filesystem path named in a hook payload | `ai-memory-hooks/src/payload.rs` `HookEnvelope::from_query_and_body` (run by `/hook` and every `/hook/batch` item) only reads the posted JSON; Antigravity step-log enrichment (`antigravity.rs` `enrich_antigravity_step_output`, which opens `<artifactDirectoryPath or transcriptPath dir>/.system_generated/steps/<stepIdx>/output.txt`) runs only client-side in `ai-memory-cli/src/commands/hook.rs` against the client's own home, and the server stores whatever `tool_response` the client sent | `router.rs` `a_hook_payload_cannot_make_the_server_read_its_own_disk` (an Antigravity `PostToolUse` batch naming a server-only directory through `artifactDirectoryPath` and through `transcriptPath`; no stored observation or file contains the server-side sentinel); `payload.rs` `envelope_parsing_never_reads_a_payload_named_antigravity_artifact` and `antigravity_post_tool_use_renders_client_enriched_output` (control: client-supplied output still rendered) | STRONG. Both adversarial tests fail with the server-side enrichment call reinstated (the sentinel file content is stored and readable through search) |-| 12 | Network/auth posture, including auth on by default for new installs (an existing install keeps loopback no-auth until `ai-memory auth enable`) | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart`; new-install default: `commands/init.rs` `root_bearer_for_new_config` mints a root bearer only on a fresh data dir (no config file and no database) and only when no bearer is supplied otherwise, via `local_auth.rs` `provision_root_token` (`auth-tokens/` `0700`, file `0600`, atomic, reused when present) and records the relative `[auth].bearer_token_file`; `config.rs` `apply_bearer_token_file` reads it once (`AI_MEMORY_AUTH_TOKEN` wins, inline + file together refused, a missing or blank file leaves no bearer) and `discover_root_token` lets a packaged install's client commands use `<data_dir>/auth-tokens/default` only with no config file at the probed path, a loopback server URL and no registered `default` profile; `serve.rs` `refuse_a_missing_token_file` stops a server whose configured file holds no token; `AuthSettings::renderable_bearer_token` keeps a file-sourced token out of every renderer: `install_mcp.rs` `route_file_token` (Claude Code gets the session-aware `ai-memory mcp-bridge` entry, Codex and Prime Agent name `AI_MEMORY_AUTH_TOKEN`, every other client a `stdio_bridge_entry` that runs `mcp-bridge --no-session-id` in its documented stdio shape, Pi keeps its extension, ZCode (HTTP-only) is refused) and `mcp_bridge.rs`, which authenticates with the config-resolved bearer and connects upstream before serving stdio, so a refused token ends it with `401 Unauthorized` instead of hanging; `uninstall.rs` `mcp_entry_is_ours` / `toml_mcp_entry_targets` recognise bridge entries by `install_mcp::bridge_entry_url`; `auth_enable.rs` `rewire_clients` re-registers every client whose entry targets this server, `install_hooks.rs` (persisted to the hook credential files, never inlined, not even on the F5 persist-failure fallback), `setup_agent.rs`, `run_autowire.rs`, `setup.rs` (runs `init`, adopts the minted token in memory through `adopt_token_file`, and calls the installers with no explicit token; the rendered user unit carries none; `user_service.rs` `is_rendered_by_setup` lets `uninstall` stop and delete only a unit carrying `setup`'s identity line whose SHA-256 still matches, never a hand-written or edited one); `local_auth.rs` `seed_hook_credential` gives hooks the token through `auth-token`/`auth-header` and keeps a different stored credential; `uninstall.rs` keeps the root bearer (`server_profiles::clear_tokens` `keep`); `commands/auth_enable.rs` is the idempotent opt-in | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls; `cli/tests/suite/auth_default_e2e.rs` against the shipped binary: `a_fresh_install_requires_the_token_and_its_own_clients_still_work` (after `init`, unauthenticated `/mcp`, `/hook`, `/api/v1/projects`, `/admin/status` → 401 and `/healthz` → 200; the same requests with the token succeed; the native hook delivers with no token in its environment, `status` authenticates through config, `mcp-bridge` lists tools; the token is in neither process's `/proc/<pid>/cmdline`; after `install-hooks`, `install-mcp --apply` for every client it writes (21, by default config path under the test home), a refused ZCode install and `auth enable` twice, a scan of the whole home finds the token nowhere and a scan of the data dir finds it only in the token file and the two hook credential files), `an_existing_install_is_unchanged_until_auth_enable` (control: a pre-default install serves every route open and `status` names the fix; `auth enable` twice is idempotent, rewires Claude Code to the bridge, and after a restart the routes refuse and the hook still delivers), `a_packaged_install_with_an_external_config_wires_its_clients`, `uninstall_keeps_the_root_bearer_and_a_missing_one_stops_the_server`, `a_host_client_given_the_token_file_by_env_authenticates`; `init.rs` `a_fresh_init_mints_a_root_bearer_the_loader_reads`, `init_on_an_existing_install_does_not_turn_auth_on`, `init_with_a_supplied_bearer_mints_nothing`, `re_running_init_keeps_the_same_root_bearer`; `config.rs` `a_relative_bearer_token_file_resolves_against_the_data_dir`, `a_missing_or_blank_bearer_token_file_is_reported_not_guessed`, `the_env_token_wins_over_the_bearer_token_file`, `an_inline_bearer_and_a_bearer_token_file_together_are_refused`, `a_client_without_a_config_file_discovers_the_root_bearer`, `root_bearer_discovery_is_refused_outside_its_narrow_case` (existing config, remote URL, `default` profile, env token); `auth_default_e2e.rs` `a_session_less_bridge_serves_any_client_without_holding_the_token` (`tools/list` and a scoped `memory_query` through `mcp-bridge --no-session-id` against a fresh auth-on server, the token in neither the bridge's `/proc/<pid>/cmdline` nor its `/proc/<pid>/environ`; control: the session-aware mode still refuses to start without `CLAUDE_CODE_SESSION_ID`) and `a_bridge_without_the_token_is_refused_cleanly_not_hung` (exits promptly naming `401 Unauthorized`); `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id`, `a_session_less_upstream_config_carries_no_session_header`, `stdio_bridge_forwards_tools_and_session_header_in_both_http_modes` (control); `install_mcp.rs` `a_file_sourced_token_wires_every_client_without_entering_its_config` (every written client: no token, no header, an entry that reaches the server; ZCode refused and unwritten), `stdio_bridge_entries_follow_each_clients_documented_shape`, `inline_and_explicit_tokens_still_embed_as_before` (control); `uninstall.rs` `bridge_entries_are_recognised_by_their_upstream_url` (JSON, OpenCode array and TOML shapes; a bridge to another server and a foreign command are kept); `install_hooks.rs` `a_file_sourced_token_is_persisted_but_never_embedded`; `auth_enable.rs` `enable_twice_is_idempotent_and_leaks_the_token_into_no_harness_config` (every client pre-wired over HTTP is re-registered, ZCode reported as manual, the second run byte-identical), `enable_leaves_an_entry_for_another_server_alone`, `enable_refuses_while_a_default_profile_would_share_the_token`; `local_auth.rs` `the_root_bearer_is_owner_only`, `seeding_never_replaces_a_different_hook_credential`; `setup_e2e.rs` `setup_installs_wires_is_idempotent_and_uninstall_removes_its_unit` (one `setup --yes` in a fresh temp home: the token is in no file under the home but the token file and the two hook credential files, not in the user unit and not in `setup`'s output; the self-check's `memory_status` and a hook event authenticate through the file; `uninstall` then disables and deletes the unit once and a second `uninstall` calls nothing), `uninstall_leaves_a_unit_it_did_not_write` (adversarial: the packaged unit copied by hand is kept, no `systemctl` call); `user_service.rs` `a_foreign_or_edited_unit_is_left_alone`, `rendered_units_carry_an_identity_that_survives_only_unedited` | STRONG. Bite checks for the new-install default: with fresh-install minting disabled the fresh e2e routes answer without a token and the `init` tests fail; with `renderable_bearer_token` returning the file token, `install-mcp`, `install-hooks`, `auth enable` and the e2e scans find it in harness configs; without the `serve` refusal a server whose token file was deleted keeps running (the e2e times out on it); without the hook seeding the fresh e2e hook is refused; without `clear_tokens` `keep` uninstall deletes the root bearer; with `route_file_token` no longer choosing the stdio bridge the every-client and `auth enable` tests fail; with `auth enable` skipping the re-registration its test fails; with the session-less mode forwarding an inherited id the bridge unit test fails; without the 401 naming the refusal e2e fails; without bridge-entry recognition the uninstall test fails; with `setup` handing the token to `install-mcp` its scan finds it in `.claude.json`; with `is_rendered_by_setup` accepting any unit, the foreign-unit tests fail; with discovery removed the packaged e2e gets 401, and with each discovery guard removed the matching case of `root_bearer_discovery_is_refused_outside_its_narrow_case` fails. Residual: a hand-edited `servers.toml` that adds a `default` profile after the root bearer exists would read the root bearer as that profile's token (`server add` refuses it, `auth enable` refuses while it exists); ZCode takes only HTTP entries and is refused, so it needs a manual entry; the stdio entries for Zero, Muse Code and DeepSeek Harness follow their documented or source-level format but were not run against those clients |+| 12 | Network/auth posture, including auth on by default for new installs (an existing install keeps loopback no-auth until `ai-memory auth enable`) | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart`; new-install default: `commands/init.rs` `root_bearer_for_new_config` mints a root bearer only on a fresh data dir (no config file and no database) and only when no bearer is supplied otherwise, via `local_auth.rs` `provision_root_token` (`auth-tokens/` `0700`, file `0600`, atomic, reused when present) and records the relative `[auth].bearer_token_file`; `config.rs` `apply_bearer_token_file` reads it once (`AI_MEMORY_AUTH_TOKEN` wins, inline + file together refused, a missing or blank file leaves no bearer) and `discover_root_token` lets a packaged install's client commands use `<data_dir>/auth-tokens/default` only with no config file at the probed path, a loopback server URL and no registered `default` profile; `serve.rs` `refuse_a_missing_token_file` stops a server whose configured file holds no token; `AuthSettings::renderable_bearer_token` keeps a file-sourced token out of every renderer: `install_mcp.rs` `route_file_token` (Claude Code gets the session-aware `ai-memory mcp-bridge` entry, Codex and Prime Agent name `AI_MEMORY_AUTH_TOKEN`, every other client a `stdio_bridge_entry` that runs `mcp-bridge --no-session-id` in its documented stdio shape, Pi keeps its extension, ZCode (HTTP-only) is refused) and `mcp_bridge.rs`, which authenticates with the config-resolved bearer and connects upstream before serving stdio, so a refused token ends it with `401 Unauthorized` instead of hanging; `mcp_bridge.rs` `bridge_bearer` sends a configured bearer, else the hook key stored in `<data_dir>/auth-token`, else the discovered loopback root token (`AuthSettings::configured_bearer_token` leaves discovery out, so a server+client host never sends root over a stored user key), and the fallback is in the bridge only (`Config::load` never reads that file, so `serve` neither requires nor accepts it); `install_mcp.rs` `store_bridge_key` stores an explicit `--auth-token` there for the Claude Code and Muse bridge entries on `--apply` and writes the entry with `--data-dir` and no key, keeping the key inline when a configured bearer would win, a different key is stored, the hooks use OIDC, the store fails or the Docker helper runs; `uninstall.rs` keeps the stored key on `--only hooks` while `install_mcp::bridge_entry_remains`; `uninstall.rs` `mcp_entry_is_ours` / `toml_mcp_entry_targets` recognise bridge entries by `install_mcp::bridge_entry_url`; `auth_enable.rs` `rewire_clients` re-registers every client whose entry targets this server, `install_hooks.rs` (persisted to the hook credential files, never inlined, not even on the F5 persist-failure fallback), `setup_agent.rs`, `run_autowire.rs`, `setup.rs` (runs `init`, adopts the minted token in memory through `adopt_token_file`, and calls the installers with no explicit token; the rendered user unit carries none; `user_service.rs` `is_rendered_by_setup` lets `uninstall` stop and delete only a unit carrying `setup`'s identity line whose SHA-256 still matches, never a hand-written or edited one); `local_auth.rs` `seed_hook_credential` gives hooks the token through `auth-token`/`auth-header` and keeps a different stored credential; `uninstall.rs` keeps the root bearer (`server_profiles::clear_tokens` `keep`); `commands/auth_enable.rs` is the idempotent opt-in | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls; `cli/tests/suite/auth_default_e2e.rs` against the shipped binary: `a_fresh_install_requires_the_token_and_its_own_clients_still_work` (after `init`, unauthenticated `/mcp`, `/hook`, `/api/v1/projects`, `/admin/status` → 401 and `/healthz` → 200; the same requests with the token succeed; the native hook delivers with no token in its environment, `status` authenticates through config, `mcp-bridge` lists tools; the token is in neither process's `/proc/<pid>/cmdline`; after `install-hooks`, `install-mcp --apply` for every client it writes (21, by default config path under the test home), a refused ZCode install and `auth enable` twice, a scan of the whole home finds the token nowhere and a scan of the data dir finds it only in the token file and the two hook credential files), `an_existing_install_is_unchanged_until_auth_enable` (control: a pre-default install serves every route open and `status` names the fix; `auth enable` twice is idempotent, rewires Claude Code to the bridge, and after a restart the routes refuse and the hook still delivers), `a_packaged_install_with_an_external_config_wires_its_clients`, `uninstall_keeps_the_root_bearer_and_a_missing_one_stops_the_server`, `a_host_client_given_the_token_file_by_env_authenticates`; `init.rs` `a_fresh_init_mints_a_root_bearer_the_loader_reads`, `init_on_an_existing_install_does_not_turn_auth_on`, `init_with_a_supplied_bearer_mints_nothing`, `re_running_init_keeps_the_same_root_bearer`; `config.rs` `a_relative_bearer_token_file_resolves_against_the_data_dir`, `a_missing_or_blank_bearer_token_file_is_reported_not_guessed`, `the_env_token_wins_over_the_bearer_token_file`, `an_inline_bearer_and_a_bearer_token_file_together_are_refused`, `a_client_without_a_config_file_discovers_the_root_bearer`, `root_bearer_discovery_is_refused_outside_its_narrow_case` (existing config, remote URL, `default` profile, env token); `auth_default_e2e.rs` `a_session_less_bridge_serves_any_client_without_holding_the_token` (`tools/list` and a scoped `memory_query` through `mcp-bridge --no-session-id` against a fresh auth-on server, the token in neither the bridge's `/proc/<pid>/cmdline` nor its `/proc/<pid>/environ`; control: the session-aware mode still refuses to start without `CLAUDE_CODE_SESSION_ID`) and `a_bridge_without_the_token_is_refused_cleanly_not_hung` (exits promptly naming `401 Unauthorized`); `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id`, `a_session_less_upstream_config_carries_no_session_header`, `stdio_bridge_forwards_tools_and_session_header_in_both_http_modes` (control); `config.rs` `config_load_never_adopts_the_stored_hook_key` (adversarial: a stored hook key leaves the loaded bearer empty, so `serve` on that data dir neither requires nor accepts it; control: a `bearer_token_file` naming the same file is adopted); `mcp_bridge.rs` `bridge_bearer_puts_the_stored_hook_key_below_a_configured_bearer` (a configured bearer wins, a blank one does not), `a_stored_user_key_outranks_the_discovered_root_token` (adversarial: discoverable loopback root plus a stored key sends the stored key; control: discovery alone still sends root); `install_mcp.rs` `an_explicit_key_for_a_bridge_is_stored_instead_of_written_inline` (Claude Code and Muse entries carry no key and name the data dir, the stored pair is the hooks' format; controls keeping the key inline and storing nothing: print path, configured bearer, a different stored key, OIDC hooks, Docker helper, HTTP entry); `removal.rs` `an_explicit_bridge_key_is_stored_and_outlives_only_hooks_removal`; `install_mcp.rs` `a_file_sourced_token_wires_every_client_without_entering_its_config` (every written client: no token, no header, an entry that reaches the server; ZCode refused and unwritten), `stdio_bridge_entries_follow_each_clients_documented_shape`, `inline_and_explicit_tokens_still_embed_as_before` (control); `uninstall.rs` `bridge_entries_are_recognised_by_their_upstream_url` (JSON, OpenCode array and TOML shapes; a bridge to another server and a foreign command are kept); `install_hooks.rs` `a_file_sourced_token_is_persisted_but_never_embedded`; `auth_enable.rs` `enable_twice_is_idempotent_and_leaks_the_token_into_no_harness_config` (every client pre-wired over HTTP is re-registered, ZCode reported as manual, the second run byte-identical), `enable_leaves_an_entry_for_another_server_alone`, `enable_refuses_while_a_default_profile_would_share_the_token`; `local_auth.rs` `the_root_bearer_is_owner_only`, `seeding_never_replaces_a_different_hook_credential`; `setup_e2e.rs` `setup_installs_wires_is_idempotent_and_uninstall_removes_its_unit` (one `setup --yes` in a fresh temp home: the token is in no file under the home but the token file and the two hook credential files, not in the user unit and not in `setup`'s output; the self-check's `memory_status` and a hook event authenticate through the file; `uninstall` then disables and deletes the unit once and a second `uninstall` calls nothing), `uninstall_leaves_a_unit_it_did_not_write` (adversarial: the packaged unit copied by hand is kept, no `systemctl` call); `user_service.rs` `a_foreign_or_edited_unit_is_left_alone`, `rendered_units_carry_an_identity_that_survives_only_unedited` | STRONG. Bite checks for the new-install default: with fresh-install minting disabled the fresh e2e routes answer without a token and the `init` tests fail; with `renderable_bearer_token` returning the file token, `install-mcp`, `install-hooks`, `auth enable` and the e2e scans find it in harness configs; without the `serve` refusal a server whose token file was deleted keeps running (the e2e times out on it); without the hook seeding the fresh e2e hook is refused; without `clear_tokens` `keep` uninstall deletes the root bearer; with `route_file_token` no longer choosing the stdio bridge the every-client and `auth enable` tests fail; with `auth enable` skipping the re-registration its test fails; with the session-less mode forwarding an inherited id the bridge unit test fails; without the 401 naming the refusal e2e fails; without bridge-entry recognition the uninstall test fails; with `Config::load` adopting the stored hook key, without the bridge fallback, with discovery counted as a configured bearer, or with `install-mcp` never storing the key, the matching new test fails; with `setup` handing the token to `install-mcp` its scan finds it in `.claude.json`; with `is_rendered_by_setup` accepting any unit, the foreign-unit tests fail; with discovery removed the packaged e2e gets 401, and with each discovery guard removed the matching case of `root_bearer_discovery_is_refused_outside_its_narrow_case` fails. Residual: a hand-edited `servers.toml` that adds a `default` profile after the root bearer exists would read the root bearer as that profile's token (`server add` refuses it, `auth enable` refuses while it exists); ZCode takes only HTTP entries and is refused, so it needs a manual entry; the stdio entries for Zero, Muse Code and DeepSeek Harness follow their documented or source-level format but were not run against those clients || 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments, with `sanitize_events` and `append_boundary_events` scrubbing event/checkpoint/losses content *before* the 64 KiB cap so a cap-straddling secret is never cut into an unmatchable prefix (#1113); `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, scrubbing content with the explicitly supplied configured sanitizer before its 16 KiB store-boundary bound; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`, `workstream_content_is_scrubbed_before_the_store_cap` (a credential straddling the 16 KiB store cap is redacted, not persisted as an unmatchable prefix; benign control verbatim; #1113); `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls), `finish_run_scrubs_event_content_before_the_byte_cap` and `finish_run_scrubs_boundary_events_before_the_byte_cap` (a credential straddling the 64 KiB event cap is redacted in the raw segment and never reaches the index; checkpoint/losses and benign controls; #1113); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten || 12c | Browser cross-origin writes refused on an unauthenticated server (a foreign page in the operator's browser, DNS rebinding, and a LAN host where browsers send no fetch metadata) | `serve.rs` `refuse_cross_origin_browser_requests` / `is_cross_origin_browser_request`, layered on the machine (`/mcp`, `/hook*`, `/handoff`, `/workstream/*`, `/identity`) and admin (`/admin/*`) routes when auth is off: `Sec-Fetch-Site` other than `same-origin`/`none` → 403, or, without fetch metadata, an `Origin` whose authority is not the `Host` → 403; and `is_non_script_browser_request`: any `Sec-Fetch-Dest` other than `empty` (case-insensitive; non-UTF-8 refused) → 403 whatever `Sec-Fetch-Site` says, so links, images, navigations, iframes and form posts are refused even as `same-origin` or `none`. Browsers send fetch metadata over plain HTTP only to a potentially trustworthy host, so on any other `Host` (a LAN address or name in the allowlist, `0.0.0.0`, `host.docker.internal`; `is_loopback_host` admits only `localhost`, `*.localhost`, `127.0.0.0/8` and `[::1]`) `handoff_fetch_lacks_client_marker` also refuses `GET`/`HEAD /handoff` without a non-empty `X-AI-Memory-Client` header (`ai_memory_hooks::CLIENT_MARKER_HEADER`) → 403 whose body names both remedies (re-stage hooks, or set a bearer token). A page cannot add that header without a preflight these routes never answer. `/handoff` is the one state-changing `GET` on these routes; the other `GET`s are reads a foreign page cannot see the answer to, and every cross-origin `POST` carries `Origin`. Every first-party client sends the marker: the native hook (`hook_capture.rs` `post_hook`/`post_batch`/`get_handoff`), CLI subcommands (`http_client.rs` `ServerEndpoint::authenticate`), every curl in `hooks/_lib.sh`, both header tables in `hooks/lib/ai-memory-hook.ps1`, and the generated TypeScript integrations (`render_shared.rs` `ts_auth_headers_fn` plus the spool drain). Loopback hosts keep accepting a fetch without it, so hooks staged before the header existed still work on a default install, except that a request carrying any proxy forwarding header (`Forwarded`, `X-Forwarded-For`/`-Host`/`-Proto`/`-Server`/`-Port`, `X-Original-Forwarded-For`, `X-Real-IP`, `X-Client-IP`, `CF-Connecting-IP`, `True-Client-IP`, `Via`; `PROXY_HEADERS`) counts as non-loopback, since a plain-HTTP proxy can rewrite `Host` to loopback while the browser behind it sent no fetch metadata. No first-party client sends those headers. Hooks, the CLI and MCP clients send none of these headers; the web UI's same-origin `/admin/pending-writes` calls are `fetch()` (`Sec-Fetch-Dest: empty`) and pass. Behind it, axum `Json` and rmcp's `Content-Type: application/json` check refuse the preflight-free content types (`text/plain`, form-urlencoded, multipart) with 415; `require_allowed_host` (and rmcp `allowed_hosts` on `/mcp`) refuses a rebinding `Host`; machine/admin routes carry no CORS layer, so a preflight never comes back permissive. A stored wiki page viewed in the built-in web UI could otherwise turn the guard's same-origin allowance into a claim: `ai-memory-web/src/markdown.rs` `safe_image_url` / `is_safe_image_target` render as `#` any image target that is root-relative, a network path, carries a `..` segment (also percent-encoded), or, for a UI mounted at the base-path root, starts with a server route segment Every `/web` surface (built-in pages including `/web/pending`, the login page, a custom SPA and `/api/v1`) answers `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'` (`ai-memory-web/src/mount.rs` `deny_framing`), because a framed page's own Approve/Reject `fetch()` is same-origin and the guard rightly lets it through | `cli/tests/suite/cross_origin_e2e.rs` `browser_cross_origin_requests_cannot_write_to_an_unauthenticated_loopback_server`, against the shipped `serve`: every write route (`/hook`, `/hook/batch`, MCP `memory_write_page`/`memory_delete_page`/`memory_message_send`/`memory_handoff_accept`, `/admin/write-page`/`delete-page`/`purge-project`/`messages/send`, `/workstream/runs`) × each simple content type × modern, Origin-only and fetch-metadata-only browser shapes → 4xx; body-less `GET /handoff` (which claims the single-use baton), `POST /admin/profile/rebuild` and `POST /admin/backup` → 403; a rebinding `Host` → 403; preflights answer no `Access-Control-Allow-*`; `GET /handoff` as a same-origin `document` or `image` and as a `Sec-Fetch-Site: none` `document` → 403 with the baton still open. Then a canary scan of the whole data dir, page/project/handoff survival, and legitimate controls (JSON MCP calls, a JSON hook → 202, the web UI's same-origin `/admin/pending-writes` list and approve reach their handlers, the anonymous active-project pointer is unmoved after the refused `/handoff` fetches while the closing hook-style fetch claims the baton and moves it). `serve.rs` `cross_origin_browser_request_detection` and `non_script_browser_request_detection` (header tables) and `cross_origin_browser_guard_applies_only_without_auth` (same-origin `image` and `none` `document` refused, same-origin `empty` passes, both pass with auth on); `ai-memory-web` `markdown.rs` `neutralises_images_that_reach_server_routes` (`/handoff?…`, `/admin/backup`, `//host/…`, `../` and `%2e%2e/` traversal, root-mounted route names refused) with `preserves_relative_images` as the legitimate control. `cross_origin_e2e.rs` `handoff_fetch_on_a_lan_host_requires_the_client_marker`, against a `serve` that allowlists a LAN name and address: `GET` and `HEAD /handoff` through either without the marker, and with an empty one → 403 carrying the remedy text, with the baton still open and the active-project pointer unmoved; controls: a marked fetch through the LAN name claims the baton, and a marker-less fetch through `127.0.0.1` (a hook staged before the marker) claims the next one; then a `127.0.0.1` fetch carrying each proxy forwarding header and no marker → 403 with the baton still open, and the same fetch with the marker claims it. `serve.rs` `loopback_host_detection`, `handoff_fetch_client_marker_decision` (incl. a loopback `Host` with each proxy header, refused without the marker and admitted with it, and a named row per header so none can drop out of the list) and `handoff_client_marker_guard_on_lan_hosts_and_under_a_base_path` (also under a `--base-path` nest; inactive with auth on). Front-door parity: `hook_capture.rs` `every_native_hook_request_carries_the_client_marker` (handoff GET, hook POST, batch POST), `http_client.rs` `authenticate_no_token_sets_only_the_client_marker`, the client-marker block of `tests/hooks/test_lib.sh` (every curl branch of the GET, the POST and the drain, plus a static check that every PowerShell header table carries it and every `Invoke-WebRequest` passes one), `render_shared.rs` `assert_every_ts_request_carries_client_marker` run for OpenCode, OpenCode 2, OMP, Pi and OpenClaw, `external_capture_ts.rs` (the rendered OpenCode plugin under Node sends no unmarked request) and `external_capture_powershell.rs` `every_request_carries_the_client_marker` (Windows leg); `ai-memory-web/src/mount.rs` `web_surfaces_refuse_to_be_framed` (`/web`, `/web/pending`, `/web/login`, `/api/v1/projects` all carry both headers; bites with `deny_framing` neutralized) | STRONG with listed residuals. Bite checks: with the marker check disabled, the LAN e2e marker-less `GET /handoff` returns 200 and the unit layer test fails; with the proxy-header rule disabled, the proxied loopback e2e fetch claims the baton and the unit decision test fails; dropping the marker from the native handoff GET, the shell token-drain curl, a PowerShell header table or the TypeScript spool drain fails the matching front-door test. With the guard removed, the cross-origin `GET /handoff` returns 200, consumes the baton and moves the active-project pointer (the pre-fix behaviour); with the guard treating `same-origin` as foreign, the web UI control gets 403; with the `Sec-Fetch-Dest` check removed, the same-origin `document` `GET /handoff` returns 200 and the unit guard test lets a same-origin image through; with the host layer removed, a rebound `/hook` returns 202; a permissive `CorsLayer` fails the preflight assertion; reverting `is_safe_image_target` to the pre-fix rule fails the markdown test on `/handoff?…`, dropping the percent-decoding fails it on `%2e%2e/`, and emptying the route list fails it on a root-mounted `handoff`. To reproduce the bite on the 415 layer, remove the guard and make `/hook` read a raw body instead of `Json`: a `text/plain` hook then returns 202 and the test fails. Residual, closed by setting a bearer token: a browser that sends no fetch metadata even to a loopback host (Safari before 16.4) sends no `Sec-Fetch-*` header and no `Origin` on an image `GET` or a link click, so such a request to a loopback host still reaches `/handoff` (loopback keeps accepting marker-less legacy hooks) and the other, read-only `GET` routes. On a non-loopback host the marker requirement closes `/handoff` for every browser. A plain-HTTP proxy that rewrites `Host` to its loopback upstream and adds no forwarding header (nginx's default `proxy_pass`) looks exactly like a local client, so in front of an unauthenticated server it must add `X-Forwarded-For` or keep `proxy_set_header Host $host`, or the server must sit behind TLS or use a bearer token (`security.md`, `https-via-proxy.md`). Browsers that send fetch metadata no longer have the earlier link residuals: a link opened from another app (`Sec-Fetch-Site: none`) and a link clicked in a stored page (`same-origin` navigation) both carry a non-`empty` destination and are refused. With auth on, the bearer token and the session CSRF token are the gate and this layer is a no-op || 12d | The web UI and `/api/v1` cannot write, and render stored text inert | `crates/ai-memory-web/clippy.toml` `disallowed-methods`: every `Wiki` write and destructive method (`write_page`, `write_page_if`, `apply_batch`, the delete/evict/purge/restore/move/reindex/remove-dir helpers, `commit_all`, `approve_auto_improve_proposal`) and the `writer()` / `git()` accessors are lint errors in the crate, so the `Wiki` held by `WebState` stays read-only under `cargo clippy -D warnings`; only the integration-test module carries the `allow`, for fixtures. Templates are askama with HTML auto-escaping; the history diff (`templates/history.html`) and the session timeline (`templates/session.html`) print page lines, observation titles and bodies escaped, with no `|safe`, and no captured value is interpolated into a script | `ai-memory-web` `history_replay.rs` `session_timeline_renders_captured_markup_inert` (a `<script>` title and body plus `"><img onerror>` and `' onmouseover='` payloads, checked to survive ingest first, render escaped) and `history_diff_renders_page_markup_inert` (the same payloads in a page version's diff lines); `mount.rs` `web_surfaces_refuse_to_be_framed` covers the history, timeline and history-API routes (200 with both anti-framing headers) | STRONG. Bite checks: a `Wiki::write_page` and a `Wiki::delete_page` call added to `routes/history.rs` fail `cargo clippy -p ai-memory-web --all-targets -- -D warnings` with `use of a disallowed method`; `|safe` on the observation body or a diff line fails the matching inert-render test. The lint is per crate: a write reached through another crate's helper is outside it, which review and the `/api/v1` "zero writer calls" rule still cover |diff --git a/docs/users.md b/docs/users.mdindex b24f5b44..7c53e4f3 100644--- a/docs/users.md+++ b/docs/users.md@@ -511,12 +511,17 @@ the data dir, both `0600` (the data dir itself is `0700`):| file | read by ||---|---|-| `<data_dir>/auth-token` | the native `ai-memory hook` command |+| `<data_dir>/auth-token` | the native `ai-memory hook` command, and `ai-memory mcp-bridge` when no bearer is configured (ahead of a discovered loopback root token) || `<data_dir>/auth-header` | the shell hooks, via `curl -H @<file>` |+`install-mcp --apply --auth-token …` writes the same pair for a Claude Code+(`--session-aware`) or Muse bridge entry and leaves the key out of that entry,+unless a different key is already stored there or the hooks sign in with OIDC.+`ai-memory uninstall` deletes both files when it removes the hooks (a full-uninstall or `--only hooks`); `--only mcp`, `--only instructions` and `--only-skills` keep them for the hooks still installed.+uninstall, or `--only hooks` while no Claude Code or Muse bridge entry+remains); `--only mcp`, `--only instructions` and `--only skills` keep them for+the hooks still installed.It is deliberately **not** written into the agent's own config any more. Before#552 it went onto the hook's command line (`--auth-token <token>` for native@@ -550,6 +555,12 @@ Until you re-run `install-hooks`, the hooks still hold the old token and thereis nothing newer to retry with, so those events stay queued and age out on thenormal retry budget rather than blocking the rest of the spool (#493).+The same re-run rotates the MCP bridge's key when the bridge reads the stored+file, which is the case for an entry written without a key. An entry that still+carries the old key in `AI_MEMORY_AUTH_TOKEN` (written by the print path, or by+`install-mcp` before the key moved to the data dir) keeps sending it: re-run+`install-mcp --apply` without `--auth-token` to drop it.+## Running for a teamEverything above concerns *who* a request is, which is the identity half. The@@ -713,6 +724,11 @@ Without `--as-user`, hooks install the same way they always have:the bearer authenticates and attribution flows from the token's owner(root user or DB user) at write time.+The MCP side needs no second copy of the key. `ai-memory install-mcp+--client claude-code --session-aware --apply` on the same data dir writes a+bridge entry without a key, and the bridge sends the key the hooks hold, so+MCP calls and captured events attribute to the same user.+## Per-project accessAuthentication says *who* is asking; each project's **access mode** decides