mod adapter;
#[cfg(test)]
mod tests;
pub mod uv;
pub mod uv_pin;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::AtomicBool;
use std::time::Duration;
pub use adapter::{parse, version_of};
pub use uv::uv_download;
use super::download::Download;
use super::process::{self, Drained, Ended, MAX_STDOUT, RunDir, passed};
use super::{Choice, ExternalReport, NotScanned, Scanner, snyk_leftover, text};
use crate::env::{Env, Os};
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::local_settings::{LocalSettings, SkillSpectorSettings};
use crate::paths::SurjectionHome;
use crate::skills::{SkillFiles, content_hash};
use uv::PrivateUv;
pub const SCANNER: Scanner = Scanner::SkillSpector;
pub const VERSION: &str = "2.13.7";
pub const PYTHON: &str = "3.13";
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(600);
pub const MAX_TIMEOUT: Duration = Duration::from_secs(59 * 60);
const _: () = assert!(
MAX_TIMEOUT.as_secs() < process::STALE_RUN.as_secs()
&& PREPARE_TIMEOUT.as_secs() < process::STALE_RUN.as_secs()
);
pub const PREPARE_TIMEOUT: Duration = Duration::from_secs(30 * 60);
const PROBE_TIMEOUT: Duration = Duration::from_secs(60);
const PROBE_STDOUT: usize = 64 * 1024;
const MAX_PROGRESS_LINE: usize = 300;
pub const SCAN_ARGS: &[&str] = &[
"scan",
"--no-llm",
"--format",
"json",
"--fail-on-incomplete",
"--",
];
pub const PASSED_VARS: &[&str] = &[
"PATH",
"PATHEXT",
"SYSTEMROOT",
"SYSTEMDRIVE",
"WINDIR",
"COMSPEC",
"PROGRAMDATA",
"PROCESSOR_ARCHITECTURE",
"HOME",
"USERPROFILE",
"USERNAME",
"USER",
"LOGNAME",
"APPDATA",
"LOCALAPPDATA",
"XDG_CACHE_HOME",
"XDG_DATA_HOME",
"XDG_CONFIG_HOME",
"LANG",
"LC_ALL",
"HTTPS_PROXY",
"https_proxy",
"HTTP_PROXY",
"http_proxy",
"ALL_PROXY",
"all_proxy",
"NO_PROXY",
"no_proxy",
"SSL_CERT_FILE",
"SSL_CERT_DIR",
"REQUESTS_CA_BUNDLE",
"UV_CACHE_DIR",
"UV_PYTHON_INSTALL_DIR",
"UV_TOOL_DIR",
];
pub const TEMP_VARS: &[&str] = &["TEMP", "TMP", "TMPDIR"];
pub const SET_VARS: &[(&str, &str)] = &[
("PYTHONIOENCODING", "utf-8"),
("PYTHONUTF8", "1"),
("NO_COLOR", "1"),
("LANGSMITH_TRACING", "false"),
("LANGCHAIN_TRACING_V2", "false"),
];
pub fn child_env(env: &Env, tmp: &Path) -> Vec<(String, OsString)> {
let mut vars = passed(env, PASSED_VARS);
for name in TEMP_VARS {
vars.push(((*name).to_owned(), tmp.as_os_str().to_owned()));
}
for (name, value) in SET_VARS {
vars.push(((*name).to_owned(), (*value).into()));
}
vars
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UvSource {
System,
Private,
}
impl UvSource {
pub const fn as_str(self) -> &'static str {
match self {
UvSource::System => "system",
UvSource::Private => "private",
}
}
}
fn run_env(
env: &Env,
home: &SurjectionHome,
tmp: &Path,
source: Option<UvSource>,
) -> Vec<(String, OsString)> {
let mut vars = child_env(env, tmp);
if source == Some(UvSource::Private) {
vars.retain(|(name, _)| !name.to_ascii_uppercase().starts_with("UV_"));
vars.extend(uv::env_in(&uv::root(home)));
}
vars
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Settings {
pub enabled: bool,
pub timeout_secs: Option<u64>,
}
impl Settings {
pub fn timeout(&self) -> Duration {
self.timeout_secs
.filter(|secs| *secs > 0)
.map_or(DEFAULT_TIMEOUT, Duration::from_secs)
.min(MAX_TIMEOUT)
}
}
pub fn settings(fs: &dyn Fs, home: &SurjectionHome) -> Result<Settings, CoreError> {
let saved = LocalSettings::load(fs, &home.state_dir())?
.skillspector
.unwrap_or_default();
Ok(Settings {
enabled: saved.enabled == Some(true),
timeout_secs: saved.timeout_secs,
})
}
pub fn set_enabled(fs: &dyn Fs, home: &SurjectionHome, enabled: bool) -> Result<(), CoreError> {
let state = home.state_dir();
let mut settings = LocalSettings::load(fs, &state)?;
let mut scanner = settings.skillspector.take().unwrap_or_default();
scanner.enabled = Some(enabled);
settings.skillspector = (scanner != SkillSpectorSettings::default()).then_some(scanner);
settings.save(fs, &state)
}
pub fn wanted(settings: &Settings, choice: Choice) -> bool {
choice.wants(settings.enabled)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RuntimeKind {
Uvx,
Path,
}
impl RuntimeKind {
pub const fn as_str(self) -> &'static str {
match self {
RuntimeKind::Uvx => "uvx",
RuntimeKind::Path => "path",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Runtime {
pub kind: RuntimeKind,
pub program: PathBuf,
pub version: String,
pub uv: Option<UvSource>,
}
impl Runtime {
pub fn tested(&self) -> bool {
self.version == VERSION
}
pub fn note(&self) -> Option<String> {
(!self.tested()).then(|| untested_note(&self.version))
}
pub fn argv(&self, skill: &Path) -> Vec<OsString> {
let mut argv: Vec<OsString> = match self.kind {
RuntimeKind::Uvx => uvx_prefix(&self.program, true)
.into_iter()
.map(OsString::from)
.collect(),
RuntimeKind::Path => Vec::new(),
};
argv.extend(SCAN_ARGS.iter().map(OsString::from));
argv.push(skill.as_os_str().to_owned());
argv
}
pub fn command_line(&self) -> String {
let program = self.program.display().to_string();
match self.kind {
RuntimeKind::Uvx => {
let prefix = uvx_prefix(&self.program, false).join(" ");
format!("{program} {prefix}")
}
RuntimeKind::Path => program,
}
}
}
pub fn untested_note(version: &str) -> String {
format!("SkillSpector {version} is not tested with this Surjection (tested: {VERSION})")
}
fn uvx_prefix(program: &Path, offline: bool) -> Vec<String> {
let mut prefix = Vec::new();
if is_uv(program) {
prefix.extend(["tool".to_owned(), "run".to_owned()]);
}
if offline {
prefix.push("--offline".to_owned());
}
prefix.extend([
"--python".to_owned(),
PYTHON.to_owned(),
"--from".to_owned(),
format!("skillspector=={VERSION}"),
"skillspector".to_owned(),
]);
prefix
}
fn is_uv(program: &Path) -> bool {
program
.file_stem()
.is_some_and(|stem| stem.eq_ignore_ascii_case("uv"))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Availability {
Ready(Runtime),
NeedsPrepare {
uv: PathBuf,
source: UvSource,
},
NotAvailable,
}
impl Availability {
pub const fn as_str(&self) -> &'static str {
match self {
Availability::Ready(_) => "ready",
Availability::NeedsPrepare { .. } => "needs_prepare",
Availability::NotAvailable => "not_available",
}
}
pub fn runtime(&self) -> Option<&Runtime> {
match self {
Availability::Ready(runtime) => Some(runtime),
_ => None,
}
}
}
fn find_program(env: &Env, name: &str) -> Option<PathBuf> {
let path = env.var("PATH")?.to_string_lossy().into_owned();
let windows = env.os() == Os::Windows;
let separator = if windows { ';' } else { ':' };
let file = if windows {
format!("{name}.exe")
} else {
name.to_owned()
};
path.split(separator)
.map(|dir| Path::new(dir.trim().trim_matches('"')))
.filter(|dir| dir.is_absolute())
.map(|dir| dir.join(&file))
.find(|candidate| candidate.is_file())
}
fn find_system_uv(env: &Env) -> Option<PathBuf> {
find_program(env, "uvx").or_else(|| find_program(env, "uv"))
}
fn find_private_uv(env: &Env, home: &SurjectionHome) -> Option<PrivateUv> {
PrivateUv::for_env(env, home)
.ok()
.filter(|private| private.installed() && private.verify().is_ok())
}
pub fn find_uv(env: &Env, home: &SurjectionHome) -> Option<(PathBuf, UvSource)> {
if let Some(uv) = find_system_uv(env) {
return Some((uv, UvSource::System));
}
find_private_uv(env, home).map(|private| (private.uvx(), UvSource::Private))
}
fn probe(
env: &Env,
home: &SurjectionHome,
program: &Path,
source: Option<UvSource>,
args: &[String],
timeout: Duration,
) -> Result<String, String> {
let run = process::stage(home, &SkillFiles::new())?;
let mut command = Command::new(program);
command
.args(args)
.current_dir(&run.dir)
.env_clear()
.envs(run_env(env, home, &run.tmp, source));
let executed = process::execute(command, timeout, None, PROBE_STDOUT, None)?;
match executed.ended {
Ended::Exited(Some(0)) => Ok(executed
.stdout
.map(|drained| String::from_utf8_lossy(&drained.kept).into_owned())
.unwrap_or_default()),
Ended::Exited(code) => Err(format!(
"exit code {}: {}",
code.map_or_else(|| "none".to_owned(), |code| code.to_string()),
executed.last_stderr_line().unwrap_or_default()
)),
Ended::TimedOut => Err(format!("no answer in {} seconds", timeout.as_secs())),
Ended::Canceled => Err("canceled".to_owned()),
Ended::Failed(why) => Err(why),
}
}
fn path_runtime(env: &Env, home: &SurjectionHome) -> Option<Runtime> {
let program = find_program(env, "skillspector")?;
let stdout = probe(
env,
home,
&program,
None,
&["--version".to_owned()],
PROBE_TIMEOUT,
)
.ok()?;
let version = version_of(&stdout)?;
Some(Runtime {
kind: RuntimeKind::Path,
program,
version,
uv: None,
})
}
fn uvx_runtime(env: &Env, home: &SurjectionHome, uv: &Path, source: UvSource) -> Option<Runtime> {
let mut args = uvx_prefix(uv, true);
args.push("--version".to_owned());
let stdout = probe(env, home, uv, Some(source), &args, PROBE_TIMEOUT).ok()?;
Some(Runtime {
kind: RuntimeKind::Uvx,
program: uv.to_owned(),
version: version_of(&stdout).unwrap_or_else(|| VERSION.to_owned()),
uv: Some(source),
})
}
pub fn detect(env: &Env, home: &SurjectionHome) -> Availability {
let system = find_system_uv(env);
if let Some(uv) = &system
&& let Some(runtime) = uvx_runtime(env, home, uv, UvSource::System)
{
return Availability::Ready(runtime);
}
if let Some(runtime) = path_runtime(env, home) {
return Availability::Ready(runtime);
}
let private = find_private_uv(env, home);
if let Some(private) = &private
&& let Some(runtime) = uvx_runtime(env, home, &private.uvx(), UvSource::Private)
{
return Availability::Ready(runtime);
}
match (system, private) {
(Some(uv), _) => Availability::NeedsPrepare {
uv,
source: UvSource::System,
},
(None, Some(private)) => Availability::NeedsPrepare {
uv: private.uvx(),
source: UvSource::Private,
},
(None, None) => Availability::NotAvailable,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Status {
pub availability: Availability,
pub enabled: bool,
pub timeout: Duration,
pub snyk_installed: bool,
pub private_uv: Option<String>,
pub private_uv_present: bool,
pub setup_supported: bool,
}
pub fn status(env: &Env, fs: &dyn Fs, home: &SurjectionHome) -> Result<Status, CoreError> {
let settings = settings(fs, home)?;
let snyk_installed = snyk_leftover::present(fs, home)?;
let availability = detect(env, home);
let private = PrivateUv::for_env(env, home).ok();
Ok(Status {
availability,
enabled: settings.enabled,
timeout: settings.timeout(),
snyk_installed,
private_uv: private
.as_ref()
.filter(|private| private.installed())
.map(|private| private.version().to_owned()),
private_uv_present: uv::root(home).exists(),
setup_supported: private.is_some(),
})
}
pub fn required(env: &Env, fs: &dyn Fs, home: &SurjectionHome) -> Result<bool, CoreError> {
if !settings(fs, home)?.enabled {
return Ok(false);
}
Ok(matches!(detect(env, home), Availability::Ready(_)))
}
pub fn prepare(
env: &Env,
home: &SurjectionHome,
progress: &mut dyn FnMut(&str),
cancel: Option<&AtomicBool>,
) -> Result<Runtime, CoreError> {
let Some((uv, source)) = find_uv(env, home) else {
return Err(CoreError::new(
ErrorCode::ScannerUnavailable,
format!(
"uv is not on PATH, so there is nothing to prepare. {}",
setup_text(setup_supported(env, home))
),
));
};
prepare_with(env, home, uv, source, progress, cancel)
}
fn prepare_with(
env: &Env,
home: &SurjectionHome,
uv: PathBuf,
source: UvSource,
progress: &mut dyn FnMut(&str),
cancel: Option<&AtomicBool>,
) -> Result<Runtime, CoreError> {
let failed = |why: String| CoreError::new(ErrorCode::ScannerDownloadFailed, why);
let run = process::stage(home, &SkillFiles::new())
.map_err(|why| failed(format!("cannot prepare SkillSpector: {why}")))?;
let mut args = uvx_prefix(&uv, false);
args.push("--version".to_owned());
let mut command = Command::new(&uv);
command
.args(&args)
.current_dir(&run.dir)
.env_clear()
.envs(run_env(env, home, &run.tmp, Some(source)));
let mut on_line = |line: &str| {
let line = text::clean(line, MAX_PROGRESS_LINE);
if !line.is_empty() {
progress(&line);
}
};
let executed = process::execute(
command,
PREPARE_TIMEOUT,
cancel,
PROBE_STDOUT,
Some(&mut on_line),
)
.map_err(failed)?;
match executed.ended {
Ended::Exited(Some(0)) => {
let stdout = executed
.stdout
.map(|drained| String::from_utf8_lossy(&drained.kept).into_owned())
.unwrap_or_default();
Ok(Runtime {
kind: RuntimeKind::Uvx,
program: uv,
version: version_of(&stdout).unwrap_or_else(|| VERSION.to_owned()),
uv: Some(source),
})
}
Ended::Exited(code) => {
let how = code.map_or_else(
|| "uv was stopped by the system".to_owned(),
|code| format!("uv exited with code {code}"),
);
let detail = executed
.last_stderr_line()
.map(|line| format!(": {}", text::clean(&line, MAX_PROGRESS_LINE)))
.unwrap_or_default();
Err(failed(format!(
"uv could not download SkillSpector {VERSION} ({how}){detail}"
)))
}
Ended::TimedOut => Err(failed(format!(
"preparing SkillSpector did not finish in {} minutes",
PREPARE_TIMEOUT.as_secs() / 60
))),
Ended::Canceled => Err(CoreError::new(
ErrorCode::Canceled,
"preparing SkillSpector was canceled",
)),
Ended::Failed(why) => Err(failed(why)),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SetupStep<'a> {
Download { received: u64, total: u64 },
Prepare { line: &'a str },
}
pub fn setup(
env: &Env,
home: &SurjectionHome,
download: &dyn Download,
progress: &mut dyn FnMut(SetupStep<'_>),
cancel: Option<&AtomicBool>,
) -> Result<Runtime, CoreError> {
if let Some(uv) = find_system_uv(env) {
return prepare_with(
env,
home,
uv,
UvSource::System,
&mut |line| progress(SetupStep::Prepare { line }),
cancel,
);
}
if path_runtime(env, home).is_some() {
return Err(CoreError::new(
ErrorCode::ScannerUnavailable,
"SkillSpector is already set up (on PATH)",
));
}
let private = PrivateUv::for_env(env, home)?;
private.install(
download,
&mut |received, total| progress(SetupStep::Download { received, total }),
cancel,
)?;
prepare_with(
env,
home,
private.uvx(),
UvSource::Private,
&mut |line| progress(SetupStep::Prepare { line }),
cancel,
)
}
pub fn remove_private_uv(home: &SurjectionHome) -> Result<bool, CoreError> {
uv::remove_root(&uv::root(home))
}
#[allow(clippy::result_large_err)]
pub fn prepare_run(
env: &Env,
fs: &dyn Fs,
home: &SurjectionHome,
) -> Result<Runner, ExternalReport> {
let timeout = settings(fs, home)
.map_err(|err| {
ExternalReport::not_scanned(
SCANNER,
VERSION,
NotScanned::Failed,
Some(err.message().to_owned()),
)
})?
.timeout();
match detect(env, home) {
Availability::Ready(runtime) => Ok(Runner::new(runtime, timeout)),
Availability::NeedsPrepare { source, .. } => Err(ExternalReport::not_scanned(
SCANNER,
VERSION,
NotScanned::NotPrepared,
Some(match source {
UvSource::System => format!(
"uv is on PATH but SkillSpector {VERSION} is not downloaded yet; prepare \
it first (`surject scanner prepare`, or Prepare in Settings > Security)"
),
UvSource::Private => format!(
"SkillSpector {VERSION} is not downloaded yet; set it up first (`surject \
scanner setup`, or Set up in Settings > Security)"
),
}),
)),
Availability::NotAvailable => Err(ExternalReport::not_scanned(
SCANNER,
VERSION,
NotScanned::NotAvailable,
Some("neither uv nor skillspector is on PATH".to_owned()),
)),
}
}
#[derive(Debug, Clone)]
pub struct Runner {
runtime: Runtime,
timeout: Duration,
}
impl Runner {
pub fn new(runtime: Runtime, timeout: Duration) -> Self {
Self { runtime, timeout }
}
pub fn runtime(&self) -> &Runtime {
&self.runtime
}
pub fn timeout(&self) -> Duration {
self.timeout
}
pub fn scan_files(
&self,
env: &Env,
home: &SurjectionHome,
files: &SkillFiles,
cancel: Option<&AtomicBool>,
) -> ExternalReport {
let started = std::time::Instant::now();
let hash = content_hash(files);
let mut report = match process::stage(home, files) {
Ok(run) => self.run(env, home, &run, cancel),
Err(why) => ExternalReport::not_scanned(
SCANNER,
&self.runtime.version,
NotScanned::Failed,
Some(format!(
"the skill could not be prepared for the scanner: {why}"
)),
),
};
report.content_hash = Some(hash);
crate::diagnostics::log::event(
"scanner.run",
&[
("scanner", &SCANNER.as_str()),
("runtime", &self.runtime.kind.as_str()),
("status", &report.status.as_str()),
("findings", &report.findings.len()),
("duration_ms", &started.elapsed().as_millis()),
],
);
report
}
fn run(
&self,
env: &Env,
home: &SurjectionHome,
run: &RunDir,
cancel: Option<&AtomicBool>,
) -> ExternalReport {
let version = self.runtime.version.as_str();
let not_scanned = |reason, detail: Option<String>| {
ExternalReport::not_scanned(SCANNER, version, reason, detail)
};
let mut command = Command::new(&self.runtime.program);
command
.args(self.runtime.argv(&run.skill))
.current_dir(&run.dir)
.env_clear()
.envs(run_env(env, home, &run.tmp, self.runtime.uv));
let executed = match process::execute(command, self.timeout, cancel, MAX_STDOUT, None) {
Ok(executed) => executed,
Err(why) => return not_scanned(NotScanned::Failed, Some(why)),
};
match executed.ended {
Ended::Exited(code) => match executed.stdout {
Some(Drained { overflow: true, .. }) if matches!(code, Some(0 | 1)) => {
ExternalReport::not_understood(
SCANNER,
version,
"the output is larger than 16 MiB",
)
}
Some(Drained { kept, .. }) => {
parse(&kept, &executed.stderr, code, &run.skill, version)
}
None => not_scanned(
NotScanned::Failed,
Some("the scanner's output did not end after it exited".to_owned()),
),
},
Ended::TimedOut => not_scanned(
NotScanned::Timeout,
Some(format!(
"SkillSpector did not finish in {} seconds",
self.timeout.as_secs()
)),
),
Ended::Canceled => not_scanned(NotScanned::Canceled, None),
Ended::Failed(why) => not_scanned(NotScanned::Failed, Some(why)),
}
}
}
pub const DISCLOSURE: &str = "SkillSpector runs on this computer and never uploads the skill. \
Nothing leaves this machine except the names and versions of the skill's dependencies, sent to \
OSV.dev (api.osv.dev) to look up known vulnerabilities, when the skill has a dependency manifest \
(requirements.txt, package.json, pyproject.toml or Pipfile). Preparing the uvx form once \
downloads SkillSpector 2.13.7 and its dependencies (a few hundred MB) from PyPI, and a Python \
3.13 build when uv has none; scans themselves never download anything. Set up (when uv is \
missing) also downloads uv 0.13.10 (about 16 MB) from GitHub once, checked against SHA-256 values \
built into Surjection, and keeps it, its cache and the Python it downloads inside Surjection's data \
folder; Remove deletes them. No account, no token, no upload of skill content. Surjection runs it \
only on skills, never on MCP servers (SkillSpector does not read MCP client configs), and only \
when you turn it on (or pass --external).";
macro_rules! manual_setup {
() => {
"install uv (https://docs.astral.sh/uv/getting-started/installation/) and run `surject \
scanner prepare` (or Prepare in Settings > Security), or install SkillSpector with \
`pipx install skillspector==2.13.7 --python 3.13`. It needs Python 3.12 or 3.13: Python \
3.14 and later don't work yet (yara-python has no wheels for them)."
};
}
pub const SETUP: &str = concat!(
"Choose Set up in Settings > Security, or run `surject scanner setup`: when uv is missing, \
Surjection downloads its own copy into its data folder (Remove deletes it). Or set it up \
yourself: ",
manual_setup!()
);
pub fn setup_text(supported: bool) -> String {
if supported {
SETUP.to_owned()
} else {
concat!("Set it up yourself: ", manual_setup!()).to_owned()
}
}
pub fn setup_supported(env: &Env, home: &SurjectionHome) -> bool {
PrivateUv::for_env(env, home).is_ok()
}