Skip to content

Commit 9c6acd6

Browse files
nik13claude
andcommitted
fix(hook-to-otlp): scrub only the user-name component of home paths
The previous round let a home-path user name run across spaces up to the next slash, so opted-in Shell command text such as "cd /Users/alice && ls src/foo" lost "&& ls src". The generic scrub now replaces only the one directory component after /Users/, /home/ or C:\Users\: it stops at whitespace, quotes and punctuation no account name uses, and does not end with a dot. Names with spaces are handled through this machine's own home directory: the basename of os.path.expanduser("~") is matched literally after any home prefix (raw, JSON-escaped or forward-slash Windows form), with a boundary check so /Users/al does not match inside /Users/alice. This also fixes "/Users/Jo Ann." and "/Users/Jo Ann," leaking "Ann". Another account's spaced name keeps the part after the first space; README and the shared page document that. Docs: the shared page no longer says every app page uses the guarded command (hook-based apps do; native-OTel apps have no hook command), and both pages note that fish reads the subshell parentheses as command substitution. Tests: command-text regression cases, own spaced home (POSIX and Windows forms, end of string, punctuation, al/alice), and the documented limitation for other accounts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 9b77d51 commit 9c6acd6

5 files changed

Lines changed: 86 additions & 34 deletions

File tree

‎examples/coding-agents/hook-to-otlp/README.md‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ send is inline (default timeout 3 s) and state files are not locked.
3030

3131
### Registering the hook (canonical guarded form)
3232

33-
Every app ships its hook commands in this form, so a missing emitter, a missing
33+
Every app that uses this emitter ships its hook commands in this form, so a missing emitter, a missing
3434
`python3`, or a crash can never return exit code 2 (which many hosts treat as
3535
"block") and never prints a decision:
3636

@@ -98,9 +98,14 @@ expected (or empty) stdout and that the installed emitter received the payload.
9898
spans add `llm.model_name` when the payload names a model (the root uses the last model
9999
reported by a session, turn or llm event).
100100
- Opted-in content keeps paths but replaces the user name in home-directory paths with
101-
`<user>` (`/Users/<user>/...`, `/home/<user>/...`, `C:\Users\<user>\...`, `~<user>/...`),
102-
including names with spaces when a path separator follows them, and this machine's own
103-
home directory wherever it appears.
101+
`<user>` (`/Users/<user>/...`, `/home/<user>/...`, `C:\Users\<user>\...`, `~<user>/...`).
102+
The name is the one directory component after the prefix; it stops at whitespace,
103+
quotes, and punctuation no account name uses, so the rest of a command stays intact
104+
(`cd /Users/<user> && ls src/x`). This machine's own user name (the last component of
105+
`os.path.expanduser("~")`) is matched literally, so it is replaced in full even when it
106+
contains spaces. Limitation: another account's name with spaces (for example from a
107+
log pasted from another machine) keeps the part after the first space
108+
(`/Users/<user> Smith/...`).
104109

105110
## Writing an adapter
106111

‎examples/coding-agents/hook-to-otlp/emit.py‎

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
import contextlib
2525
import dataclasses
26+
import functools
2627
import hashlib
2728
import importlib
2829
import json
@@ -67,12 +68,20 @@
6768
re.compile(r"(?i)\b(bearer\s+)[A-Za-z0-9._~+/=-]{12,}"),
6869
re.compile(r"(?i)\b((?:api[_-]?key|secret[_-]?key|access[_-]?token|password|passwd|token)\b[\"']?\s*[:=]\s*[\"']?)[^\s\"',}]+"),
6970
)
70-
# Opted-in content keeps paths but not the account name inside them. A name
71-
# may contain spaces when a path separator follows it ("/Users/Jo Ann/x").
72-
_NAME = r"(?:[^/\\\s\"']+(?: [^/\\\s\"']+)*(?=[/\\])|[^/\\\s\"']+)"
71+
# Opted-in content keeps paths but not the account name inside them: the one
72+
# directory component after /Users/, /home/ or C:\Users\ (raw, JSON-escaped or
73+
# with forward slashes). A component stops at whitespace, quotes and characters
74+
# no macOS, Linux or Windows account name uses (shell and sentence punctuation),
75+
# and does not end with a dot, so text after the path ("&& ls src/x", "),")
76+
# stays as it was. Names with spaces are matched only for this machine's own
77+
# home directory (see _own_home_pattern).
78+
_HOME_PREFIX = r"(/Users/|/home/|[A-Za-z]:(?:\\\\|\\|/)+Users(?:\\\\|\\|/)+)"
79+
_NAME_CHAR = r"[^\s/\\\"'`\[\]:;|=,+*?<>(){}&]"
80+
_NAME = _NAME_CHAR + r"*(?:(?!\.)" + _NAME_CHAR + r")"
81+
# Own name at a boundary: not followed by more name characters (al vs alice).
82+
_NAME_END = r"(?!\.*(?:(?!\.)" + _NAME_CHAR + r"))"
7383
HOME_PATTERNS = (
74-
re.compile(r"(/Users/|/home/)" + _NAME),
75-
re.compile(r"([A-Za-z]:(?:\\\\|\\|/)+Users(?:\\\\|\\|/)+)" + _NAME),
84+
re.compile(_HOME_PREFIX + _NAME),
7685
re.compile(r"((?<![\w~])~)[A-Za-z_][A-Za-z0-9._-]*(?=/)"),
7786
)
7887
MAX_ENDED_TURNS = 64
@@ -179,20 +188,24 @@ def redact(text: str) -> str:
179188
return text
180189

