1use std::path::{Path, PathBuf};
2
3use serde::Deserialize;
4use serde_json::{Value, json};
5
6use super::{HookFormat, HookInput, HookResponse, InstallOutcome, ParseError, Target, allow_reason};
7use crate::verdict::Verdict;
8
9pub struct CursorTarget;
10
11impl Target for CursorTarget {
12 fn name(&self) -> &'static str {
13 "cursor"
14 }
15
16 fn display_name(&self) -> &'static str {
17 "Cursor CLI"
18 }
19
20 fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
21 vec![home.join(".cursor")]
22 }
23
24 fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
25 let dir = home.join(".cursor");
26 if !dir.exists() {
27 return Ok(InstallOutcome::Skipped {
28 reason: format!("~/.cursor not found at {} (Cursor not installed for this user)", dir.display()),
29 });
30 }
31
32 let path = dir.join("hooks.json");
33 let binary = "safe-chains hook cursor";
34
35 if path.exists() {
36 let contents = std::fs::read_to_string(&path).map_err(|e| format!("Could not read {}: {e}", path.display()))?;
37 let mut settings: Value = serde_json::from_str(&contents).map_err(|e| format!("Could not parse {}: {e}", path.display()))?;
38
39 if has_safe_chains_hook(&settings) {
40 return Ok(InstallOutcome::AlreadyConfigured { path });
41 }
42
43 add_hook(&mut settings, binary).map_err(|e| format!("{}: {e}", path.display()))?;
44 let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
45 std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
46 Ok(InstallOutcome::Installed { path })
47 } else {
48 let mut settings = json!({"version": 1});
49 add_hook(&mut settings, binary).map_err(|e| format!("{}: {e}", path.display()))?;
50 let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
51 std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
52 Ok(InstallOutcome::Installed { path })
53 }
54 }
55
56 fn hook_format(&self) -> Option<&dyn HookFormat> {
57 Some(&CursorHookFormat)
58 }
59}
60
61struct CursorHookFormat;
62
63impl CursorHookFormat {
64 const SHELL_EVENT: &'static str = "beforeShellExecution";
66}
67
68#[derive(Deserialize)]
69struct CursorHookEnvelope {
70 command: String,
71 #[serde(default)]
79 hook_event_name: Option<String>,
80 #[serde(default)]
81 cwd: Option<String>,
82 #[serde(default)]
83 workspace_roots: Vec<String>,
84}
85
86impl HookFormat for CursorHookFormat {
87 fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
88 let mut envelope: CursorHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
89 if let Some(event) = envelope.hook_event_name.as_deref()
93 && event != Self::SHELL_EVENT
94 {
95 return Err(ParseError { message: format!("not a shell event: {event}") });
96 }
97 Ok(HookInput {
98 command: envelope.command,
99 cwd: envelope.cwd,
100 root: (!envelope.workspace_roots.is_empty()).then(|| envelope.workspace_roots.swap_remove(0)),
102 session_id: None,
104 permission_mode: None,
105 })
106 }
107
108 fn decision_pointer(&self) -> &'static str {
109 "/permission" }
111
112 fn render_response(&self, verdict: Verdict) -> HookResponse {
113 if verdict.is_allowed() {
114 let reason = allow_reason(verdict);
115 let body = json!({
120 "permission": "allow",
121 "agent_message": reason,
122 });
123 HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
124 } else {
125 HookResponse { stdout: String::new(), exit_code: 0 }
126 }
127 }
128
129 fn gated_policy(&self) -> super::GatedPolicy {
134 super::GatedPolicy::Deny
135 }
136
137 fn render_deny(&self, reason: &str) -> HookResponse {
138 let body = json!({
139 "permission": "deny",
140 "user_message": reason,
141 "agent_message": reason,
142 });
143 HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
144 }
145}
146
147fn hook_entry(binary: &str) -> Value {
148 json!({
149 "command": binary,
150 "timeout": 30,
151 })
152}
153
154fn has_safe_chains_hook(settings: &Value) -> bool {
155 settings
156 .get("hooks")
157 .and_then(|h| h.get("beforeShellExecution"))
158 .and_then(|arr| arr.as_array())
159 .is_some_and(|entries| {
160 entries
161 .iter()
162 .any(|entry| entry.get("command").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains("safe-chains")))
163 })
164}
165
166fn add_hook(settings: &mut Value, binary: &str) -> Result<(), String> {
167 if let Some(obj) = settings.as_object_mut()
174 && !obj.contains_key("version")
175 {
176 obj.insert("version".to_string(), json!(1));
177 }
178 super::append_hook_entry(settings, "hooks", "beforeShellExecution", hook_entry(binary))
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184 use crate::verdict::SafetyLevel;
185
186 fn target() -> CursorTarget {
187 CursorTarget
188 }
189
190 #[test]
191 fn install_no_cursor_dir_skips() {
192 let dir = tempfile::tempdir().unwrap();
193 let outcome = target().install(dir.path()).unwrap();
194 assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
195 }
196
197 #[test]
198 fn install_creates_hooks_file() {
199 let dir = tempfile::tempdir().unwrap();
200 std::fs::create_dir(dir.path().join(".cursor")).unwrap();
201 let outcome = target().install(dir.path()).unwrap();
202 assert!(matches!(outcome, InstallOutcome::Installed { .. }));
203 let contents = std::fs::read_to_string(dir.path().join(".cursor/hooks.json")).unwrap();
204 let settings: Value = serde_json::from_str(&contents).unwrap();
205 assert_eq!(settings.get("version").and_then(|v| v.as_u64()), Some(1));
206 assert!(has_safe_chains_hook(&settings));
207 }
208
209 #[test]
210 fn install_uses_subcommand_invocation() {
211 let dir = tempfile::tempdir().unwrap();
212 std::fs::create_dir(dir.path().join(".cursor")).unwrap();
213 target().install(dir.path()).unwrap();
214 let contents = std::fs::read_to_string(dir.path().join(".cursor/hooks.json")).unwrap();
215 assert!(contents.contains("safe-chains hook cursor"));
216 }
217
218 #[test]
219 fn install_idempotent() {
220 let dir = tempfile::tempdir().unwrap();
221 std::fs::create_dir(dir.path().join(".cursor")).unwrap();
222 target().install(dir.path()).unwrap();
223 let outcome = target().install(dir.path()).unwrap();
224 assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
225 }
226
227 #[test]
228 fn install_preserves_existing_hooks() {
229 let dir = tempfile::tempdir().unwrap();
230 let cursor_dir = dir.path().join(".cursor");
231 std::fs::create_dir(&cursor_dir).unwrap();
232 std::fs::write(
233 cursor_dir.join("hooks.json"),
234 r#"{"version": 1, "hooks": {"afterFileEdit": [{"command": "format-it", "timeout": 30}]}}"#,
235 )
236 .unwrap();
237 target().install(dir.path()).unwrap();
238 let contents = std::fs::read_to_string(cursor_dir.join("hooks.json")).unwrap();
239 let settings: Value = serde_json::from_str(&contents).unwrap();
240 assert!(has_safe_chains_hook(&settings));
241 assert!(
242 settings.pointer("/hooks/afterFileEdit").and_then(|a| a.as_array()).is_some_and(|a| !a.is_empty()),
243 "existing afterFileEdit hook must be preserved"
244 );
245 }
246
247 const CURSOR_DOCS_SAMPLE: &str = r#"{
251 "conversation_id": "abc-123",
252 "generation_id": "gen-456",
253 "model": "claude-sonnet-4-5",
254 "hook_event_name": "beforeShellExecution",
255 "cursor_version": "2.0.43",
256 "workspace_roots": ["/Users/me/project"],
257 "user_email": "me@example.com",
258 "transcript_path": "/Users/me/.cursor/transcripts/abc.json",
259 "command": "ls -la",
260 "cwd": "/Users/me/project",
261 "sandbox": false
262 }"#;
263
264 #[test]
275 fn parse_input_abstains_on_a_foreign_hook_event() {
276 for event in ["beforeReadFile", "afterFileEdit", "beforeSubmitPrompt", "stop"] {
277 let envelope = format!(r#"{{"hook_event_name":"{event}","command":"rm -rf /","workspace_roots":["/w"]}}"#);
278 assert!(CursorHookFormat.parse_input(&envelope).is_err(), "decided on a {event} envelope");
279 }
280
281 let shell = r#"{"hook_event_name":"beforeShellExecution","command":"ls","workspace_roots":["/w"]}"#;
283 assert_eq!(CursorHookFormat.parse_input(shell).unwrap().command, "ls");
284
285 let no_event = r#"{"command":"ls","workspace_roots":["/w"]}"#;
288 assert_eq!(CursorHookFormat.parse_input(no_event).unwrap().command, "ls");
289 }
290
291 #[test]
292 fn parse_input_extracts_top_level_command() {
293 let parsed = CursorHookFormat.parse_input(CURSOR_DOCS_SAMPLE).unwrap();
294 assert_eq!(parsed.command, "ls -la");
295 assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
296 }
297
298 #[test]
299 fn parse_input_rejects_garbage() {
300 assert!(CursorHookFormat.parse_input("not json").is_err());
301 assert!(CursorHookFormat.parse_input("{}").is_err());
302 }
303
304 #[test]
305 fn parse_input_takes_the_project_root_from_workspace_roots() {
306 let stdin = r#"{"command": "ls", "cwd": "/w/p/sub", "workspace_roots": ["/w/p", "/w/other"]}"#;
307 let parsed = CursorHookFormat.parse_input(stdin).unwrap();
308 assert_eq!(parsed.cwd.as_deref(), Some("/w/p/sub"));
309 assert_eq!(parsed.root.as_deref(), Some("/w/p"), "first workspace root");
310 let bare = CursorHookFormat.parse_input(r#"{"command": "ls"}"#).unwrap();
312 assert_eq!(bare.root, None);
313 }
314
315 #[test]
316 fn render_response_uses_permission_key_not_decision() {
317 let r = CursorHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
321 let v: Value = serde_json::from_str(&r.stdout).unwrap();
322 assert_eq!(v.get("permission").and_then(|s| s.as_str()), Some("allow"));
323 assert!(v.get("decision").is_none());
324 assert!(v.get("permissionDecision").is_none());
325 }
326
327 #[test]
328 fn render_response_includes_agent_message() {
329 let r = CursorHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
330 let v: Value = serde_json::from_str(&r.stdout).unwrap();
331 assert!(v.get("agent_message").and_then(|s| s.as_str()).is_some());
332 }
333
334 #[test]
335 fn render_response_deny_emits_empty_body() {
336 let r = CursorHookFormat.render_response(Verdict::Denied);
338 assert_eq!(r.stdout, "");
339 }
340
341 #[test]
342 fn cursor_is_a_deny_harness() {
343 assert_eq!(CursorHookFormat.gated_policy(), super::super::GatedPolicy::Deny);
346 }
347
348 #[test]
349 fn render_deny_emits_permission_deny_with_message() {
350 let r = CursorHookFormat.render_deny("safe-chains blocked this: not on the allowlist");
351 let v: Value = serde_json::from_str(&r.stdout).unwrap();
352 assert_eq!(v.get("permission").and_then(|s| s.as_str()), Some("deny"));
353 assert_eq!(v.get("user_message").and_then(|s| s.as_str()), Some("safe-chains blocked this: not on the allowlist"),);
355 assert!(v.get("agent_message").and_then(|s| s.as_str()).is_some());
356 assert!(v.get("permissionDecision").is_none());
357 }
358}