use std::path::{Component, Path, PathBuf};
use super::INTERPRETER_WHITELIST;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScriptLawError {
BadName { name: String },
EmptyRun,
RelativeProgram { program: String },
InterpreterMissingScriptArg { interpreter: String },
RelativeScriptArg { interpreter: String, arg: String },
EscapedPluginRoot { path: String },
ScriptFileMissing { path: String },
ScriptFileNotExecutable { path: String },
}
impl std::fmt::Display for ScriptLawError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::BadName { name } => write!(f, "script tool name `{name}` is invalid"),
Self::EmptyRun => write!(f, "`run` must not be empty"),
Self::RelativeProgram { program } => write!(
f,
"`run[0]` must be an absolute path (got `{program}`); \
the only exception is the interpreter whitelist {INTERPRETER_WHITELIST:?} \
with an absolute script file argument"
),
Self::InterpreterMissingScriptArg { interpreter } => write!(
f,
"interpreter `{interpreter}` needs a script file argument \
(`-File`/`-f` for powershell/pwsh, `/c` for cmd) so its absolute path can be pinned"
),
Self::RelativeScriptArg { interpreter, arg } => write!(
f,
"script file argument `{arg}` of interpreter `{interpreter}` must be an absolute path"
),
Self::EscapedPluginRoot { path } => {
write!(f, "script path `{path}` escapes the plugin root")
}
Self::ScriptFileMissing { path } => write!(
f,
"script file `{path}` does not exist (must be a regular file)"
),
Self::ScriptFileNotExecutable { path } => write!(
f,
"script file `{path}` is not executable (chmod +x) — it runs directly as `run[0]`"
),
}
}
}
impl std::error::Error for ScriptLawError {}
fn interpreter_of(program: &str) -> Option<&'static str> {
let stem = Path::new(program)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_lowercase();
INTERPRETER_WHITELIST
.iter()
.find(|name| **name == stem)
.copied()
}
fn interpreter_script_arg_index(run: &[String]) -> Result<Option<usize>, ScriptLawError> {
let Some((program, args)) = run.split_first() else {
return Err(ScriptLawError::EmptyRun);
};
let Some(interpreter) = interpreter_of(program) else {
return Ok(None);
};
let flags: &[&str] = if interpreter == "cmd" {
&["/c"]
} else {
&["-file", "-f"]
};
for (offset, arg) in args.iter().enumerate() {
if flags.iter().any(|f| arg.eq_ignore_ascii_case(f)) {
let flag_index = offset + 1;
return run.get(flag_index + 1).map(|_| Some(flag_index + 1)).ok_or(
ScriptLawError::InterpreterMissingScriptArg {
interpreter: interpreter.to_string(),
},
);
}
}
Err(ScriptLawError::InterpreterMissingScriptArg {
interpreter: interpreter.to_string(),
})
}
pub fn script_file_index(run: &[String]) -> Result<usize, ScriptLawError> {
if run.is_empty() {
return Err(ScriptLawError::EmptyRun);
}
Ok(interpreter_script_arg_index(run)?.unwrap_or(0))
}
pub fn check_run_law(run: &[String]) -> Result<(), ScriptLawError> {
let Some((program, _)) = run.split_first() else {
return Err(ScriptLawError::EmptyRun);
};
match interpreter_script_arg_index(run)? {
Some(index) => {
let arg = &run[index];
if Path::new(arg).is_absolute() {
Ok(())
} else {
Err(ScriptLawError::RelativeScriptArg {
interpreter: program.clone(),
arg: arg.clone(),
})
}
}
None => {
if Path::new(program).is_absolute() {
Ok(())
} else {
Err(ScriptLawError::RelativeProgram {
program: program.clone(),
})
}
}
}
}
pub fn script_file_is_program(run: &[String]) -> Result<bool, ScriptLawError> {
Ok(interpreter_script_arg_index(run)?.is_none())
}
pub fn check_script_file_on_disk(
path: &Path,
require_executable: bool,
) -> Result<(), ScriptLawError> {
let missing = ScriptLawError::ScriptFileMissing {
path: path.display().to_string(),
};
let meta = std::fs::metadata(path).map_err(|_| missing.clone())?;
if !meta.is_file() {
return Err(missing);
}
#[cfg(unix)]
if require_executable {
use std::os::unix::fs::PermissionsExt;
if meta.permissions().mode() & 0o111 == 0 {
return Err(ScriptLawError::ScriptFileNotExecutable {
path: path.display().to_string(),
});
}
}
#[cfg(not(unix))]
let _ = require_executable;
Ok(())
}
fn normalize_lexical(path: &Path) -> Option<PathBuf> {
let mut out = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
if !out.pop() {
return None;
}
}
other => out.push(other.as_os_str()),
}
}
Some(out)
}
pub fn resolve_under_root(plugin_root: &Path, path: &str) -> Result<String, ScriptLawError> {
let escape = |p: &str| ScriptLawError::EscapedPluginRoot {
path: p.to_string(),
};
let root_norm = normalize_lexical(plugin_root).ok_or_else(|| escape(path))?;
let joined = if Path::new(path).is_absolute() {
PathBuf::from(path)
} else {
root_norm.join(path)
};
let normalized = normalize_lexical(&joined).ok_or_else(|| escape(path))?;
if normalized.starts_with(&root_norm) {
Ok(normalized.to_string_lossy().into_owned())
} else {
Err(escape(path))
}
}
pub fn pin_from_plugin_root(
run: &[String],
plugin_root: &Path,
) -> Result<Vec<String>, ScriptLawError> {
let index = script_file_index(run)?;
let mut pinned = run.to_vec();
pinned[index] = resolve_under_root(plugin_root, &run[index])?;
check_run_law(&pinned)?;
Ok(pinned)
}