181190

182-
def _own_home() -> Optional[Tuple[str, str]]:
183-
"""This machine's home directory and its <user> form, if it is a usual one."""
184-
home = os.path.expanduser("~")
185-
match = re.fullmatch(r"(/Users/|/home/|[A-Za-z]:\\Users\\)([^/\\]+)", home or "")
186-
return (home, match.group(1) + "<user>") if match else None
191+
@functools.lru_cache(maxsize=4)
192+
def _own_home_pattern(home: str) -> Optional["re.Pattern[str]"]:
193+
"""The basename of this machine's home directory after any home prefix.
194+
195+
Matched literally, so a name the generic pattern cannot take whole (one
196+
with spaces, quotes or parentheses) is still replaced in full.
197+
"""
198+
name = re.split(r"[/\\]", home.rstrip("/\\"))[-1]
199+
if not name or name in (".", ".."):
200+
return None
201+
return re.compile(_HOME_PREFIX + re.escape(name) + _NAME_END)
187202

188203

189204
def scrub_home(text: str) -> str:
190205
"""Replace the user name in home-directory paths with <user>."""
191-
own = _own_home()
192-
if own: # this machine's home first: catches a spaced name at the end of a string
193-
home, scrubbed = own
194-
for raw, repl in {home: scrubbed, json.dumps(home)[1:-1]: json.dumps(scrubbed)[1:-1]}.items():
195-
text = re.sub(re.escape(raw) + r"(?![^/\\\s\"'])", lambda _m, r=repl: r, text)
206+
own = _own_home_pattern(os.path.expanduser("~"))
207+
if own: # this machine's own name first: it may contain spaces
208+
text = own.sub(lambda m: m.group(1) + "<user>", text)
196209
for pattern in HOME_PATTERNS:
197210
text = pattern.sub(lambda m: m.group(1) + "<user>", text)
198211
return text

‎examples/coding-agents/hook-to-otlp/tests/test_core.py‎

Lines changed: 44 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -243,22 +243,54 @@ def test_opted_in_content_drops_the_user_name_from_home_paths(self):
243243
self.assertNotIn(name, text)
244244
self.assertIn("/Users/<user>/p/a.md", text)
245245

