1use super::EditError;
9use crate::engine::facet::LocalLocus;
10use crate::engine::resolve::regions::Frozen;
11use crate::engine::resolve::regions::hypothetical::ungranted_role;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Protected {
16 Credential,
17 TrustFile,
18 SystemFile,
19 Device,
20 RunsLater,
21}
22
23impl Protected {
24 pub(super) fn explain(self) -> &'static str {
25 match self {
26 Protected::Credential => {
27 "holds credentials, and safe-chains will not grant a credential store from a command. If \
28 you want commands there approved, write that grant into ~/.config/safe-chains.toml \
29 yourself"
30 }
31 Protected::TrustFile => {
32 "holds a file safe-chains or your agent reads its approvals from. A grant there would let \
33 an agent approve itself, so no grant can cover it"
34 }
35 Protected::SystemFile => "decides who may log in and what they may do, so no grant can cover it",
36 Protected::Device => "is a raw device, not a folder, so safe-chains will not grant it from a command",
37 Protected::RunsLater => {
38 "is, or holds, settings or programs that run later without anyone asking: a coding agent's \
39 settings, a shell or login startup file, or a folder on PATH. A grant there would let an agent \
40 change what runs next, so safe-chains will not make it from a command"
41 }
42 }
43 }
44}
45
46pub(crate) const AGENT_COMMANDS: &[&str] = &[
50 "agy", "aider", "amazon-q", "amp", "antigravity", "claude", "cline", "codex", "continue", "copilot", "crush", "cursor", "cursor-agent",
51 "devin", "droid", "gemini", "goose", "gptme", "grok", "kiro", "kiro-cli", "openhands", "opencode", "plandex", "q", "qwen", "roo",
52];
53
54pub(super) fn check_entry_name(name: &str) -> Result<(), EditError> {
55 if AGENT_COMMANDS.contains(&name) {
56 return Err(EditError::RunsAnAgent(name.to_string()));
57 }
58 Ok(())
59}
60
61pub(super) fn normalize_path(raw: &str) -> Result<String, EditError> {
64 let raw = raw.trim();
65 let home = crate::process_home::var().map_err(|_| EditError::NoHome)?;
66 let home = home.trim_end_matches('/');
67 let absolute = if raw == "~" {
68 home.to_string()
69 } else if let Some(rest) = raw.strip_prefix("~/") {
70 format!("{home}/{rest}")
71 } else if raw.starts_with('/') {
72 raw.to_string()
73 } else if raw.is_empty() || raw.starts_with('~') || raw.starts_with('$') {
74 return Err(EditError::NotAbsolute(raw.to_string()));
75 } else {
76 let cwd = std::env::current_dir().map_err(|e| EditError::Unreadable(e.to_string()))?;
77 format!("{}/{raw}", cwd.to_string_lossy())
78 };
79 let mut parts: Vec<&str> = Vec::new();
80 for part in absolute.split('/') {
81 match part {
82 "" | "." => {}
83 ".." => {
84 parts.pop();
85 }
86 other => parts.push(other),
87 }
88 }
89 let joined = format!("/{}", parts.join("/"));
90 Ok(match joined.strip_prefix(home) {
91 Some("") => "~".to_string(),
92 Some(rest) if rest.starts_with('/') => format!("~{rest}"),
93 _ => joined,
94 })
95}
96
97pub(super) fn check_grant_path(path: &str) -> Result<(), EditError> {
99 if path.contains(['*', '?', '[']) {
100 return Err(EditError::Glob(path.to_string()));
101 }
102 let home = crate::process_home::var().unwrap_or_default();
103 if path == "/" || path == "~" || home.starts_with(&format!("{path}/")) {
104 return Err(EditError::TooBroad(path.to_string()));
105 }
106 let role = ungranted_role(path);
107 let protected = if role.reads_secret {
108 Some(Protected::Credential)
109 } else if role.frozen != Frozen::Nothing {
110 Some(Protected::TrustFile)
111 } else if role.write_locus >= LocalLocus::Device {
112 Some(Protected::Device)
113 } else if role.write_locus >= LocalLocus::SystemIntegrity {
114 Some(Protected::SystemFile)
115 } else if runs_later(path) {
116 Some(Protected::RunsLater)
117 } else {
118 None
119 };
120 match protected {
121 Some(why) => Err(EditError::Protected(path.to_string(), why)),
122 None => Ok(()),
123 }
124}
125
126const HOME_RUNS_LATER: &[&str] = &[
131 ".claude", ".claude.json", ".codex", ".gemini", ".cursor", ".qwen", ".factory", ".copilot", ".grok", ".aider.conf.yml", ".continue",
132 ".config/opencode", ".config/goose", ".kiro", ".aws/amazonq", ".zshrc", ".zshenv", ".zprofile", ".zlogin", ".bashrc", ".bash_profile",
133 ".bash_login", ".profile", ".config/fish", ".gitconfig", ".config/git", ".npmrc", ".cargo", ".local/bin", "bin", ".config/systemd",
134 ".config/autostart", "Library/LaunchAgents",
135];
136const SYSTEM_RUNS_LATER: &[&str] = &[
137 "/Library/LaunchAgents", "/Library/LaunchDaemons", "/usr/local/bin", "/usr/local/sbin", "/opt/homebrew", "/usr/bin", "/bin",
138 "/usr/sbin", "/sbin", "/etc/profile", "/etc/zshrc", "/etc/zprofile", "/etc/bashrc", "/etc/paths", "/etc/paths.d", "/etc/cron.d",
139 "/etc/crontab", "/etc/systemd", "/etc/xdg/autostart", "/etc/launchd.conf",
140];
141
142fn runs_later(path: &str) -> bool {
146 let home = crate::process_home::var().unwrap_or_default();
147 let absolute = |p: &str| match p.strip_prefix('~') {
148 Some(rest) => format!("{}{rest}", home.trim_end_matches('/')),
149 None => p.to_string(),
150 };
151 let granted = absolute(path).to_ascii_lowercase();
152 let on_path = std::env::var("PATH").unwrap_or_default();
153 let places = HOME_RUNS_LATER
154 .iter()
155 .map(|p| format!("{}/{p}", home.trim_end_matches('/')))
156 .chain(SYSTEM_RUNS_LATER.iter().map(|p| (*p).to_string()))
157 .chain(on_path.split(':').filter(|p| p.starts_with('/')).map(String::from));
158 places.map(|p| p.trim_end_matches('/').to_ascii_lowercase()).filter(|p| !p.is_empty()).any(|place| {
159 let inside = granted == place || granted.starts_with(&format!("{place}/"));
160 let above = place
161 .strip_prefix(&format!("{granted}/"))
162 .is_some_and(|below| !below.split('/').any(|c| c.starts_with('.')));
163 inside || above
164 })
165}
166
167pub(super) fn check_spelling(command: &str, entry: &crate::suggest::GeneratedEntry) -> Result<(), EditError> {
174 let lower = entry.name.to_ascii_lowercase();
175 let lowered = command.replacen(&entry.name, &lower, 1);
176 let unknown_in_lower_case = match crate::suggest::analyze(&lowered) {
177 crate::suggest::Outcome::Generated { entries, .. } => entries.iter().any(|e| e.name == lower),
178 _ => false,
179 };
180 if lower != entry.name && !unknown_in_lower_case || crate::suggest::is_known(&lower) {
181 return Err(EditError::BuiltIn(vec![entry.name.clone()]));
182 }
183 check_entry_name(&lower)?;
184 let plain = entry.name.starts_with(|c: char| c.is_ascii_alphanumeric())
185 && entry.name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-'));
186 if !plain {
187 return Err(EditError::OddName(entry.name.clone()));
188 }
189 let words = shell_words::split(command).unwrap_or_default();
190 for (at, word) in words.iter().enumerate() {
191 let names_it = word == &entry.name || word.ends_with(&format!("/{}", entry.name));
192 if !names_it || at > 0 && !matches!(words[at - 1].as_str(), "|" | "&&" | "||" | ";") {
193 continue;
194 }
195 if word.contains('/') {
196 return Err(EditError::PathSpelled(word.clone()));
197 }
198 let rest = &words[at + 1..];
199 let hidden = rest.first().is_some_and(|w| w.starts_with('-'))
200 && rest
201 .iter()
202 .take_while(|w| !matches!(w.as_str(), "|" | "&&" | "||" | ";"))
203 .any(|w| crate::suggest::is_sub_word(w));
204 if hidden && entry.subs.is_empty() {
205 let sub = rest.iter().find(|w| crate::suggest::is_sub_word(w)).cloned().unwrap_or_default();
206 return Err(EditError::SubAfterFlags(entry.name.clone(), sub));
207 }
208 }
209 Ok(())
210}