Skip to main content

dort_core/tools/install/
npm.rs

1//! Installs one exact npm package in an explicit scope.
2use super::*;
3use serde::{Deserialize, Serialize};
4use std::{collections::BTreeMap, path::Path};
5
6pub const WARNING: &str = "Installs one exact npm package with lifecycle scripts off. Native dependencies and bin/man links can change the prefix and add commands to PATH. npm can read configuration and contact package sources. No sandbox or rollback. A 10-minute deadline can leave partial effects.";
7
8#[derive(Clone, Serialize, Deserialize)]
9#[serde(deny_unknown_fields)]
10pub struct Catalog {
11    pub query: inspection::Query,
12    pub executable: PathBuf,
13    pub search_dirs: Vec<PathBuf>,
14    pub npm_binding: Option<inspection::NpmBinding>,
15    pub tools: BTreeSet<String>,
16}
17#[derive(Clone, Serialize, Deserialize)]
18#[serde(deny_unknown_fields)]
19pub struct Scope {
20    pub binding: inspection::NpmBinding,
21    pub catalogs: Vec<Catalog>,
22}
23#[derive(Clone, Serialize, Deserialize)]
24#[serde(deny_unknown_fields)]
25pub(super) struct Sources {
26    pub programs: Vec<Entry>,
27    pub directories: Vec<Entry>,
28    pub tool_directories: Vec<Entry>,
29}
30pub(super) fn valid(scope: &super::Scope) -> bool {
31    let Some(npm) = &scope.npm else {
32        return false;
33    };
34    if scope.brew.is_some()
35        || npm.catalogs.is_empty()
36        || npm.catalogs.len() > 16
37        || npm.binding.node != scope.executable
38        || npm.binding.prefix == scope.home
39        || npm.binding.prefix.ancestors().count() > 32
40        || !npm.binding.prefix.starts_with(&scope.home)
41        || !scope.bound_tools.contains(&npm.binding.runtime_tool)
42    {
43        return false;
44    }
45    let mut ids = BTreeSet::new();
46    for c in &npm.catalogs {
47        if c.tools.is_empty()
48            || c.tools.len() > 256
49            || c.search_dirs.len() > 256
50            || c.preview(&scope.home).is_err()
51            || c.tools.iter().any(|id| !ids.insert(id.clone()))
52        {
53            return false;
54        }
55        if c.tools.contains(&scope.tool)
56            && (c.npm_binding.as_ref() != Some(&npm.binding) || c.search_dirs != scope.search_dirs)
57        {
58            return false;
59        }
60    }
61    ids == scope.bound_tools
62}
63impl Catalog {
64    pub(crate) fn preview(&self, home: &Path) -> Result<inspection::Preview> {
65        let result = if self.query == inspection::Query::NpmGlobals {
66            let binding = self
67                .npm_binding
68                .clone()
69                .ok_or_else(|| invalid("npm catalog binding missing"))?;
70            if binding.node != self.executable {
71                return Err(invalid("npm catalog executable differs from selected Node"));
72            }
73            inspection::Preview::npm_probe(binding, home.to_owned(), self.search_dirs.clone())
74        } else {
75            if self.npm_binding.is_some() {
76                return Err(invalid("non-npm catalog cannot have an npm binding"));
77            }
78            inspection::Preview::new(
79                self.query,
80                self.executable.clone(),
81                home.to_owned(),
82                self.search_dirs.clone(),
83            )
84        };
85        result.map_err(|_| invalid("invalid explicit installation catalog scope"))
86    }
87    pub(super) fn matches(&self, home: &Path, r: &inspection::Report) -> bool {
88        let d = &r.description;
89        d.query == self.query
90            && d.executable == self.executable
91            && d.home == home
92            && d.trusted_search_path == self.search_dirs
93            && d.npm_binding == self.npm_binding
94    }
95}
96/// Process-free reconstruction from explicit catalog bindings. Serialized command
97/// descriptions are not accepted. The application must validate snapshot provenance.
98pub fn prepare(
99    host: &HostContext,
100    request: Request,
101    npm: Scope,
102    reports: &[&inspection::Report],
103) -> Result<Preview> {
104    prepare_inner(host, request, npm, reports, false)
105}
106
107pub(crate) fn prepare_environment(
108    host: &HostContext,
109    request: Request,
110    npm: Scope,
111    reports: &[&inspection::Report],
112) -> Result<Preview> {
113    prepare_inner(host, request, npm, reports, true)
114}
115
116fn prepare_inner(
117    host: &HostContext,
118    request: Request,
119    npm: Scope,
120    reports: &[&inspection::Report],
121    environment: bool,
122) -> Result<Preview> {
123    let (manifest, scope, sources) = super::sources(host, &request, Some(&npm), None)?;
124    // The durable intent budget applies before creation. Newly pinned parents
125    // expand in-memory fingerprints, not the immutable persisted intent.
126    super::bounded_metadata(&scope, &sources)?;
127    if !valid(&scope) {
128        return Err(invalid("invalid explicit npm installation scope"));
129    }
130    validate_catalogs(&manifest, &scope, &npm, reports)?;
131    let row = super::evaluate_catalogs(host, &manifest, &scope, reports)?;
132    if !super::reviewable(&row, environment) {
133        return Err(invalid(
134            "only an observed missing exact npm package with satisfied explicit runtime and prerequisites can be reviewed",
135        ));
136    }
137    Ok(Preview {
138        request,
139        scope,
140        sources,
141    })
142}
143fn validate_catalogs(
144    manifest: &Manifest,
145    scope: &super::Scope,
146    npm: &Scope,
147    reports: &[&inspection::Report],
148) -> Result<()> {
149    if npm.catalogs.is_empty() || npm.catalogs.len() > 16 || reports.len() != npm.catalogs.len() {
150        return Err(invalid("installation requires bounded explicit catalogs"));
151    }
152    let mut bound = BTreeMap::new();
153    for (catalog, report) in npm.catalogs.iter().zip(reports) {
154        catalog.preview(&scope.home)?;
155        if catalog.tools.is_empty() || !catalog.matches(&scope.home, report) {
156            return Err(invalid("selected installation catalog scope differs"));
157        }
158        for id in &catalog.tools {
159            if !scope.bound_tools.contains(id) || bound.insert(id.clone(), catalog).is_some() {
160                return Err(invalid(
161                    "duplicate or inactive installation catalog binding",
162                ));
163            }
164        }
165    }
166    if bound.len() != scope.bound_tools.len()
167        || !bound.get(&scope.tool).is_some_and(|c| {
168            c.query == inspection::Query::NpmGlobals && c.npm_binding.as_ref() == Some(&npm.binding)
169        })
170        || !bound.contains_key(&npm.binding.runtime_tool)
171        || !manifest
172            .tools
173            .iter()
174            .any(|t| t.id == npm.binding.runtime_tool)
175    {
176        return Err(invalid(
177            "explicit target and runtime catalog bindings required",
178        ));
179    }
180    Ok(())
181}
182pub(super) fn catalogs<'a>(
183    scope: &super::Scope,
184    npm: &Scope,
185    reports: &[&'a inspection::Report],
186) -> Result<BTreeMap<String, &'a inspection::Report>> {
187    if npm.catalogs.len() != reports.len() {
188        return Err(invalid("installation catalog count differs"));
189    }
190    let mut catalogs = BTreeMap::new();
191    for (c, r) in npm.catalogs.iter().zip(reports) {
192        if !c.matches(&scope.home, r) {
193            return Err(invalid("installation catalog scope differs"));
194        }
195        for id in &c.tools {
196            if catalogs.insert(id.clone(), *r).is_some() {
197                return Err(invalid("duplicate installation catalog binding"));
198            }
199        }
200    }
201    Ok(catalogs)
202}
203pub(super) fn arguments(scope: &super::Scope) -> Vec<String> {
204    let binding = &scope.npm.as_ref().expect("npm scope").binding;
205    [
206        binding.npm_cli.to_str().expect("validated path").to_owned(),
207        "install".into(),
208        "--global".into(),
209        "--prefix".into(),
210        binding.prefix.to_str().expect("validated path").into(),
211        "--ignore-scripts".into(),
212        "--audit=false".into(),
213        "--fund=false".into(),
214        "--update-notifier=false".into(),
215        "--logs-max=0".into(),
216        "--loglevel=silent".into(),
217        "--registry=https://registry.npmjs.org/".into(),
218        "--userconfig=/dev/null".into(),
219        "--globalconfig=/dev/null".into(),
220        format!("{}@{}", scope.package, scope.version),
221    ]
222    .into()
223}
224pub(super) fn program(path: &Path, executable: bool) -> Result<Entry> {
225    let e = observation::inspect(path, false)?;
226    if e.kind != Kind::Regular
227        || e.fingerprint
228            .as_ref()
229            .is_none_or(|f| f.links != 1 || (executable && f.mode & 0o111 == 0))
230    {
231        return Err(invalid(
232            "installation requires a physical regular trusted program",
233        ));
234    }
235    Ok(e)
236}
237pub(super) fn sources(scope: &super::Scope) -> Result<Sources> {
238    let npm = scope.npm.as_ref().expect("npm scope");
239    let b = &npm.binding;
240    if !inspection::absolute(&b.prefix)
241        || b.prefix == scope.home
242        || !b.prefix.starts_with(&scope.home)
243    {
244        return Err(invalid(
245            "npm installation prefix must be strictly inside HOME",
246        ));
247    }
248    for root in ["lib/node_modules", "bin", "share/man"] {
249        let root = b.prefix.join(root);
250        if b.node.starts_with(&root) || b.npm_cli.starts_with(&root) {
251            return Err(invalid(
252                "npm write roots must not contain selected Node or npm CLI",
253            ));
254        }
255    }
256    let mut programs = vec![program(&b.node, true)?, program(&b.npm_cli, false)?];
257    for c in &npm.catalogs {
258        c.preview(&scope.home)?;
259        programs.push(program(&c.executable, true)?);
260        if let Some(b) = &c.npm_binding {
261            programs.push(program(&b.npm_cli, false)?);
262        }
263    }
264    let mut paths = BTreeSet::new();
265    let mut roots = vec![
266        b.prefix.clone(),
267        b.prefix.join("lib/node_modules"),
268        b.prefix.join("bin"),
269        b.prefix.join("share/man"),
270    ];
271    if let Some((scope, _)) = scope
272        .package
273        .strip_prefix('@')
274        .and_then(|p| p.split_once('/'))
275    {
276        roots.push(b.prefix.join("lib/node_modules").join(format!("@{scope}")));
277    }
278    for path in roots {
279        for p in path.ancestors().take_while(|p| p.starts_with(&scope.home)) {
280            paths.insert(p.to_owned());
281        }
282    }
283    let mut directories = Vec::new();
284    for path in paths {
285        let e = observation::inspect(&path, false)?;
286        if !matches!(e.kind, Kind::Missing | Kind::Directory)
287            || e.fingerprint.as_ref().is_some_and(|f| {
288                f.uid != rustix::process::geteuid().as_raw() || f.mode & 0o022 != 0
289            })
290            || (path == scope.home && e.kind != Kind::Directory)
291        {
292            return Err(invalid(
293                "npm prefix parents must be physical owned directories without group/world write access",
294            ));
295        }
296        directories.push(e);
297    }
298    let tool_directories = scope
299        .tool_search_dirs
300        .iter()
301        .map(|p| {
302            let e = observation::inspect(p, false)?;
303            if e.kind != Kind::Directory {
304                return Err(invalid("tool search directory unavailable or unsafe"));
305            }
306            Ok(e)
307        })
308        .collect::<Result<Vec<_>>>()?;
309    Ok(Sources {
310        programs,
311        directories,
312        tool_directories,
313    })
314}
315pub(super) fn same_directory(a: &Entry, b: &Entry) -> bool {
316    a.path == b.path
317        && a.kind == b.kind
318        && match (&a.fingerprint, &b.fingerprint) {
319            (Some(a), Some(b)) => adoption::parent_identity(a, b),
320            (None, None) => true,
321            _ => false,
322        }
323        && a.parents.len() == b.parents.len()
324        && a.parents.iter().zip(&b.parents).all(|(a, b)| {
325            a.path == b.path && adoption::parent_identity(&a.fingerprint, &b.fingerprint)
326        })
327}
328pub(super) fn effect_sources(sources: &Sources) -> Sources {
329    let mut stable = sources.clone();
330    for program in &mut stable.programs {
331        *program = program.clone().stable_parents();
332    }
333    for entry in stable
334        .directories
335        .iter_mut()
336        .chain(&mut stable.tool_directories)
337    {
338        *entry = entry.clone().stable_parents();
339        if let Some(fingerprint) = &mut entry.fingerprint {
340            fingerprint.modified = (0, 0);
341            fingerprint.changed = (0, 0);
342            fingerprint.links = 0;
343            fingerprint.size = 0;
344        }
345    }
346    stable
347}
348
349pub(super) fn same(a: &Sources, b: &Sources) -> bool {
350    a.tool_directories.len() == b.tool_directories.len()
351        && a.tool_directories
352            .iter()
353            .zip(&b.tool_directories)
354            .all(|(a, b)| same_directory(a, b))
355        && a.programs.len() == b.programs.len()
356        && a.programs
357            .iter()
358            .zip(&b.programs)
359            .all(|(a, b)| same_source(a, b))
360        && a.directories.len() == b.directories.len()
361        && a.directories
362            .iter()
363            .zip(&b.directories)
364            .all(|(a, b)| same_directory(a, b))
365}
366/// Called only after immutable intent and final guards. Create only approved
367/// mutation parents, descriptor-relative, then pin the resulting identities.
368pub(super) fn create_directories(scope: &super::Scope, old: &Sources) -> Result<Sources> {
369    if !same(old, &sources(scope)?) {
370        return Err(invalid("npm prefix changed before creation"));
371    }
372    let mut created = Vec::new();
373    for e in &old.directories {
374        if e.kind != Kind::Missing {
375            continue;
376        }
377        let handle = observation::parent_handle(&e.path)?;
378        if handle.missing {
379            return Err(invalid("npm prefix creation parent unavailable"));
380        }
381        rustix::fs::mkdirat(
382            &handle.directory,
383            &handle.name,
384            rustix::fs::Mode::from_raw_mode(0o755),
385        )
386        .map_err(|_| invalid("npm prefix creation failed; inspect pending attempt"))?;
387        handle
388            .directory
389            .sync_all()
390            .map_err(|_| invalid("npm prefix parent sync failed"))?;
391        let made = observation::parent_handle(&e.path.join(".dort-parent-check"))?;
392        made.directory
393            .sync_all()
394            .map_err(|_| invalid("npm prefix directory sync failed"))?;
395        // Pin each new directory immediately, not only at the end of creation.
396        let entry = observation::inspect(&e.path, false)?;
397        if entry.kind != Kind::Directory {
398            return Err(invalid("new npm directory changed"));
399        }
400        created.push(entry);
401    }
402    let fresh = sources(scope)?;
403    if old.tool_directories.len() != fresh.tool_directories.len()
404        || old
405            .tool_directories
406            .iter()
407            .zip(&fresh.tool_directories)
408            .any(|(a, b)| !same_directory(a, b))
409        || created.iter().any(|a| {
410            fresh
411                .directories
412                .iter()
413                .find(|b| b.path == a.path)
414                .is_none_or(|b| !same_directory(a, b))
415        })
416        || old
417            .programs
418            .iter()
419            .zip(&fresh.programs)
420            .any(|(a, b)| !same_source(a, b))
421        || old
422            .directories
423            .iter()
424            .zip(&fresh.directories)
425            .any(|(a, b)| a.kind != Kind::Missing && !same_directory(a, b))
426    {
427        return Err(invalid(
428            "npm prefix changed while creating approved parents",
429        ));
430    }
431    Ok(fresh)
432}