246-
def test_home_path_scrub_handles_spaced_and_tilde_names(self):
247-
cases = {
248-
"C:\\Users\\John Smith\\x": "C:\\Users\\<user>\\x",
249-
"/Users/Hank Smith/notes.txt": "/Users/<user>/notes.txt",
250-
"see /Users/alice and /tmp": "see /Users/<user> and /tmp",
251-
"~bob/x and ~/y": "~<user>/x and ~/y",
252-
}
246+
def assert_scrubs(self, cases):
253247
for raw, want in cases.items():
254248
self.assertEqual(emit.render_content(raw, 0), want)
255-
self.assertEqual(json.loads(emit.render_content({"p": raw}, 0))["p"], want)
249+
self.assertEqual(json.loads(emit.render_content({"p": raw}, 0))["p"], want, "JSON-escaped")
250+
251+
def test_home_path_scrub_replaces_only_the_name_component(self):
252+
# Regression: a name must not run on across spaces and swallow the command after it.
253+
with mock.patch.dict(os.environ, {"HOME": "/Users/someone"}):
254+
self.assert_scrubs({
255+
"cd /Users/alice && ls src/foo": "cd /Users/<user> && ls src/foo",
256+
"grep -rn TODO /home/bob --include=*.py && cat docs/readme.md":
257+
"grep -rn TODO /home/<user> --include=*.py && cat docs/readme.md",
258+
"ls /Users/alice;echo hi": "ls /Users/<user>;echo hi",
259+
"(see /Users/alice), then /home/bob.": "(see /Users/<user>), then /home/<user>.",
260+
"see /Users/alice and /tmp": "see /Users/<user> and /tmp",
261+
"/Users/john.smith/x and /Users/ann@corp/y": "/Users/<user>/x and /Users/<user>/y",
262+
"C:\\Users\\carol\\y and d:/Users/dave/z": "C:\\Users\\<user>\\y and d:/Users/<user>/z",
263+
"~bob/x and ~/y": "~<user>/x and ~/y",
264+
"/Users/<user>/x": "/Users/<user>/x",
265+
})
266+
267+
def test_spaced_user_name_is_scrubbed_for_this_machines_home(self):
256268
with mock.patch.dict(os.environ, {"HOME": "/Users/Jo Ann"}):
257-
text = emit.render_content({"cwd": "/Users/Jo Ann", "cmd": "cd /Users/Jo Ann && ls"}, 0)
258-
self.assertNotIn("Jo Ann", text)
259-
self.assertNotIn("Ann", text)
269+
self.assert_scrubs({
270+
"error at /Users/Jo Ann": "error at /Users/<user>",
271+
"failed in /Users/Jo Ann.": "failed in /Users/<user>.",
272+
"at /Users/Jo Ann, ok": "at /Users/<user>, ok",
273+
"cd /Users/Jo Ann && ls src/x": "cd /Users/<user> && ls src/x",
274+
"/Users/Jo Ann/notes.txt": "/Users/<user>/notes.txt",
275+
# Another account that only starts with the same name is not this home.
276+
"/Users/Jo Annabel/x": "/Users/<user> Annabel/x",
277+
})
278+
with mock.patch.dict(os.environ, {"HOME": "C:\\Users\\Jo Ann"}):
279+
self.assert_scrubs({
280+
"C:\\Users\\Jo Ann\\x": "C:\\Users\\<user>\\x",
281+
"c:/Users/Jo Ann/x": "c:/Users/<user>/x",
282+
"dir C:\\Users\\Jo Ann": "dir C:\\Users\\<user>",
283+
})
260284
with mock.patch.dict(os.environ, {"HOME": "/Users/al"}):
261-
self.assertEqual(emit.render_content("/Users/alice/x", 0), "/Users/<user>/x")
285+
self.assert_scrubs({"/Users/alice/x /Users/al/y /Users/al.": "/Users/<user>/x /Users/<user>/y /Users/<user>."})
286+
287+
def test_another_accounts_spaced_name_keeps_the_part_after_the_space(self):
288+
# Documented limitation: without this machine's home to go by, a space ends the name.
289+
with mock.patch.dict(os.environ, {"HOME": "/Users/someone"}):
290+
self.assert_scrubs({
291+
"/Users/Hank Smith/notes.txt": "/Users/<user> Smith/notes.txt",
292+
"C:\\Users\\John Smith\\x": "C:\\Users\\<user> Smith\\x",
293+
})
262294

263295
def test_default_timeout_is_short_when_the_send_is_inline(self):
264296
fork = os.fork

