Skip to main content

lean_ctx_cli/cli/
harden.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::path::PathBuf;
3
4pub fn run(args: &[String]) {
5    if args.iter().any(|a| a == "--help" || a == "-h") {
6        print_help();
7        return;
8    }
9
10    let undo = args.iter().any(|a| a == "--undo");
11    let level = if args.iter().any(|a| a == "--hard") {
12        "hard"
13    } else {
14        "soft"
15    };
16
17    if undo {
18        undo_harden();
19    } else {
20        apply_harden(level);
21    }
22}
23
24fn print_help() {
25    println!("lean-ctx harden — tighten IDE security by denying native Read/Grep/Glob");
26    println!();
27    println!("USAGE:");
28    println!("    lean-ctx harden [OPTIONS]");
29    println!();
30    println!("OPTIONS:");
31    println!("    --hard     Replace mode: deny native tools across all IDEs");
32    println!("    --undo     Revert all harden changes");
33    println!("    --help     Show this help message");
34}
35
36fn apply_harden(level: &str) {
37    println!("lean-ctx harden (level: {level})");
38    println!();
39
40    if level == "hard" {
41        println!("  Hard mode = Replace mode: denying native Read/Grep/Glob across all IDEs.");
42        println!();
43        // Replace is opt-in since it stopped being a default: record the
44        // choice so setup, every hook refresh and the runtime deny hook see it.
45        if let Err(e) = lean_ctx::core::config::setter::set_by_key("hook_mode", "replace") {
46            eprintln!("  Could not set hook_mode = \"replace\": {e}");
47            return;
48        }
49        let opts = crate::setup::SetupOptions {
50            non_interactive: true,
51            yes: true,
52            fix: true,
53            ..Default::default()
54        };
55        if let Err(e) = crate::setup::run_setup_with_options(&opts) {
56            eprintln!("  Setup error: {e}");
57        }
58        println!();
59        println!("Replace mode active. All native tools denied — use ctx_* MCP tools.");
60        println!("Undo with: lean-ctx harden --undo");
61        return;
62    }
63
64    let mut applied = Vec::new();
65
66    if set_env_in_mcp_configs() {
67        applied.push("Set LEAN_CTX_HARDEN=1 in MCP configs");
68    }
69
70    match cleanup_claude_stale_bash_deny() {
71        Ok(true) => applied.push("Claude Code: removed stale Bash from permissions.deny (GH #799)"),
72        Ok(false) => {}
73        Err(error) => eprintln!("  [ERROR] {error}"),
74    }
75
76    if applied.is_empty() {
77        println!("  Nothing to harden (no supported editors detected).");
78    } else {
79        println!();
80        for item in &applied {
81            println!("  [OK] {item}");
82        }
83        println!();
84        println!("Harden active. Native Read/Grep will be denied (except after Edit).");
85        println!("Undo with: lean-ctx harden --undo");
86    }
87}
88
89fn undo_harden() {
90    println!("lean-ctx harden --undo");
91    println!();
92
93    let mut errors = remove_env_from_mcp_configs();
94    if let Err(error) = remove_claude_permissions_deny() {
95        errors.push(error);
96    }
97    // Undo `harden --hard`: back to the default mode (Hybrid), so the deny
98    // hooks stand down and the next refresh renders non-denying artifacts.
99    if lean_ctx::core::config::Config::load().hook_mode_override()
100        == Some(lean_ctx_hooks::hooks::HookMode::Replace)
101        && let Err(error) = lean_ctx::core::config::setter::set_by_key("hook_mode", "auto")
102    {
103        errors.push(format!("could not reset hook_mode: {error}"));
104    }
105
106    if errors.is_empty() {
107        println!("  [OK] Harden deactivated. Native tools allowed again.");
108    } else {
109        for error in &errors {
110            eprintln!("  [ERROR] {error}");
111        }
112        eprintln!("  Harden could not be fully deactivated.");
113    }
114}
115
116fn set_env_in_mcp_configs() -> bool {
117    let targets = discover_mcp_configs();
118    let mut any_set = false;
119
120    for path in targets {
121        if let Ok(content) = std::fs::read_to_string(&path)
122            && let Ok(mut json) = lean_ctx::core::jsonc::parse_jsonc(&content)
123            && let Some(servers) = find_lean_ctx_server_mut(&mut json)
124        {
125            let env = servers
126                .as_object_mut()
127                .and_then(|s| s.get_mut("env"))
128                .and_then(|e| e.as_object_mut());
129
130            if let Some(env_map) = env {
131                env_map.insert(
132                    "LEAN_CTX_HARDEN".to_string(),
133                    serde_json::Value::String("1".to_string()),
134                );
135            } else if let Some(server_obj) = servers.as_object_mut() {
136                let mut env_map = serde_json::Map::new();
137                env_map.insert(
138                    "LEAN_CTX_HARDEN".to_string(),
139                    serde_json::Value::String("1".to_string()),
140                );
141                server_obj.insert("env".to_string(), serde_json::Value::Object(env_map));
142            }
143
144            match serde_json::to_string_pretty(&json)
145                .map_err(|error| format!("cannot serialize {}: {error}", path.display()))
146                .and_then(|out| write_json_config(&path, &out))
147            {
148                Ok(()) => {
149                    any_set = true;
150                    println!("  [OK] {}", path.display());
151                }
152                Err(error) => eprintln!("  [ERROR] {error}"),
153            }
154        }
155    }
156    any_set
157}
158
159fn remove_env_from_mcp_configs() -> Vec<String> {
160    let mut errors = Vec::new();
161
162    for path in discover_mcp_configs() {
163        if let Ok(content) = std::fs::read_to_string(&path)
164            && let Ok(mut json) = lean_ctx::core::jsonc::parse_jsonc(&content)
165            && let Some(servers) = find_lean_ctx_server_mut(&mut json)
166            && let Some(env) = servers
167                .as_object_mut()
168                .and_then(|s| s.get_mut("env"))
169                .and_then(|e| e.as_object_mut())
170        {
171            env.remove("LEAN_CTX_HARDEN");
172            if let Err(error) = serde_json::to_string_pretty(&json)
173                .map_err(|error| format!("cannot serialize {}: {error}", path.display()))
174                .and_then(|out| write_json_config(&path, &out))
175            {
176                errors.push(error);
177            }
178        }
179    }
180
181    errors
182}
183
184/// Remove stale "Bash" from Claude Code's `permissions.deny` (GH #799).
185///
186/// Older versions added "Bash" here, which blocks ALL bash usage globally —
187/// including plugin commands (e.g. codex-companion). The PreToolUse hook
188/// (`lean-ctx hook deny`) already blocks agent-level native Bash, so the
189/// permissions.deny entry is unnecessary and harmful.
190fn cleanup_claude_stale_bash_deny() -> Result<bool, String> {
191    let Some(home) = dirs::home_dir() else {
192        return Ok(false);
193    };
194    let settings_path = home.join(".claude").join("settings.json");
195    if !settings_path.exists() {
196        return Ok(false);
197    }
198
199    let Ok(content) = std::fs::read_to_string(&settings_path) else {
200        return Ok(false);
201    };
202    let Ok(mut json) = lean_ctx::core::jsonc::parse_jsonc(&content) else {
203        return Ok(false);
204    };
205
206    let removed = if let Some(deny) = json
207        .pointer_mut("/permissions/deny")
208        .and_then(|d| d.as_array_mut())
209    {
210        let before = deny.len();
211        deny.retain(|v| v.as_str() != Some("Bash"));
212        deny.len() < before
213    } else {
214        false
215    };
216
217    if removed {
218        serde_json::to_string_pretty(&json)
219            .map_err(|error| format!("cannot serialize {}: {error}", settings_path.display()))
220            .and_then(|out| write_json_config(&settings_path, &out))?;
221    }
222    Ok(removed)
223}
224
225fn remove_claude_permissions_deny() -> Result<(), String> {
226    let Some(home) = dirs::home_dir() else {
227        return Ok(());
228    };
229    let settings_path = home.join(".claude").join("settings.json");
230    if !settings_path.exists() {
231        return Ok(());
232    }
233
234    let Ok(content) = std::fs::read_to_string(&settings_path) else {
235        return Ok(());
236    };
237    let Ok(mut json) = lean_ctx::core::jsonc::parse_jsonc(&content) else {
238        return Ok(());
239    };
240
241    if let Some(deny) = json
242        .pointer_mut("/permissions/deny")
243        .and_then(|d| d.as_array_mut())
244    {
245        deny.retain(|v| v.as_str() != Some("Bash"));
246    }
247
248    serde_json::to_string_pretty(&json)
249        .map_err(|error| format!("cannot serialize {}: {error}", settings_path.display()))
250        .and_then(|out| write_json_config(&settings_path, &out))
251}
252
253fn write_json_config(path: &std::path::Path, content: &str) -> Result<(), String> {
254    lean_ctx::config_io::write_atomic(path, content)
255        .map_err(|error| format!("cannot write {}: {error}", path.display()))
256}
257
258fn discover_mcp_configs() -> Vec<PathBuf> {
259    let Some(home) = dirs::home_dir() else {
260        return Vec::new();
261    };
262
263    let candidates = [
264        home.join(".cursor").join("mcp.json"),
265        home.join(".claude.json"),
266        home.join(".codebuddy.json"),
267        home.join(".codeium")
268            .join("windsurf")
269            .join("mcp_config.json"),
270    ];
271
272    candidates.into_iter().filter(|p| p.exists()).collect()
273}
274
275fn find_lean_ctx_server_mut(json: &mut serde_json::Value) -> Option<&mut serde_json::Value> {
276    if let Some(servers) = json.get_mut("mcpServers")
277        && let Some(lctx) = servers.get_mut("lean-ctx")
278    {
279        return Some(lctx);
280    }
281    None
282}