1use super::{
3 VersionPolicy, inspection,
4 planning::{PackageAction, PackageFinding, Row},
5};
6use crate::model::Provider;
7use serde::Serialize;
8use std::{collections::BTreeMap, path::PathBuf};
9
10pub const MAX_COMMAND_BYTES: usize = 65_536;
11pub const MAX_TOTAL_COMMAND_BYTES: usize = 4 * 1024 * 1024;
12pub const WARNING: &str = "PREVIEW ONLY: Dort cannot execute this description. It is not approval, a tested provider capability or proof of safe global absence. Native installation may download code, execute provider/plugins/package code, change dependencies, links and caches, or fail with partial effects. No rollback or tool-readiness guarantee. Execution needs a separately agreed fresh-validation, approval, persistence and failure design.";
13#[derive(Debug, Serialize, Default)]
14#[serde(tag = "state", rename_all = "snake_case")]
15pub enum Preview {
16 NoPackageChange,
17 #[default]
18 Blocked,
19 Deferred {
20 reason: Deferred,
21 },
22 PreviewOnly {
23 command: Command,
24 },
25}
26#[derive(Debug, Serialize)]
27#[serde(rename_all = "snake_case")]
28pub enum Deferred {
29 MissingScope,
30 InvalidScope,
31 UnsupportedPolicy,
32 DescriptionLimit,
33}
34#[derive(Debug, Serialize)]
35#[serde(rename_all = "snake_case")]
36pub enum VersionSelection {
37 ProviderDefaultUnresolved,
38 LatestUnresolved,
39 ExactRequested,
40}
41#[derive(Debug, Serialize)]
42#[serde(rename_all = "snake_case")]
43pub enum Effect {
44 NetworkAndDownloads,
45 ProviderConfigurationAndCode,
46 DependencyChangesMayIncludeUpgrades,
47 SharedLinksCachesAndData,
48 NoAutomaticRollback,
49 NpmLifecycleScriptsDisabled,
50 SkippedScriptsMayLeavePackageUnusable,
51}
52#[derive(Debug, Serialize)]
53pub struct Command {
54 pub executable: PathBuf,
55 pub arguments: Vec<String>,
56 pub working_directory: &'static str,
57 pub environment_cleared: bool,
58 pub environment: BTreeMap<String, String>,
60 pub version_selection: VersionSelection,
61 pub effects: Vec<Effect>,
62 pub warning: &'static str,
63 pub execution_authorized: bool,
64}
65pub(super) fn describe(
68 row: &Row,
69 trusted_search_path: &[PathBuf],
70 total_bytes: &mut usize,
71) -> Preview {
72 match row.action {
73 PackageAction::NoChange => return Preview::NoPackageChange,
74 PackageAction::Blocked => return Preview::Blocked,
75 PackageAction::ReviewMissingPackage => (),
76 }
77 if !row.blockers.is_empty()
78 || !matches!(row.package, PackageFinding::Absent)
79 || !matches!(
80 row.binary_observation,
81 super::planning::BinaryObservation::Missing
82 )
83 {
84 return Preview::Blocked;
85 }
86 let (Some(declaration), Some(scope)) = (&row.declaration, &row.catalog_scope) else {
87 return Preview::Deferred {
88 reason: Deferred::MissingScope,
89 };
90 };
91 if scope.query.provider() != declaration.provider
92 || !inspection::absolute(&scope.executable)
93 || !inspection::absolute(&scope.home)
94 || trusted_search_path.is_empty()
95 || !trusted_search_path.iter().all(|p| inspection::absolute(p))
96 {
97 return Preview::Deferred {
98 reason: Deferred::InvalidScope,
99 };
100 }
101 let Ok(path) = std::env::join_paths(trusted_search_path) else {
102 return Preview::Deferred {
103 reason: Deferred::InvalidScope,
104 };
105 };
106 let Some(path) = path.to_str() else {
107 return Preview::Deferred {
108 reason: Deferred::InvalidScope,
109 };
110 };
111 let mut environment: BTreeMap<String, String> = [
112 ("HOME", scope.home.clone()),
113 ("XDG_CONFIG_HOME", scope.home.join(".config")),
114 ("XDG_CACHE_HOME", scope.home.join(".cache")),
115 ("XDG_DATA_HOME", scope.home.join(".local/share")),
116 ("XDG_STATE_HOME", scope.home.join(".local/state")),
117 ]
118 .into_iter()
119 .map(|(key, value)| {
120 (
121 key.into(),
122 value.to_str().expect("validated UTF-8 home scope").into(),
123 )
124 })
125 .collect();
126 for (key, value) in [
127 ("PATH", path),
128 ("LC_ALL", "C"),
129 ("LANG", "C"),
130 ("NO_COLOR", "1"),
131 ] {
132 environment.insert(key.into(), value.into());
133 }
134 let selection = match declaration.policy {
135 VersionPolicy::ProviderDefault {} => VersionSelection::ProviderDefaultUnresolved,
136 VersionPolicy::Latest {} => VersionSelection::LatestUnresolved,
137 VersionPolicy::Exact { .. } => VersionSelection::ExactRequested,
138 };
139 let mut effects = vec![
140 Effect::NetworkAndDownloads,
141 Effect::ProviderConfigurationAndCode,
142 Effect::DependencyChangesMayIncludeUpgrades,
143 Effect::SharedLinksCachesAndData,
144 Effect::NoAutomaticRollback,
145 ];
146 let arguments = match declaration.provider {
147 Provider::Brew => {
148 if !matches!(
149 declaration.policy,
150 VersionPolicy::ProviderDefault {} | VersionPolicy::Latest {}
151 ) {
152 return Preview::Deferred {
153 reason: Deferred::UnsupportedPolicy,
154 };
155 }
156 for key in [
159 "HOMEBREW_NO_AUTO_UPDATE",
160 "HOMEBREW_NO_ANALYTICS",
161 "HOMEBREW_NO_ENV_HINTS",
162 "HOMEBREW_NO_INSTALL_FROM_API",
163 "HOMEBREW_NO_INSTALL_UPGRADE",
164 "HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK",
165 "HOMEBREW_NO_INSTALL_CLEANUP",
166 ] {
167 environment.insert(key.into(), "1".into());
168 }
169 vec![
170 "install".into(),
171 "--formula".into(),
172 declaration.package.clone(),
173 ]
174 }
175 Provider::Npm => {
176 let Some(binding) = scope.npm_binding.as_ref().filter(|b| {
177 b.node == scope.executable
178 && Some(b.runtime_tool.as_str()) == declaration.runtime_tool.as_deref()
179 && inspection::absolute(&b.npm_cli)
180 && inspection::absolute(&b.prefix)
181 }) else {
182 return Preview::Deferred {
183 reason: Deferred::InvalidScope,
184 };
185 };
186 let package = match &declaration.policy {
187 VersionPolicy::ProviderDefault {} => declaration.package.clone(),
188 VersionPolicy::Latest {} => format!("{}@latest", declaration.package),
189 VersionPolicy::Exact { version } => format!("{}@{version}", declaration.package),
190 };
191 effects.push(Effect::NpmLifecycleScriptsDisabled);
192 effects.push(Effect::SkippedScriptsMayLeavePackageUnusable);
193 vec![
194 binding
195 .npm_cli
196 .to_str()
197 .expect("validated UTF-8 npm CLI")
198 .into(),
199 "install".into(),
200 "--global".into(),
201 "--prefix".into(),
202 binding
203 .prefix
204 .to_str()
205 .expect("validated UTF-8 npm prefix")
206 .into(),
207 "--ignore-scripts".into(),
208 "--no-audit".into(),
209 "--no-fund".into(),
210 "--logs-max=0".into(),
211 "--update-notifier=false".into(),
212 package,
213 ]
214 }
215 };
216 let preview = Preview::PreviewOnly {
217 command: Command {
218 executable: scope.executable.clone(),
219 arguments,
220 working_directory: "/",
221 environment_cleared: true,
222 environment,
223 version_selection: selection,
224 effects,
225 warning: WARNING,
226 execution_authorized: false,
227 },
228 };
229 let Ok(encoded) = serde_json::to_vec(&preview) else {
230 return Preview::Deferred {
231 reason: Deferred::InvalidScope,
232 };
233 };
234 let bytes = encoded.len();
235 if bytes > MAX_COMMAND_BYTES || total_bytes.saturating_add(bytes) > MAX_TOTAL_COMMAND_BYTES {
236 return Preview::Deferred {
237 reason: Deferred::DescriptionLimit,
238 };
239 }
240 *total_bytes += bytes;
241 preview
242}