Skip to main content

write_session_env

Function write_session_env 

Source
pub fn write_session_env(env_file: &Path, session_id: &str) -> Result<()>
Expand description

Append export TRACEVAULT_SESSION_ID='<session_id>' to the Claude Code session env file, unless that exact line is already present. Pure I/O helper factored out so it can be unit-tested without touching the real CLAUDE_ENV_FILE env var. Creates the file if it doesn’t exist.

SessionStart fires on startup and on resume/clear/compact — all with the same session id — so an unconditional append would grow the env file with duplicate export lines every time. Reading the file first and skipping an already-present line makes the write idempotent.

session_id is untrusted input from the hook event JSON, and this file is later sourced by the shell — a naive unquoted interpolation would be a shell-injection sink. Defend in depth: reject anything outside the existing session-id allowlist ([A-Za-z0-9_-], non-empty) by silently skipping the write (best-effort: a malformed id is simply never exported), and single-quote the value we do write. After the allowlist check there are no quote or metacharacters left, so single-quoting closes the sink.