Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix: secure generated DSH hook config
AkitaOnRails822b3737261d
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex cad62489..ee018218 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -7876,16 +7876,44 @@ fn apply_to_dsh(strategy,);let hooks_json = command_dir.join("hooks.json");- fs::write(+ write_private_dsh_config(&hooks_json,- serde_json::to_string_pretty(&payload).expect("static hook payload serializes"),- )- .with_context(|| format!("writing {}", hooks_json.display()))?;+ serde_json::to_string_pretty(&payload)+ .expect("static hook payload serializes")+ .as_bytes(),+ )?;eprintln!("✓ wrote DSH hook config → {}", hooks_json.display());print!("{}", dsh_bridge_patch_fragment(&command_dir));Ok(())}+/// DSH's generated hook config can embed the server bearer. Keep it private+/// from the first byte and refuse a final-component symlink instead of+/// following an attacker-controlled target.+fn write_private_dsh_config(path: &Path, content: &[u8]) -> Result<()> {+ let mut options = fs::OpenOptions::new();+ options.write(true).create(true).truncate(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt as _;+ options.mode(0o600).custom_flags(libc::O_NOFOLLOW);+ }++ let mut file = options+ .open(path)+ .with_context(|| format!("opening private DSH hook config {}", path.display()))?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ file.set_permissions(fs::Permissions::from_mode(0o600))+ .with_context(|| format!("securing DSH hook config {}", path.display()))?;+ }+ file.write_all(content)+ .with_context(|| format!("writing {}", path.display()))?;+ file.sync_all()+ .with_context(|| format!("syncing {}", path.display()))+}+/// The Cordis patch-list fragment that mounts the/// `@deepseek-ai/dsh-hooks-claude-code` bridge with `configPath` pointing at/// the generated `hooks.json` in `command_dir`. Shared by `install-hooks`@@ -9742,6 +9770,102 @@ command = "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/a}}+ #[test]+ fn powershell_fallback_drops_raw_dsh_assistant_output() {+ let helper = fs::read_to_string(+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../hooks/lib/ai-memory-hook.ps1"),+ )+ .unwrap();+ assert!(+ helper.contains(+ "($Agent -eq \"claude-code\" -or $Agent -eq \"dsh\") -and $Event -eq \"stop\""+ ),+ "DSH must share the raw Stop-field refusal with Claude Code"+ );+ }++ #[cfg(unix)]+ #[test]+ fn apply_to_dsh_keeps_an_embedded_bearer_owner_only() {+ use std::os::unix::fs::PermissionsExt as _;++ let root = TempDir::new().unwrap();+ let data = TempDir::new().unwrap();+ let source = root.path().join("hooks").join("dsh");+ fs::create_dir_all(&source).unwrap();+ let scripts = DSH_EVENTS+ .iter()+ .map(|(_, script)| *script)+ .collect::<Vec<_>>();+ stub_scripts(&source, &scripts);+ fs::write(root.path().join("hooks").join("_lib.sh"), "#!/bin/sh\n").unwrap();++ let staged = data.path().join("hooks").join("dsh");+ fs::create_dir_all(&staged).unwrap();+ let hooks_json = staged.join("hooks.json");+ fs::write(&hooks_json, "{}").unwrap();+ fs::set_permissions(&hooks_json, fs::Permissions::from_mode(0o644)).unwrap();++ let mut args = default_hook_args();+ args.agent = AgentChoice::Dsh;+ apply_to_dsh(+ &source,+ "http://127.0.0.1:49374",+ Some("private-bearer"),+ data.path(),+ &args,+ )+ .expect("apply_to_dsh succeeds");++ assert_eq!(+ fs::metadata(&hooks_json).unwrap().permissions().mode() & 0o777,+ 0o600+ );+ let content = fs::read_to_string(hooks_json).unwrap();+ assert!(content.contains("private-bearer"));+ }++ #[cfg(unix)]+ #[test]+ fn apply_to_dsh_refuses_a_symlinked_hook_config() {+ use std::os::unix::fs::symlink;++ let root = TempDir::new().unwrap();+ let data = TempDir::new().unwrap();+ let source = root.path().join("hooks").join("dsh");+ fs::create_dir_all(&source).unwrap();+ let scripts = DSH_EVENTS+ .iter()+ .map(|(_, script)| *script)+ .collect::<Vec<_>>();+ stub_scripts(&source, &scripts);+ fs::write(root.path().join("hooks").join("_lib.sh"), "#!/bin/sh\n").unwrap();++ let staged = data.path().join("hooks").join("dsh");+ fs::create_dir_all(&staged).unwrap();+ let target = data.path().join("foreign.json");+ fs::write(&target, "untouched").unwrap();+ symlink(&target, staged.join("hooks.json")).unwrap();++ let mut args = default_hook_args();+ args.agent = AgentChoice::Dsh;+ let error = apply_to_dsh(+ &source,+ "http://127.0.0.1:49374",+ Some("private-bearer"),+ data.path(),+ &args,+ )+ .expect_err("a final symlink must be refused");++ assert!(+ error+ .to_string()+ .contains("opening private DSH hook config")+ );+ assert_eq!(fs::read_to_string(target).unwrap(), "untouched");+ }+/// Hermes' output must state the manual paste step (ai-memory does not write/// `~/.hermes/config.yaml`) and must not advertise a staged bundle or a/// session-end hook — the memory-provider plugin owns session lifecycle.diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex b5f1eaf4..6d35c09f 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -22,6 +22,7 @@ means the boundary is not built yet.| # | Boundary | Enforcing code | Adversarial test(s) | Coverage ||---|----------|----------------|---------------------|----------|+| 0a | A generated DSH hook config cannot expose or redirect an embedded server bearer | `ai-memory-cli/src/commands/install_hooks.rs` `write_private_dsh_config` creates `hooks.json` owner-only before writing, resets a pre-existing file to `0600`, and refuses a final-component symlink | `install_hooks.rs` `apply_to_dsh_keeps_an_embedded_bearer_owner_only` (a world-readable predecessor becomes private before the new bearer is written; the bearer control is present), `apply_to_dsh_refuses_a_symlinked_hook_config` (an attempted redirect is refused and its target stays byte-identical) | STRONG on Unix; Windows protection remains the data directory ACL || 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)`; `reader.rs` `sessions_for_scope_filtered` joins only consolidation jobs in the requested workspace and project; `reader.rs` `incremental_pages` filters workspace and project before its keyset and limit; `reader.rs` `session_counts_by_agent` filters mixed-source observations by the requested workspace and project; `reader.rs` `observation_stream_votes` (`[retrieval] observation_stream`, on by default) filters both the matching observations and the `sessions/<id>.md` page they vote for to the queried workspace and project, and attaches a vote's observation excerpt and ids only when the caller's session-timeline owner filter admits the session (`sessions_hidden_from`; `HybridSearch::owner`, threaded from `memory_query`, `/web/search` and `/api/v1/search` through `OwnerFilter::for_actor_context`); the raw-observation fallback `search_observations_for_project_as` drops sessions that filter does not admit; `reader.rs` `page_versions` / `page_version_body` (web page history) read by `(workspace_id, project_id, path)` and take a caller's version id only inside that triple; `ai-memory-web` `routes/session.rs` takes a raw session id only through `session_summary_scoped` (row or observation in the project, owner filter) and `session_observations_scoped` | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs`; `session_observations.rs` `consolidation_summary_latest_generation_is_scope_and_owner_bound` (a foreign-scope job is absent; the own latest generation and owner controls pass), `incremental_pages_equal_timestamps_cutoff_expiry_and_foreign_scope` (foreign scope absent with a same-scope control), `mixed_capture_count_scopes_observations_and_preserves_owner_and_window` (foreign-scope observations cannot turn an own session into a mixed one; same-scope control can); handoff receiver-session scope: see row 4, `multi_session.rs` `handoff_accept_rejects_foreign_or_missing_receiver_session` (cross-project and cross-workspace receivers refused); `multi_session.rs` `observation_stream_never_crosses_a_project_or_workspace` (a home observation cannot vote for a same-path session page in another project or workspace, and a foreign project's observation cannot lift a home page; control: home's own page receives the vote), fails with either the observation or the page scope filter removed; `multi_session.rs` `observation_excerpts_follow_the_session_owner_while_the_vote_stays_shared` (operator B, and an unattributed caller, querying words only A's owned session holds get A's shared session page with its own snippet, no excerpt, no observation ids and no raw hit; controls: A gets the excerpt, ids and raw hit, an unattributed session's excerpt reaches every viewer, and the unfiltered single-user path is unchanged), bite-checked against both the vote guard and the raw-fallback clause; `ai-memory-mcp` `server.rs` `memory_query_shows_observation_text_only_to_its_sessions_owner` and `ai-memory-web` `recall_trace.rs` `project_search_shows_observation_excerpts_only_to_the_sessions_owner` (the same through `memory_query`, `/web/search` and `/api/v1/search`; each fails when its surface passes `OwnerFilter::Any`); `multi_session.rs` `page_history_keeps_the_overwritten_version_and_stays_in_scope` (a sibling project's or another workspace's version id, or a home id under another path, reads as `None`; control: both home versions); `ai-memory-web` `history_replay.rs` `history_refuses_foreign_project_workspace_and_version_ids` (another project's or workspace's path, and a foreign version id as `from` or `to`, answer 404 on `/web/w/…/h/*path` and `/api/v1/…/history/*path` without the foreign text; control: the home history lists only home's rows at a path a sibling also uses, and an explicit home pair diffs) and `session_timeline_refuses_foreign_session_ids` (a sibling project's or another workspace's session id and an unknown id → 404, another operator's owned session → 404; controls: the home session, and the owner reading theirs); bite: dropping the scope filter from `page_version_body` or the project filter from `page_versions`, or replacing the `session_summary_scoped` check or its owner filter, fails them | STRONG || 1b | Reserved `_global` scope union never leaks a foreign project (#930) | `ai-memory-mcp/src/server.rs` `memory_query` — the union runs for single-project queries (`scopes` empty) and searches **only** `lookup_global_scope`'s reserved `(workspace_id, project_id)`, never an arbitrary project; the double-search guard resolves the *queried* project (named or active) so it can't be tricked into skipping | `server.rs` `global_union_never_leaks_a_foreign_projects_pages` (a third real project's page must not surface via the union; reserved page must), `single_project_query_unions_global_scope_and_multi_scope_skips_it` | STRONG || 1c | Reserved `_global` scope is read-open, write-gated (GHSA-7qj3-7wqw-m5w6) | `ai-memory-store/src/project_authz.rs` `ProjectAuthz::authorize` (a write to `default/_global` needs root or a `write` grant in either access mode; creator ignored) fed by `resolve_project_authz`/`read_project_row` (`reserved_global`, grant read for the global scope regardless of mode); `ai-memory-mcp/src/server.rs` `memory_write_page` resolves `scope: "global"` through `write_target_ids_with_actor` like an explicit `default/_global` | `project_authz.rs` `the_global_scope_admits_writes_only_from_root_or_a_write_grant`; `server.rs` `a_user_without_a_global_grant_cannot_change_the_global_scope` (both spellings and delete refused for an ungranted user and for `_global`'s creator; page survives; reads stay open), `a_global_write_grant_admits_writes_and_the_union_stays_readable` (legitimate control: write grant admits both spellings, another user's restricted-project query still unions the page); bite-checked with the authz rule removed and with the raw `create_global_scope` path restored | STRONG |diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index cfdb584f..e5fa1825 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -1005,11 +1005,11 @@ function Invoke-AiMemoryHook {Set-AiMemoryBriefed -Path $StartMarker}}- # Assistant/Stop capture (#196) is native-only. Scoped to claude-code + stop- # so a PostToolUse whose tool output legitimately contains the literal string- # is unaffected. If a Stop payload still carries the raw field, drop the whole- # event rather than POST it verbatim (the script fallback cannot sanitize it).- if ($Agent -eq "claude-code" -and $Event -eq "stop" -and $Payload -and $Payload.Contains('"last_assistant_message"')) {+ # Assistant/Stop capture (#196) is native-only. Scoped to agents whose Stop+ # payload may carry the field, so unrelated tool output containing the literal+ # string is unaffected. If a Stop payload still carries the raw field, drop the+ # whole event rather than POST it verbatim (the fallback cannot sanitize it).+ if (($Agent -eq "claude-code" -or $Agent -eq "dsh") -and $Event -eq "stop" -and $Payload -and $Payload.Contains('"last_assistant_message"')) {return}$Cwd = Resolve-AiMemoryCwd -Payload $Payload -Agent $Agent