use super::EditError;
use crate::engine::facet::LocalLocus;
use crate::engine::resolve::regions::Frozen;
use crate::engine::resolve::regions::hypothetical::ungranted_role;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Protected {
Credential,
TrustFile,
SystemFile,
Device,
RunsLater,
}
impl Protected {
pub(super) fn explain(self) -> &'static str {
match self {
Protected::Credential => {
"holds credentials, and safe-chains will not grant a credential store from a command. If \
you want commands there approved, write that grant into ~/.config/safe-chains.toml \
yourself"
}
Protected::TrustFile => {
"holds a file safe-chains or your agent reads its approvals from. A grant there would let \
an agent approve itself, so no grant can cover it"
}
Protected::SystemFile => "decides who may log in and what they may do, so no grant can cover it",
Protected::Device => "is a raw device, not a folder, so safe-chains will not grant it from a command",
Protected::RunsLater => {
"is, or holds, settings or programs that run later without anyone asking: a coding agent's \
settings, a shell or login startup file, or a folder on PATH. A grant there would let an agent \
change what runs next, so safe-chains will not make it from a command"
}
}
}
}
pub(crate) const AGENT_COMMANDS: &[&str] = &[
"agy", "aider", "amazon-q", "amp", "antigravity", "claude", "cline", "codex", "continue", "copilot", "crush", "cursor", "cursor-agent",
"devin", "droid", "gemini", "goose", "gptme", "grok", "kiro", "kiro-cli", "openhands", "opencode", "plandex", "q", "qwen", "roo",
];
pub(super) fn check_entry_name(name: &str) -> Result<(), EditError> {
if AGENT_COMMANDS.contains(&name) {
return Err(EditError::RunsAnAgent(name.to_string()));
}
Ok(())
}
pub(super) fn normalize_path(raw: &str) -> Result<String, EditError> {
let raw = raw.trim();
let home = crate::process_home::var().map_err(|_| EditError::NoHome)?;
let home = home.trim_end_matches('/');
let absolute = if raw == "~" {
home.to_string()
} else if let Some(rest) = raw.strip_prefix("~/") {
format!("{home}/{rest}")
} else if raw.starts_with('/') {
raw.to_string()
} else if raw.is_empty() || raw.starts_with('~') || raw.starts_with('$') {
return Err(EditError::NotAbsolute(raw.to_string()));
} else {
let cwd = std::env::current_dir().map_err(|e| EditError::Unreadable(e.to_string()))?;
format!("{}/{raw}", cwd.to_string_lossy())
};
let mut parts: Vec<&str> = Vec::new();
for part in absolute.split('/') {
match part {
"" | "." => {}
".." => {
parts.pop();
}
other => parts.push(other),
}
}
let joined = format!("/{}", parts.join("/"));
Ok(match joined.strip_prefix(home) {
Some("") => "~".to_string(),
Some(rest) if rest.starts_with('/') => format!("~{rest}"),
_ => joined,
})
}
pub(super) fn check_grant_path(path: &str) -> Result<(), EditError> {
if path.contains(['*', '?', '[']) {
return Err(EditError::Glob(path.to_string()));
}
let home = crate::process_home::var().unwrap_or_default();
if path == "/" || path == "~" || home.starts_with(&format!("{path}/")) {
return Err(EditError::TooBroad(path.to_string()));
}
let role = ungranted_role(path);
let protected = if role.reads_secret {
Some(Protected::Credential)
} else if role.frozen != Frozen::Nothing {
Some(Protected::TrustFile)
} else if role.write_locus >= LocalLocus::Device {
Some(Protected::Device)
} else if role.write_locus >= LocalLocus::SystemIntegrity {
Some(Protected::SystemFile)
} else if runs_later(path) {
Some(Protected::RunsLater)
} else {
None
};
match protected {
Some(why) => Err(EditError::Protected(path.to_string(), why)),
None => Ok(()),
}
}
const HOME_RUNS_LATER: &[&str] = &[
".claude", ".claude.json", ".codex", ".gemini", ".cursor", ".qwen", ".factory", ".copilot", ".grok", ".aider.conf.yml", ".continue",
".config/opencode", ".config/goose", ".kiro", ".aws/amazonq", ".zshrc", ".zshenv", ".zprofile", ".zlogin", ".bashrc", ".bash_profile",
".bash_login", ".profile", ".config/fish", ".gitconfig", ".config/git", ".npmrc", ".cargo", ".local/bin", "bin", ".config/systemd",
".config/autostart", "Library/LaunchAgents",
];
const SYSTEM_RUNS_LATER: &[&str] = &[
"/Library/LaunchAgents", "/Library/LaunchDaemons", "/usr/local/bin", "/usr/local/sbin", "/opt/homebrew", "/usr/bin", "/bin",
"/usr/sbin", "/sbin", "/etc/profile", "/etc/zshrc", "/etc/zprofile", "/etc/bashrc", "/etc/paths", "/etc/paths.d", "/etc/cron.d",
"/etc/crontab", "/etc/systemd", "/etc/xdg/autostart", "/etc/launchd.conf",
];
fn runs_later(path: &str) -> bool {
let home = crate::process_home::var().unwrap_or_default();
let absolute = |p: &str| match p.strip_prefix('~') {
Some(rest) => format!("{}{rest}", home.trim_end_matches('/')),
None => p.to_string(),
};
let granted = absolute(path).to_ascii_lowercase();
let on_path = std::env::var("PATH").unwrap_or_default();
let places = HOME_RUNS_LATER
.iter()
.map(|p| format!("{}/{p}", home.trim_end_matches('/')))
.chain(SYSTEM_RUNS_LATER.iter().map(|p| (*p).to_string()))
.chain(on_path.split(':').filter(|p| p.starts_with('/')).map(String::from));
places.map(|p| p.trim_end_matches('/').to_ascii_lowercase()).filter(|p| !p.is_empty()).any(|place| {
let inside = granted == place || granted.starts_with(&format!("{place}/"));
let above = place
.strip_prefix(&format!("{granted}/"))
.is_some_and(|below| !below.split('/').any(|c| c.starts_with('.')));
inside || above
})
}
pub(super) fn check_spelling(command: &str, entry: &crate::suggest::GeneratedEntry) -> Result<(), EditError> {
let lower = entry.name.to_ascii_lowercase();
let lowered = command.replacen(&entry.name, &lower, 1);
let unknown_in_lower_case = match crate::suggest::analyze(&lowered) {
crate::suggest::Outcome::Generated { entries, .. } => entries.iter().any(|e| e.name == lower),
_ => false,
};
if lower != entry.name && !unknown_in_lower_case || crate::suggest::is_known(&lower) {
return Err(EditError::BuiltIn(vec![entry.name.clone()]));
}
check_entry_name(&lower)?;
let plain = entry.name.starts_with(|c: char| c.is_ascii_alphanumeric())
&& entry.name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-'));
if !plain {
return Err(EditError::OddName(entry.name.clone()));
}
let words = shell_words::split(command).unwrap_or_default();
for (at, word) in words.iter().enumerate() {
let names_it = word == &entry.name || word.ends_with(&format!("/{}", entry.name));
if !names_it || at > 0 && !matches!(words[at - 1].as_str(), "|" | "&&" | "||" | ";") {
continue;
}
if word.contains('/') {
return Err(EditError::PathSpelled(word.clone()));
}
let rest = &words[at + 1..];
let hidden = rest.first().is_some_and(|w| w.starts_with('-'))
&& rest
.iter()
.take_while(|w| !matches!(w.as_str(), "|" | "&&" | "||" | ";"))
.any(|w| crate::suggest::is_sub_word(w));
if hidden && entry.subs.is_empty() {
let sub = rest.iter().find(|w| crate::suggest::is_sub_word(w)).cloned().unwrap_or_default();
return Err(EditError::SubAfterFlags(entry.name.clone(), sub));
}
}
Ok(())
}