‎src/pages/docs/integrations/coding-agents/cursor.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ The project `.cursor/hooks.json` it writes registers the emitter on the observat
6565
}
6666
```
6767

68-
Each command is guarded with `2>/dev/null || true` so a missing emitter or `python3` can never return exit code 2, which Cursor treats as "block this action". Cursor runs each command with `$SHELL -c` (falling back to `/bin/sh`), so your login shell must be a POSIX shell such as zsh or bash. The parentheses are required: the IDE agent pipes the hook payload to stdin, but Cursor's headless agent host appends it to the command as a heredoc (`<command> <<'CURSOR_HOOK_EOF'`), and without the subshell that heredoc would reach `true` instead of `python3`. `-B` keeps `__pycache__` out of your repository. Project hooks run from the project root, so the paths start with `.cursor/`. User hooks run from `~/.cursor/` and use `./hooks/fi-hook-to-otlp/emit.py` instead (the installer handles this). Project hooks only run in a [trusted workspace](https://cursor.com/docs/hooks).
68+
Each command is guarded with `2>/dev/null || true` so a missing emitter or `python3` can never return exit code 2, which Cursor treats as "block this action". Cursor runs each command with `$SHELL -c` (falling back to `/bin/sh`), so your login shell must be a POSIX shell such as zsh or bash (fish reads the parentheses as command substitution). The parentheses are required: the IDE agent pipes the hook payload to stdin, but Cursor's headless agent host appends it to the command as a heredoc (`<command> <<'CURSOR_HOOK_EOF'`), and without the subshell that heredoc would reach `true` instead of `python3`. `-B` keeps `__pycache__` out of your repository. Project hooks run from the project root, so the paths start with `.cursor/`. User hooks run from `~/.cursor/` and use `./hooks/fi-hook-to-otlp/emit.py` instead (the installer handles this). Project hooks only run in a [trusted workspace](https://cursor.com/docs/hooks).
6969

7070
<Note>
7171
The emitter is deliberately not registered on permission hooks (`preToolUse`, `beforeShellExecution`, `beforeMCPExecution`, `beforeReadFile`, `subagentStart`). Tool timing comes from the `duration` Cursor reports in `postToolUse`, so tracing never takes part in approving or blocking an action. On `beforeSubmitPrompt` it always answers `{"continue": true}`. If you register it on a permission hook by mistake, it prints nothing: Cursor treats that as a failed hook and lets the action through, so it never approves or blocks anything.

‎src/pages/docs/integrations/coding-agents/hook-to-otlp.mdx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ By default the emitter exports structure and metadata only: ids, names, model, d
5959
| Paths inside prompts, tool input, and tool output (for example a Read tool's `file_path`) | **not exported** | exported as part of that content, with the user name in home-directory paths replaced by `<user>` (`/Users/<user>/project/README.md`) |
6060
| User email | **never exported** | **never exported** |
6161

62+
The user name is the one directory after `/Users/`, `/home/`, or `C:\Users\` (and the name in `~name/`); the text after it, such as the rest of a shell command, is kept as it was. A name with spaces is replaced in full when it is this machine's own home directory. For another account's name with spaces (for example in a log copied from another machine), only the part before the first space is replaced.
63+
6264
The emitter never reads files named in a payload (for example a transcript path) and never reads the app's local database or logs. It only sees the JSON the app passes to the hook.
6365

6466
<Warning>
@@ -84,7 +86,7 @@ Set these in the environment that starts the agent, or in `~/.config/fi-hook-to-
8486

8587
## Registering the hook
8688

87-
Every app page uses the same guarded command, so a missing emitter or a missing `python3` can never block the agent (many apps treat exit code 2 from a hook as "block this action"):
89+
Apps that export OpenTelemetry natively do not use this emitter and have no hook command; their pages set up the app's own telemetry export. Every app that is traced through hooks registers this same guarded command, so a missing emitter or a missing `python3` can never block the agent (many apps treat exit code 2 from a hook as "block this action"):
8890

8991
```bash
9092
(python3 -B <path-to>/emit.py <app> <EventName> 2>/dev/null || true)
@@ -96,7 +98,7 @@ Every app page uses the same guarded command, so a missing emitter or a missing
9698
- `-B` stops Python from writing `__pycache__` into your project.
9799
- The event name is passed explicitly, so the emitter works even if the app leaves it out of the payload.
98100

99-
This form needs a POSIX shell (`sh`, `bash`, `zsh`). On macOS and Linux, Cursor runs each hook command with `$SHELL -c` (falling back to `/bin/sh`). The commands and installers on these pages are not tested on native Windows; there, use WSL or write the equivalent for the shell your app runs hooks with, and keep it exiting 0 with no output on failure.
101+
This form needs a POSIX shell (`sh`, `bash`, `zsh`); fish, for example, reads the parentheses as command substitution. On macOS and Linux, Cursor runs each hook command with `$SHELL -c` (falling back to `/bin/sh`). The commands and installers on these pages are not tested on native Windows; there, use WSL or write the equivalent for the shell your app runs hooks with, and keep it exiting 0 with no output on failure.
100102

101103
## Safety for the host app
102104

0 commit comments

Comments
 (0)