Skip to main content

aube_scripts/
lib.rs

1//! Lifecycle script runner for aube.
2//!
3//! **Security model**:
4//! - Scripts from the **root package** (the project's own `package.json`)
5//!   run by default. They're written by the user, so they're trusted the
6//!   same way a user trusts `aube run <script>`.
7//! - Scripts from **installed dependencies** (e.g. `node-gyp` postinstall
8//!   from a native module) are SKIPPED by default. A package runs its
9//!   lifecycle scripts only if the active [`BuildPolicy`] allows it —
10//!   configured via `pnpm.allowBuilds` in `package.json`, `allowBuilds`
11//!   in `aube-workspace.yaml` (or `pnpm-workspace.yaml`), or the
12//!   escape-hatch `--dangerously-allow-all-builds` flag.
13//! - `--ignore-scripts` forces everything off, matching pnpm/npm.
14
15pub mod content_sniff;
16pub mod direct;
17pub mod policy;
18
19#[cfg(target_os = "linux")]
20mod linux_jail;
21
22#[cfg(windows)]
23mod windows_job;
24
25pub use content_sniff::{Suspicion, SuspicionKind, sniff_lifecycle};
26pub use policy::{AllowDecision, BuildPolicy, BuildPolicyError, pattern_matches};
27
28use aube_manifest::PackageJson;
29use std::collections::hash_map::DefaultHasher;
30use std::hash::{Hash, Hasher};
31use std::path::{Path, PathBuf};
32use tokio::io::{AsyncBufReadExt, AsyncReadExt};
33
34const MAX_SCRIPT_OUTPUT_RECORD_BYTES: usize = 64 * 1024;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ScriptOutputStream {
38    Stdout,
39    Stderr,
40}
41
42pub trait ScriptOutputReporter: Send + Sync + 'static {
43    fn report(&self, stream: ScriptOutputStream, line: String);
44}
45
46/// Env var naming the executable that can dispatch aube's CLI — the running
47/// program, whether that is aube itself or a host that embedded it. Aube's
48/// `npm_execpath` shim reads it rather than baking a path into the cached
49/// file, so a host that moves or upgrades keeps working. Set on every
50/// lifecycle script, exactly like `AUBE_NODE_GYP_EXE`.
51pub const CLI_EXE_ENV: &str = "AUBE_CLI_EXE";
52
53/// Settings that affect every package-script shell aube spawns.
54#[derive(Debug, Clone, Default)]
55pub struct ScriptSettings {
56    pub node_options: Option<String>,
57    pub script_shell: Option<PathBuf>,
58    pub unsafe_perm: Option<bool>,
59    pub shell_emulator: bool,
60    /// Directory of the project's resolved Node runtime. `None` when no
61    /// runtime switching is active.
62    pub node_bin_dir: Option<PathBuf>,
63    /// The node exported as `NODE` (npm parity) — the program a
64    /// script's `$NODE` / bare `node` re-spawns. A wrapper's shim; the
65    /// real binary otherwise.
66    pub node_program: Option<PathBuf>,
67    /// The node exported as `npm_node_execpath` — the *real* binary
68    /// node-gyp reads to find Node's install prefix. Equals
69    /// [`Self::node_program`] unless a wrapper split them apart.
70    pub node_execpath: Option<PathBuf>,
71    /// Extra environment an embedder contributes to every script,
72    /// applied last (after `env_clear`) so it survives the jail. Merge
73    /// semantics against aube's own values are resolved upstream; these
74    /// are plain overrides. (`NODE_OPTIONS` folding happens through
75    /// [`Self::node_options`].)
76    pub extra_env: Vec<(std::ffi::OsString, std::ffi::OsString)>,
77    /// The top-level package-manager command, exported as `npm_command`
78    /// (npm/pnpm parity): `"run-script"` for `aube run`, `"install"`
79    /// for install lifecycle hooks, `"rebuild"`, `"pack"`, etc. `None`
80    /// leaves `npm_command` unset.
81    pub command: Option<String>,
82    /// Path to a runnable `node-gyp` stand-in, exported as
83    /// `npm_config_node_gyp` (npm/pnpm parity). npm/pnpm point this at
84    /// their bundled `node-gyp/bin/node-gyp.js`; aube bootstraps node-gyp
85    /// lazily, so this is a tiny shim that resolves (and bootstraps on
86    /// first use) the real node-gyp and forwards argv. `None` leaves
87    /// `npm_config_node_gyp` unset.
88    pub node_gyp_js: Option<PathBuf>,
89    /// The proxy aube resolved for its own registry traffic, re-exported
90    /// to lifecycle scripts as the standard `HTTPS_PROXY` / `HTTP_PROXY`
91    /// / `NO_PROXY` env vars (plus `NODE_USE_ENV_PROXY=1`) so a script's
92    /// own `fetch()` / `http` calls honor the same proxy. aube reaches
93    /// scripts as `npm_config_proxy`, which Node ignores — only these
94    /// vars work. `None` on each leaves the corresponding var unset; the
95    /// proxy block is skipped entirely when both `http_proxy` and
96    /// `https_proxy` are `None`.
97    pub http_proxy: Option<String>,
98    pub https_proxy: Option<String>,
99    pub no_proxy: Option<String>,
100}
101
102/// Native build jail applied to dependency lifecycle scripts.
103#[derive(Debug, Clone)]
104pub struct ScriptJail {
105    pub package_dir: PathBuf,
106    pub env: Vec<String>,
107    pub read_paths: Vec<PathBuf>,
108    pub write_paths: Vec<PathBuf>,
109    pub network: bool,
110}
111
112impl ScriptJail {
113    pub fn new(package_dir: impl Into<PathBuf>) -> Self {
114        Self {
115            package_dir: package_dir.into(),
116            env: Vec::new(),
117            read_paths: Vec::new(),
118            write_paths: Vec::new(),
119            network: false,
120        }
121    }
122
123    pub fn with_env(mut self, env: impl IntoIterator<Item = String>) -> Self {
124        self.env = env.into_iter().collect();
125        self
126    }
127
128    pub fn with_read_paths(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
129        self.read_paths = paths.into_iter().collect();
130        self
131    }
132
133    pub fn with_write_paths(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
134        self.write_paths = paths.into_iter().collect();
135        self
136    }
137
138    pub fn with_network(mut self, network: bool) -> Self {
139        self.network = network;
140        self
141    }
142}
143
144pub struct ScriptJailHomeCleanup {
145    path: PathBuf,
146}
147
148impl ScriptJailHomeCleanup {
149    pub fn new(jail: &ScriptJail) -> Self {
150        Self {
151            path: jail_home(&jail.package_dir),
152        }
153    }
154}
155
156impl Drop for ScriptJailHomeCleanup {
157    fn drop(&mut self) {
158        if self.path.exists()
159            && let Err(err) = std::fs::remove_dir_all(&self.path)
160        {
161            tracing::debug!("failed to clean jail HOME {}: {err}", self.path.display());
162        }
163    }
164}
165
166#[derive(Clone, Default)]
167struct ScriptSettingsState {
168    settings: ScriptSettings,
169    node_bin_dir_precedes_project_bins: bool,
170    output_reporter: Option<std::sync::Arc<dyn ScriptOutputReporter>>,
171    /// The npm-compatible executable exported as `npm_execpath`. See
172    /// [`set_pm_execpath`].
173    pm_execpath: Option<PathBuf>,
174}
175
176static SCRIPT_SETTINGS: std::sync::OnceLock<std::sync::RwLock<ScriptSettingsState>> =
177    std::sync::OnceLock::new();
178
179type ScriptSettingsSlot = std::sync::Arc<std::sync::RwLock<ScriptSettingsState>>;
180
181tokio::task_local! {
182    static INSTALL_SCRIPT_SETTINGS: ScriptSettingsSlot;
183}
184
185/// Run an install with an isolated script-settings snapshot.
186pub async fn scope<F: std::future::Future>(future: F) -> F::Output {
187    INSTALL_SCRIPT_SETTINGS
188        .scope(
189            std::sync::Arc::new(std::sync::RwLock::new(ScriptSettingsState::default())),
190            future,
191        )
192        .await
193}
194
195/// Propagate the current install's script settings into a spawned task.
196pub fn scope_current<F: std::future::Future>(
197    future: F,
198) -> impl std::future::Future<Output = F::Output> {
199    let settings = INSTALL_SCRIPT_SETTINGS.try_with(std::sync::Arc::clone).ok();
200    async move {
201        match settings {
202            Some(settings) => INSTALL_SCRIPT_SETTINGS.scope(settings, future).await,
203            None => future.await,
204        }
205    }
206}
207
208fn script_settings_lock() -> &'static std::sync::RwLock<ScriptSettingsState> {
209    SCRIPT_SETTINGS.get_or_init(|| std::sync::RwLock::new(ScriptSettingsState::default()))
210}
211
212/// Replace the current install's script settings snapshot, or the process-wide
213/// fallback when called outside an install scope.
214pub fn set_script_settings(settings: ScriptSettings) {
215    set_script_settings_with_path_order(settings, false);
216}
217
218/// Replace the script settings and control whether the runtime bin directory
219/// precedes project-local bins. Wrapping runtimes use `true` so a local `node`
220/// cannot bypass their shim; selectors use `false`.
221#[doc(hidden)]
222pub fn set_script_settings_with_path_order(
223    settings: ScriptSettings,
224    node_bin_dir_precedes_project_bins: bool,
225) {
226    if INSTALL_SCRIPT_SETTINGS
227        .try_with(|slot| match slot.write() {
228            Ok(mut guard) => {
229                guard.settings = settings.clone();
230                guard.node_bin_dir_precedes_project_bins = node_bin_dir_precedes_project_bins;
231            }
232            Err(poisoned) => {
233                let mut guard = poisoned.into_inner();
234                guard.settings = settings.clone();
235                guard.node_bin_dir_precedes_project_bins = node_bin_dir_precedes_project_bins;
236            }
237        })
238        .is_ok()
239    {
240        return;
241    }
242    match script_settings_lock().write() {
243        Ok(mut guard) => {
244            guard.settings = settings;
245            guard.node_bin_dir_precedes_project_bins = node_bin_dir_precedes_project_bins;
246        }
247        Err(poisoned) => {
248            let mut guard = poisoned.into_inner();
249            guard.settings = settings;
250            guard.node_bin_dir_precedes_project_bins = node_bin_dir_precedes_project_bins;
251        }
252    }
253}
254
255/// Route lifecycle child output through an embedding host. When unset,
256/// scripts inherit the parent process's stdout and stderr as usual.
257pub fn set_output_reporter(reporter: Option<std::sync::Arc<dyn ScriptOutputReporter>>) {
258    if INSTALL_SCRIPT_SETTINGS
259        .try_with(|slot| match slot.write() {
260            Ok(mut guard) => guard.output_reporter = reporter.clone(),
261            Err(poisoned) => poisoned.into_inner().output_reporter = reporter.clone(),
262        })
263        .is_ok()
264    {
265        return;
266    }
267    match script_settings_lock().write() {
268        Ok(mut guard) => guard.output_reporter = reporter,
269        Err(poisoned) => poisoned.into_inner().output_reporter = reporter,
270    }
271}
272
273/// Register the npm-compatible executable exported as `npm_execpath` — what
274/// a lifecycle script re-invokes to reach *this* package manager
275/// (`${npm_execpath} run build`).
276///
277/// Unset (the default) names aube's own binary when aube is the running
278/// program, and leaves `npm_execpath` unset under an embedder: the running
279/// executable is then the host's, and its CLI is not aube's. Pass a shim that
280/// re-enters aube to restore the variable there.
281pub fn set_pm_execpath(path: Option<PathBuf>) {
282    if INSTALL_SCRIPT_SETTINGS
283        .try_with(|slot| match slot.write() {
284            Ok(mut guard) => guard.pm_execpath = path.clone(),
285            Err(poisoned) => poisoned.into_inner().pm_execpath = path.clone(),
286        })
287        .is_ok()
288    {
289        return;
290    }
291    match script_settings_lock().write() {
292        Ok(mut guard) => guard.pm_execpath = path,
293        Err(poisoned) => poisoned.into_inner().pm_execpath = path,
294    }
295}
296
297fn script_settings_state() -> ScriptSettingsState {
298    if let Ok(state) = INSTALL_SCRIPT_SETTINGS.try_with(|slot| match slot.read() {
299        Ok(guard) => guard.clone(),
300        Err(poisoned) => poisoned.into_inner().clone(),
301    }) {
302        return state;
303    }
304    match script_settings_lock().read() {
305        Ok(guard) => guard.clone(),
306        Err(poisoned) => poisoned.into_inner().clone(),
307    }
308}
309
310fn script_settings() -> ScriptSettings {
311    script_settings_state().settings
312}
313
314#[cfg(test)]
315mod scoped_settings_tests {
316    use super::*;
317
318    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
319    async fn install_script_settings_are_isolated_and_propagated() {
320        let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(2));
321        let first_barrier = std::sync::Arc::clone(&barrier);
322        let second_barrier = std::sync::Arc::clone(&barrier);
323
324        let first = scope(async move {
325            set_script_settings_with_path_order(
326                ScriptSettings {
327                    command: Some("first".to_string()),
328                    ..ScriptSettings::default()
329                },
330                true,
331            );
332            first_barrier.wait().await;
333            tokio::spawn(scope_current(async {
334                let state = script_settings_state();
335                (
336                    state.settings.command,
337                    state.node_bin_dir_precedes_project_bins,
338                )
339            }))
340            .await
341            .unwrap()
342        });
343        let second = scope(async move {
344            set_script_settings(ScriptSettings {
345                command: Some("second".to_string()),
346                ..ScriptSettings::default()
347            });
348            second_barrier.wait().await;
349            tokio::spawn(scope_current(async {
350                let state = script_settings_state();
351                (
352                    state.settings.command,
353                    state.node_bin_dir_precedes_project_bins,
354                )
355            }))
356            .await
357            .unwrap()
358        });
359
360        let (first, second) = tokio::join!(first, second);
361        assert_eq!(first.0.as_deref(), Some("first"));
362        assert!(first.1);
363        assert_eq!(second.0.as_deref(), Some("second"));
364        assert!(!second.1);
365    }
366}
367
368/// Prepend `bin_dir` to the current `PATH` using the platform's path
369/// separator (`:` on Unix, `;` on Windows).
370pub fn prepend_path(bin_dir: &Path) -> std::ffi::OsString {
371    prepend_paths(std::slice::from_ref(&bin_dir.to_path_buf()))
372}
373
374/// [`prepend_path`] for multiple directories, prepended in order.
375pub fn prepend_paths(bin_dirs: &[PathBuf]) -> std::ffi::OsString {
376    let path = std::env::var_os("PATH").unwrap_or_default();
377    let mut entries: Vec<PathBuf> = bin_dirs.to_vec();
378    entries.extend(std::env::split_paths(&path));
379    std::env::join_paths(entries).unwrap_or(path)
380}
381
382/// Place a runtime bin directory around project-local bin directories.
383/// Wrappers lead so a local `node` cannot bypass their shim; selectors follow
384/// so package-provided commands retain normal precedence.
385pub fn order_path_entries(
386    mut project_bins: Vec<PathBuf>,
387    runtime_bin: Option<&Path>,
388    runtime_precedes_project_bins: bool,
389) -> Vec<PathBuf> {
390    let Some(runtime_bin) = runtime_bin else {
391        return project_bins;
392    };
393    if runtime_precedes_project_bins {
394        project_bins.insert(0, runtime_bin.to_path_buf());
395    } else {
396        project_bins.push(runtime_bin.to_path_buf());
397    }
398    project_bins
399}
400
401#[cfg(test)]
402mod path_entry_tests {
403    use super::*;
404
405    #[test]
406    fn wrapper_runtime_leads_project_bins() {
407        let runtime = Path::new("/shim");
408        let project = PathBuf::from("/project/node_modules/.bin");
409        assert_eq!(
410            order_path_entries(vec![project.clone()], Some(runtime), true),
411            vec![runtime.to_path_buf(), project]
412        );
413    }
414
415    #[test]
416    fn selector_runtime_follows_project_bins() {
417        let runtime = Path::new("/opt/node/bin");
418        let project = PathBuf::from("/project/node_modules/.bin");
419        assert_eq!(
420            order_path_entries(vec![project.clone()], Some(runtime), false),
421            vec![project, runtime.to_path_buf()]
422        );
423    }
424}
425
426/// Spawn a shell command line. On Unix we go through `sh -c`, on
427/// Windows through `cmd.exe /d /s /c` — matching what npm passes in
428/// `@npmcli/run-script`.
429///
430/// On Windows, the script command line is appended with
431/// [`std::os::windows::process::CommandExt::raw_arg`] instead of
432/// the normal `.arg()` path. `.arg()` would run the string through
433/// Rust's `CommandLineToArgvW`-oriented encoder, which wraps it in
434/// `"..."` and escapes interior `"` as `\"` — but `cmd.exe` parses
435/// command lines with a different set of rules and does not
436/// understand `\"`, so a script like
437/// `node -e "require('is-odd')(3)"` arrives mangled. `raw_arg`
438/// hands the command line to `CreateProcessW` verbatim, so we
439/// control the exact bytes cmd.exe sees. We wrap the whole script
440/// in an outer pair of double quotes, which `/s` tells cmd.exe to
441/// strip (just those outer quotes — the rest of the string is
442/// preserved literally). This is the same trick
443/// `@npmcli/run-script` and `node-cross-spawn` use.
444pub fn spawn_shell(script_cmd: &str) -> tokio::process::Command {
445    let settings = script_settings();
446    spawn_shell_with_settings(script_cmd, &settings)
447}
448
449/// Spawn a resolved program directly, skipping the shell.
450///
451/// The counterpart to [`spawn_shell`] for a script body that
452/// [`direct::direct_argv`] found to be a single plain command. `program`
453/// is the absolute path `direct_argv` resolved; `arg0` is the program as
454/// written in the script body, passed through as `argv[0]` so the child
455/// sees what a shell would have given it.
456///
457/// Env parity with the shell path is structural, not a parallel list:
458/// this calls the same [`apply_script_settings_env`] and shares
459/// `kill_on_drop`. Which now kills the tool itself rather than a shell
460/// holding it as a child — strictly more direct, and the reason the
461/// Windows Job Object story in [`spawn_shell`] does not apply here (the
462/// fast path is Unix-only).
463pub fn spawn_program<I, S>(program: &Path, arg0: &str, args: I) -> tokio::process::Command
464where
465    I: IntoIterator<Item = S>,
466    S: AsRef<std::ffi::OsStr>,
467{
468    let settings = script_settings();
469    let mut cmd = tokio::process::Command::new(program);
470    #[cfg(unix)]
471    {
472        use std::os::unix::process::CommandExt;
473        cmd.as_std_mut().arg0(arg0);
474    }
475    #[cfg(not(unix))]
476    let _ = arg0;
477    cmd.args(args);
478    apply_script_settings_env(&mut cmd, &settings);
479    cmd.kill_on_drop(true);
480    cmd
481}
482
483fn spawn_shell_with_settings(
484    script_cmd: &str,
485    settings: &ScriptSettings,
486) -> tokio::process::Command {
487    #[cfg(unix)]
488    let mut cmd = {
489        let mut cmd = tokio::process::Command::new(
490            settings
491                .script_shell
492                .as_deref()
493                .unwrap_or_else(|| Path::new("sh")),
494        );
495        cmd.arg("-c").arg(script_cmd);
496        cmd
497    };
498    #[cfg(windows)]
499    let mut cmd = {
500        let mut cmd = tokio::process::Command::new(
501            settings
502                .script_shell
503                .as_deref()
504                .unwrap_or_else(|| Path::new("cmd.exe")),
505        );
506        if settings.script_shell.is_some() {
507            cmd.arg("-c").arg(script_cmd);
508        } else {
509            // `/d` skips AutoRun, `/s` flips the quote-stripping rule
510            // so only the *outer* `"..."` pair is removed, `/c` runs
511            // the command and exits. Build the raw argv tail manually
512            // so cmd.exe sees the original script bytes.
513            cmd.raw_arg("/d /s /c \"").raw_arg(script_cmd).raw_arg("\"");
514        }
515        cmd
516    };
517    apply_script_settings_env(&mut cmd, settings);
518    // Aborting the `JoinSet` that drives the parallel lifecycle pass
519    // drops the spawned `Child`, which without `kill_on_drop` would
520    // leave the shell running detached (Discussion #654). On Windows
521    // that's only half the fix — `TerminateProcess` on `cmd.exe`
522    // doesn't reach grandchildren like `node-gyp` → `MSBuild` → `node`;
523    // [`run_command_killing_descendants`] also assigns the shell to a
524    // `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` job object to reap the
525    // whole tree.
526    cmd.kill_on_drop(true);
527    cmd
528}
529
530#[cfg(target_os = "macos")]
531fn sbpl_escape(s: &str) -> String {
532    s.replace('\\', "\\\\").replace('"', "\\\"")
533}
534
535#[cfg(target_os = "macos")]
536fn push_write_rule(rules: &mut Vec<String>, path: &Path) {
537    let path = sbpl_escape(&path.to_string_lossy());
538    let rule = format!("(allow file-write* (subpath \"{path}\"))");
539    if !rules.iter().any(|existing| existing == &rule) {
540        rules.push(rule);
541    }
542}
543
544#[cfg(target_os = "macos")]
545fn jail_profile(jail: &ScriptJail, home: &Path) -> String {
546    let mut rules = vec![
547        "(version 1)".to_string(),
548        "(allow default)".to_string(),
549        "(allow network* (local unix))".to_string(),
550        "(deny file-write*)".to_string(),
551    ];
552    if !jail.network {
553        rules.insert(2, "(deny network*)".to_string());
554    }
555
556    for path in [
557        Path::new("/tmp"),
558        Path::new("/private/tmp"),
559        Path::new("/dev"),
560    ] {
561        push_write_rule(&mut rules, path);
562    }
563    for path in [&jail.package_dir, home] {
564        push_write_rule(&mut rules, path);
565    }
566    for path in &jail.write_paths {
567        push_write_rule(&mut rules, path);
568    }
569    for path in [&jail.package_dir, home] {
570        if let Ok(canonical) = path.canonicalize() {
571            push_write_rule(&mut rules, &canonical);
572        }
573    }
574    for path in &jail.write_paths {
575        if let Ok(canonical) = path.canonicalize() {
576            push_write_rule(&mut rules, &canonical);
577        }
578    }
579    rules.join("\n")
580}
581
582#[cfg(target_os = "macos")]
583fn spawn_jailed_shell(
584    script_cmd: &str,
585    settings: &ScriptSettings,
586    jail: &ScriptJail,
587    home: &Path,
588) -> tokio::process::Command {
589    let shell = settings
590        .script_shell
591        .as_deref()
592        .unwrap_or_else(|| Path::new("sh"));
593    let profile = jail_profile(jail, home);
594    let mut cmd = tokio::process::Command::new("sandbox-exec");
595    cmd.arg("-p")
596        .arg(profile)
597        .arg("--")
598        .arg(shell)
599        .arg("-c")
600        .arg(script_cmd);
601    apply_script_settings_env(&mut cmd, settings);
602    // Matches the unjailed path — see `spawn_shell_with_settings`.
603    cmd.kill_on_drop(true);
604    cmd
605}
606
607#[cfg(target_os = "linux")]
608fn spawn_jailed_shell(
609    script_cmd: &str,
610    settings: &ScriptSettings,
611    jail: &ScriptJail,
612    home: &Path,
613) -> tokio::process::Command {
614    let mut cmd = spawn_shell_with_settings(script_cmd, settings);
615    let jail = jail.clone();
616    let home = home.to_path_buf();
617    unsafe {
618        cmd.pre_exec(move || {
619            linux_jail::apply_landlock(&jail, &home).map_err(std::io::Error::other)?;
620            if !jail.network {
621                linux_jail::apply_seccomp_net_filter().map_err(std::io::Error::other)?;
622            }
623            Ok(())
624        });
625    }
626    cmd
627}
628
629#[cfg(not(any(target_os = "linux", target_os = "macos")))]
630fn spawn_jailed_shell(
631    script_cmd: &str,
632    settings: &ScriptSettings,
633    _jail: &ScriptJail,
634    _home: &Path,
635) -> tokio::process::Command {
636    spawn_shell_with_settings(script_cmd, settings)
637}
638
639/// Shell-quote one arg for safe splicing into a shell command line.
640///
641/// Used by `aube run <script> -- args`. Args get joined into the
642/// script string, then sh -c or cmd /c reparses the whole thing. If
643/// user arg contains $, backticks, ;, |, &, (, ), etc, the shell
644/// interprets those as metacharacters. That is shell injection.
645/// `aube run echo 'hello; rm -rf ~'` would run two commands. Same
646/// issue npm had pre-2016. Quote each arg so shell treats it as one
647/// literal token.
648///
649/// Unix: wrap in single quotes. sh treats interior of '...' as pure
650/// literal with one exception, embedded single quote. Handle that
651/// with the standard '\'' escape trick: close the single-quoted
652/// string, emit an escaped quote, reopen. Works in every POSIX sh.
653///
654/// Windows cmd.exe: wrap in double quotes. cmd interprets many
655/// metachars even inside double quotes, but CreateProcessW hands the
656/// string to our spawn_shell that uses `/d /s /c "..."`, the outer
657/// quotes get stripped per /s rule and the content runs. Escape
658/// interior " and backslash per CommandLineToArgvW. Full cmd.exe
659/// metachar caret-escaping is a rabbit hole, so this is best-effort,
660/// works for the common cases, matches what node's shell-quote does.
661pub fn shell_quote_arg(arg: &str) -> String {
662    #[cfg(unix)]
663    {
664        let mut out = String::with_capacity(arg.len() + 2);
665        out.push('\'');
666        for ch in arg.chars() {
667            if ch == '\'' {
668                out.push_str("'\\''");
669            } else {
670                out.push(ch);
671            }
672        }
673        out.push('\'');
674        out
675    }
676    #[cfg(windows)]
677    {
678        let mut out = String::with_capacity(arg.len() + 2);
679        out.push('"');
680        let mut backslashes: usize = 0;
681        for ch in arg.chars() {
682            match ch {
683                '\\' => backslashes += 1,
684                '"' => {
685                    for _ in 0..backslashes * 2 + 1 {
686                        out.push('\\');
687                    }
688                    out.push('"');
689                    backslashes = 0;
690                }
691                // cmd.exe expands %VAR% even inside double quotes.
692                // Outer `/s /c "..."` only strips the outermost
693                // quote pair, the shell still runs env expansion
694                // on the body. Argument like `%COMSPEC%` would
695                // otherwise get replaced with the shell path
696                // before the child saw it. Double the percent so
697                // cmd passes a literal `%` through. Full
698                // caret-escaping of `^ & | < > ( )` is a deeper
699                // rabbit hole, this handles the common injection
700                // vector.
701                '%' => {
702                    for _ in 0..backslashes {
703                        out.push('\\');
704                    }
705                    backslashes = 0;
706                    out.push_str("%%");
707                }
708                _ => {
709                    for _ in 0..backslashes {
710                        out.push('\\');
711                    }
712                    backslashes = 0;
713                    out.push(ch);
714                }
715            }
716        }
717        for _ in 0..backslashes * 2 {
718            out.push('\\');
719        }
720        out.push('"');
721        out
722    }
723}
724
725/// Translate child ExitStatus to a parent exit code.
726///
727/// On Unix a signal-killed child has None from .code(). Old code
728/// collapsed that to 1. That loses signal identity: SIGKILL (OOM
729/// killer, exit 137), SIGSEGV (139), Ctrl-C (130) all look like
730/// plain exit 1. CI pipelines watching for 137 to detect OOM cannot
731/// distinguish it from a normal script error anymore. Bash convention
732/// is 128 + signum, match that.
733///
734/// Windows has no signal concept so .code() is always Some, the
735/// fallback 1 is dead code there but keeps the function total.
736pub fn exit_code_from_status(status: std::process::ExitStatus) -> i32 {
737    if let Some(code) = status.code() {
738        return code;
739    }
740    #[cfg(unix)]
741    {
742        use std::os::unix::process::ExitStatusExt;
743        if let Some(sig) = status.signal() {
744            return 128 + sig;
745        }
746    }
747    1
748}
749
750/// User agent string exported to lifecycle scripts as
751/// `npm_config_user_agent`. Mirrors pnpm's format
752/// (`<name>/<version> <os> <arch>`) so dep build scripts that sniff
753/// the env var to detect the running PM (e.g. `husky`,
754/// `unrs-resolver`) recognize aube without falling back to npm-mode.
755/// OS/arch use Node's `process.platform` / `process.arch` vocabulary
756/// (`darwin`/`linux`/`win32`, `x64`/`arm64`), not Rust's native
757/// `std::env::consts::{OS,ARCH}` values, so tools that parse the full
758/// UA string identify the platform the same way npm/yarn/pnpm do.
759pub fn aube_user_agent() -> String {
760    format!(
761        "{} {} {}",
762        aube_util::embedder().user_agent,
763        node_platform(),
764        node_arch(),
765    )
766}
767
768fn node_platform() -> &'static str {
769    match std::env::consts::OS {
770        "macos" => "darwin",
771        "windows" => "win32",
772        other => other,
773    }
774}
775
776fn node_arch() -> &'static str {
777    // Mappings from Rust's `std::env::consts::ARCH` to Node's
778    // `process.arch`. Common arches first; the rare ones at the bottom
779    // exist so the test below stays a real guarantee on every host
780    // Rust ships, not just x64/arm64. Pass-through covers `arm`,
781    // `mips`, `riscv64`, `s390x` — those tokens match between the two
782    // vocabularies.
783    match std::env::consts::ARCH {
784        "x86_64" => "x64",
785        "aarch64" => "arm64",
786        "x86" => "ia32",
787        "powerpc" => "ppc",
788        "powerpc64" => "ppc64",
789        "loongarch64" => "loong64",
790        other => other,
791    }
792}
793
794/// Resolve `npm_execpath` from the three inputs that decide it: the
795/// registered override ([`set_pm_execpath`]), whether a host embeds aube, and
796/// this process's own executable.
797///
798/// A host's override always wins. Failing that, only a standalone aube can
799/// name itself — embedded, the running executable answers to the host's CLI,
800/// so there is nothing to name and the variable stays unset.
801fn pm_execpath_for(
802    registered: Option<PathBuf>,
803    embedded: bool,
804    aube_exe: Option<PathBuf>,
805) -> Option<PathBuf> {
806    registered.or_else(|| (!embedded).then_some(aube_exe).flatten())
807}
808
809fn apply_script_settings_env(cmd: &mut tokio::process::Command, settings: &ScriptSettings) {
810    // Strip credentials that aube itself owns before we spawn any
811    // lifecycle script. AUBE_AUTH_TOKEN is aube's own registry login
812    // token. No transitive postinstall has any business reading it.
813    // NPM_TOKEN and NODE_AUTH_TOKEN stay untouched because release
814    // flows ("npm publish" in a postpublish script) genuinely need
815    // them. Matches what pnpm does today.
816    cmd.env_remove("AUBE_AUTH_TOKEN");
817    // pnpm parity: every lifecycle script gets `npm_config_user_agent`
818    // so dep postinstalls can detect the running PM. Set here (not at
819    // spawn time) so it flows through both the jailed and the
820    // non-jailed paths.
821    cmd.env("npm_config_user_agent", aube_user_agent());
822    // `npm_execpath`: the package-manager binary that drove the script.
823    // Tools (and pnpm's own `$npm_execpath run …` postinstalls) read it
824    // to re-invoke the *same* PM. Standalone, that is `current_exe()` —
825    // the aube binary; ignore the rare resolution failure rather than
826    // abort the script. Embedded, `current_exe()` is the *host* binary,
827    // whose CLI is its own, so a `${npm_execpath} run …` would land in
828    // the host's command surface: the caller supplies a shim that
829    // re-enters aube instead, and `None` leaves the variable unset (no
830    // reachable aube CLI) rather than naming a program that would
831    // misparse the command. `current_exe()` is still resolved here for
832    // `AUBE_CLI_EXE` / `AUBE_NODE_GYP_EXE`, so resolve it once.
833    //
834    // The removal is unconditional and comes first: a non-jailed spawn
835    // inherits this process's environment, so an aube running inside
836    // someone else's npm lifecycle would otherwise pass that outer
837    // manager's `npm_execpath` straight through to its own scripts — a
838    // stale path aube never chose, exactly where "unset" is the answer.
839    let aube_exe = std::env::current_exe().ok();
840    let pm_execpath = pm_execpath_for(
841        script_settings_state().pm_execpath,
842        aube_util::is_embedded(),
843        aube_exe.clone(),
844    );
845    cmd.env_remove("npm_execpath");
846    if let Some(execpath) = pm_execpath.as_deref() {
847        cmd.env("npm_execpath", execpath);
848    }
849    // `AUBE_CLI_EXE`: the executable that dispatches aube's CLI behind the
850    // private `__aube-cli` argv token — the running program, whether that
851    // is aube itself or an embedding host. The `npm_execpath` shim above
852    // reads it instead of baking a path into the cached file. Cleared
853    // first for the same reason as `npm_execpath`: should `current_exe()`
854    // fail, an inherited value would point the shim at whatever binary
855    // ran somewhere further up, not at this process.
856    cmd.env_remove(CLI_EXE_ENV);
857    if let Some(exe) = aube_exe.as_deref() {
858        cmd.env(CLI_EXE_ENV, exe);
859    }
860    // `npm_node_execpath` / `NODE`: the node binaries scripts should use
861    // — the switched runtime's node, or the ambient `node` on PATH. `NODE`
862    // is the program a script re-spawns (a wrapper's shim); the execpath
863    // is the *real* binary node-gyp reads for Node's install prefix. They
864    // coincide unless a wrapping embedder split them. Set here (not at
865    // spawn) so they survive the jail's `env_clear`.
866    let node_execpath = settings
867        .node_execpath
868        .as_deref()
869        .or(settings.node_program.as_deref());
870    if let Some(execpath) = node_execpath {
871        cmd.env("npm_node_execpath", execpath);
872    }
873    if let Some(node) = settings.node_program.as_deref().or(node_execpath) {
874        cmd.env("NODE", node);
875    }
876    // `npm_command`: the top-level PM command (run-script / install / …).
877    if let Some(command) = settings.command.as_deref() {
878        cmd.env("npm_command", command);
879    }
880    // `npm_config_node_gyp`: path to a runnable node-gyp. npm/pnpm bundle
881    // node-gyp and point this at its `bin/node-gyp.js`; aube hands out a
882    // lazy shim that resolves the bootstrapped node-gyp on first use. The
883    // shim trampolines back into aube via `AUBE_NODE_GYP_EXE`, so always
884    // stamp the running aube — it must be a real aube that implements
885    // `__node-gyp-bootstrap`, never an inherited/user-set value (which
886    // could be stale or wrong). `aube run` stamps the same value at its
887    // own spawn site; keeping both unconditional holds the two paths in
888    // lockstep. `AUBE_NODE_GYP_PROJECT_DIR` is optional — the shim falls
889    // back to the script's cwd.
890    if let Some(node_gyp_js) = settings.node_gyp_js.as_deref() {
891        cmd.env("npm_config_node_gyp", node_gyp_js);
892        if let Some(exe) = aube_exe.as_deref() {
893            cmd.env("AUBE_NODE_GYP_EXE", exe);
894        }
895    }
896    if let Some(node_options) = settings.node_options.as_deref() {
897        cmd.env("NODE_OPTIONS", node_options);
898    }
899    if let Some(unsafe_perm) = settings.unsafe_perm {
900        cmd.env(
901            "npm_config_unsafe_perm",
902            if unsafe_perm { "true" } else { "false" },
903        );
904    }
905    if settings.shell_emulator {
906        cmd.env("npm_config_shell_emulator", "true");
907    }
908    // Proxy passthrough. aube already resolved a proxy for its own
909    // registry traffic and forwards it to scripts as `npm_config_proxy`,
910    // but Node's built-in `fetch`/`http`/`https` only read the standard
911    // `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` vars, and only when
912    // `NODE_USE_ENV_PROXY=1` is set (Node 24+). Stamp all four so a
913    // dependency's install script hits the same proxy aube does. A proxy
914    // URL is not a secret, so this is safe to leak past the jail. Skip
915    // the whole block when no proxy is configured — no reason to flip
916    // Node's experimental env-proxy flag (which warns on Node 24) for a
917    // direct connection. Use the plain env var, never
918    // `NODE_OPTIONS=--use-env-proxy`: Node < 24 rejects that unknown
919    // flag and refuses to start, breaking installs; the plain var is
920    // silently ignored there instead. Set after `env_clear` (like `NODE`
921    // above) so it survives the jail.
922    if settings.http_proxy.is_some() || settings.https_proxy.is_some() {
923        if let Some(https) = settings.https_proxy.as_deref() {
924            cmd.env("HTTPS_PROXY", https);
925        }
926        if let Some(http) = settings.http_proxy.as_deref() {
927            cmd.env("HTTP_PROXY", http);
928        }
929        if let Some(no_proxy) = settings.no_proxy.as_deref() {
930            cmd.env("NO_PROXY", no_proxy);
931        }
932        cmd.env("NODE_USE_ENV_PROXY", "1");
933    }
934    // Embedder-contributed env, applied last (after `env_clear`, so it
935    // survives the jail) and after every aube-set var, so a wrapping
936    // host has the final say. `NODE_OPTIONS` is not among these — it is
937    // folded into `settings.node_options` upstream to preserve the
938    // user's value.
939    for (key, value) in &settings.extra_env {
940        cmd.env(key, value);
941    }
942}
943
944/// Apply the manifest-derived `npm_package_*` env (name, version,
945/// absolute `npm_package_json` path, and the deep-flattened
946/// `engines`/`config`/`bin`) plus `npm_lifecycle_script` (the raw
947/// script body) to a lifecycle or `aube run` command. Call last so the
948/// values land *after* any jail `env_clear`. `script_dir` is the
949/// directory the script runs in, whose `package.json` is the manifest
950/// being executed; `lifecycle_script` is the raw script body exported
951/// as `npm_lifecycle_script`.
952///
953/// pnpm rebuilds the `npm_package_*` namespace per package: it drops
954/// every inherited `npm_package_*` key and stamps only the running
955/// manifest's allowlist. We mirror that — scrub first, then re-stamp —
956/// so a script never sees a parent/sibling package's fields (verified
957/// against pnpm 11.5). Without the scrub, non-allowlisted inherited
958/// keys (e.g. an outer `npm run`'s `npm_package_description`) would
959/// leak through on the unjailed path and break allowlist parity. On
960/// the jailed path the prior `env_clear` already dropped them, so the
961/// scrub is a harmless no-op there.
962pub fn apply_npm_manifest_env(
963    cmd: &mut tokio::process::Command,
964    manifest: &PackageJson,
965    script_dir: &Path,
966    lifecycle_script: &str,
967) {
968    for (key, _) in std::env::vars_os() {
969        if key.to_str().is_some_and(|k| k.starts_with("npm_package_")) {
970            cmd.env_remove(&key);
971        }
972    }
973    cmd.env("npm_lifecycle_script", lifecycle_script);
974    cmd.env("npm_package_json", script_dir.join("package.json"));
975    for (key, value) in manifest.npm_package_env() {
976        cmd.env(key, value);
977    }
978}
979
980fn safe_jail_env_key(key: &str) -> bool {
981    const EXACT: &[&str] = &[
982        "PATH",
983        "HOME",
984        "TERM",
985        "LANG",
986        "LC_ALL",
987        "INIT_CWD",
988        "npm_lifecycle_event",
989        "npm_package_name",
990        "npm_package_version",
991    ];
992    if EXACT.contains(&key) {
993        return true;
994    }
995    let lower = key.to_ascii_lowercase();
996    if lower.contains("token")
997        || lower.contains("auth")
998        || lower.contains("password")
999        || lower.contains("credential")
1000        || lower.contains("secret")
1001    {
1002        return false;
1003    }
1004    key.starts_with("npm_config_")
1005}
1006
1007fn inherit_jail_env_key(key: &str, extra_env: &[String]) -> bool {
1008    (safe_jail_env_key(key) || extra_env.iter().any(|env| env == key))
1009        && !matches!(
1010            key,
1011            "PATH" | "HOME" | "npm_lifecycle_event" | "npm_package_name" | "npm_package_version"
1012        )
1013}
1014
1015fn jail_home(package_dir: &Path) -> PathBuf {
1016    let mut hasher = DefaultHasher::new();
1017    package_dir.hash(&mut hasher);
1018    let hash = hasher.finish();
1019    let name = package_dir
1020        .file_name()
1021        .and_then(|s| s.to_str())
1022        .unwrap_or("package")
1023        .chars()
1024        .map(|c| {
1025            if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
1026                c
1027            } else {
1028                '_'
1029            }
1030        })
1031        .collect::<String>();
1032    std::env::temp_dir()
1033        .join("aube-jail")
1034        .join(std::process::id().to_string())
1035        .join(format!("{name}-{hash:016x}"))
1036}
1037
1038fn apply_jail_env(
1039    cmd: &mut tokio::process::Command,
1040    path_env: &std::ffi::OsStr,
1041    home: &Path,
1042    project_root: &Path,
1043    manifest: &PackageJson,
1044    script_name: &str,
1045    extra_env: &[String],
1046) {
1047    cmd.env_clear();
1048    cmd.env("PATH", path_env)
1049        .env("HOME", home)
1050        .env("TMPDIR", home)
1051        .env("TMP", home)
1052        .env("TEMP", home)
1053        // `run_script` stamps this before entering the jail, but `env_clear`
1054        // removes it. Restore the outer project so the lazy node-gyp shim
1055        // inherits the right registry/auth and bootstrap-lock context.
1056        // `apply_script_settings_env` runs after this and intentionally lets
1057        // an embedder's `extra_env` override the default.
1058        .env("AUBE_NODE_GYP_PROJECT_DIR", project_root)
1059        .env("npm_lifecycle_event", script_name);
1060    if std::env::var_os("INIT_CWD").is_none() {
1061        cmd.env("INIT_CWD", project_root);
1062    }
1063    if let Some(ref name) = manifest.name {
1064        cmd.env("npm_package_name", name);
1065    }
1066    if let Some(ref version) = manifest.version {
1067        cmd.env("npm_package_version", version);
1068    }
1069    for (key, val) in std::env::vars_os() {
1070        let Some(key_str) = key.to_str() else {
1071            continue;
1072        };
1073        if inherit_jail_env_key(key_str, extra_env) {
1074            cmd.env(key, val);
1075        }
1076    }
1077}
1078
1079/// Lifecycle hooks that `aube install` runs against the root package's
1080/// `scripts` field, in this order: `preinstall` → (dependencies link) →
1081/// `install` → `postinstall` → `prepare`. Matches pnpm / npm.
1082#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1083pub enum LifecycleHook {
1084    PreInstall,
1085    Install,
1086    PostInstall,
1087    Prepare,
1088}
1089
1090impl LifecycleHook {
1091    pub fn script_name(self) -> &'static str {
1092        match self {
1093            Self::PreInstall => "preinstall",
1094            Self::Install => "install",
1095            Self::PostInstall => "postinstall",
1096            Self::Prepare => "prepare",
1097        }
1098    }
1099}
1100
1101/// Dependency lifecycle hooks, in the order aube runs them for each
1102/// allowlisted package. `prepare` is intentionally omitted — it's meant
1103/// for the root package and git-dep preparation, not installed tarballs.
1104pub const DEP_LIFECYCLE_HOOKS: [LifecycleHook; 3] = [
1105    LifecycleHook::PreInstall,
1106    LifecycleHook::Install,
1107    LifecycleHook::PostInstall,
1108];
1109
1110/// Holds the real stderr fd saved before `aube` redirects fd 2 to
1111/// `/dev/null` under `--silent`. Child processes spawned through
1112/// `child_stderr()` get a fresh dup of this fd so their stderr still
1113/// reaches the user's terminal — `--silent` only silences aube's own
1114/// output, not the scripts / binaries it invokes (matches `pnpm
1115/// --loglevel silent`). A value of `-1` means silent mode is off and
1116/// children should inherit stderr normally.
1117#[cfg(unix)]
1118static SAVED_STDERR_FD: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1);
1119
1120/// Called once by `aube` after it saves + redirects fd 2. Passing
1121/// the caller-owned saved fd here means child processes spawned via
1122/// `child_stderr()` will write to the real terminal stderr instead of
1123/// `/dev/null`.
1124#[cfg(unix)]
1125pub fn set_saved_stderr_fd(fd: std::os::fd::RawFd) {
1126    SAVED_STDERR_FD.store(fd, std::sync::atomic::Ordering::SeqCst);
1127}
1128
1129/// Windows has no equivalent fd-based silencing plumbing: aube's
1130/// `SilentStderrGuard` is `libc::dup`/`libc::dup2` on fd 2, and those
1131/// calls are gated to unix in `aube`. The stub keeps the public
1132/// API shape identical so call sites compile unchanged.
1133#[cfg(not(unix))]
1134pub fn set_saved_stderr_fd(_fd: i32) {}
1135
1136/// Returns a `Stdio` suitable for a child process's stderr. When silent
1137/// mode is active, this dups the saved real-stderr fd so the child
1138/// bypasses the `/dev/null` redirect on fd 2. Otherwise returns
1139/// `Stdio::inherit()`.
1140#[cfg(unix)]
1141pub fn child_stderr() -> std::process::Stdio {
1142    let fd = SAVED_STDERR_FD.load(std::sync::atomic::Ordering::SeqCst);
1143    if fd < 0 {
1144        return std::process::Stdio::inherit();
1145    }
1146    // SAFETY: `fd` was registered by `set_saved_stderr_fd` from a live
1147    // `dup` that `aube`'s `SilentStderrGuard` keeps open for the
1148    // duration of main. `BorrowedFd` only borrows, so this does not
1149    // transfer ownership.
1150    let borrowed = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) };
1151    match borrowed.try_clone_to_owned() {
1152        Ok(owned) => std::process::Stdio::from(owned),
1153        Err(_) => std::process::Stdio::inherit(),
1154    }
1155}
1156
1157#[cfg(not(unix))]
1158pub fn child_stderr() -> std::process::Stdio {
1159    std::process::Stdio::inherit()
1160}
1161
1162/// Write `line` plus a newline to the parent's real stderr. Used by
1163/// the recursive-run output multiplexer, which pipes child stderr
1164/// through aube and re-emits each line with a `<package>: ` prefix —
1165/// `eprintln!` writes to fd 2, which `SilentStderrGuard` has redirected
1166/// to `/dev/null` under `--silent`, so child stderr would otherwise be
1167/// silently swallowed in `--silent --parallel` mode. Routes through the
1168/// saved real-stderr fd when silent mode is active, fd 2 otherwise.
1169///
1170/// `write_all` of a pre-built `<line>\n` buffer issues a single short
1171/// write to the kernel; on TTYs and pipes the kernel's `PIPE_BUF`
1172/// (= 4096+ on every supported unix) atomicity keeps lines from
1173/// concurrent pump tasks intact without explicit locking. The dup
1174/// happens per line so we don't share a long-lived `File` handle that
1175/// would need its own lock — a duplicate `write` syscall pair is
1176/// cheaper than an `Arc<Mutex<File>>` and correct under concurrency.
1177#[cfg(unix)]
1178pub fn write_line_to_real_stderr(line: &str) {
1179    use std::io::Write;
1180    let saved = SAVED_STDERR_FD.load(std::sync::atomic::Ordering::SeqCst);
1181    let fd = if saved >= 0 { saved } else { 2 };
1182    // SAFETY: `fd` is either the saved real-stderr fd (kept live by
1183    // `SilentStderrGuard` for the duration of main) or fd 2 (always
1184    // open). `BorrowedFd` only borrows; ownership stays with the
1185    // saved-fd / std-stream side and `try_clone_to_owned` issues a
1186    // `dup` so dropping the resulting `File` does not close fd 2 or
1187    // the saved fd.
1188    let borrowed = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) };
1189    let Ok(owned) = borrowed.try_clone_to_owned() else {
1190        return;
1191    };
1192    let mut file = std::fs::File::from(owned);
1193    let mut buf = String::with_capacity(line.len() + 1);
1194    buf.push_str(line);
1195    buf.push('\n');
1196    let _ = file.write_all(buf.as_bytes());
1197}
1198
1199#[cfg(not(unix))]
1200pub fn write_line_to_real_stderr(line: &str) {
1201    eprintln!("{line}");
1202}
1203
1204/// Spawn `cmd`, wait for it, and on Windows attach the shell to a
1205/// kill-on-job-close job object so an aborted lifecycle script reaps
1206/// its full descendant tree instead of leaving orphans behind.
1207///
1208/// `kill_on_drop(true)` on the parent `Command` (set by
1209/// [`spawn_shell_with_settings`]) covers `TerminateProcess` /
1210/// `SIGKILL` on the direct shell. That alone is enough on Unix
1211/// because most build tooling handles the parent dying — and the
1212/// shell itself is the foreground process for the subscript pipeline.
1213/// On Windows the shell's grandchildren (`node-gyp` → `MSBuild` →
1214/// `node`) are *not* part of the shell's job by default, so killing
1215/// the shell leaves them running detached. Discussion #654 is the
1216/// in-the-wild bug: `aube add --global` failed, aube exited, and
1217/// node/MSBuild kept writing to the console.
1218///
1219/// We mitigate by spawning, then assigning the child process handle
1220/// to a job created with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`. The
1221/// `_job` binding's `Drop` (called when this future returns, panics,
1222/// or is aborted) closes the last job handle, and the kernel kills
1223/// every assigned process — including everything the shell has
1224/// spawned by that point. There is a microscopic race between spawn
1225/// and `AssignProcessToJobObject`, but the shell does not have time
1226/// to spawn anything in that window; the `tokio::process::Child`
1227/// returns control to us synchronously after `CreateProcessW`
1228/// returns.
1229///
1230/// Job-object failures are fail-open: restricted Windows environments
1231/// (nested-job parents, container policy, handle quota) can refuse
1232/// either `CreateJobObjectW` or `AssignProcessToJobObject`. In those
1233/// cases we surface a `WARN_AUBE_WINDOWS_JOB_OBJECT_UNAVAILABLE`
1234/// warning and run the script anyway — degrading to the
1235/// `kill_on_drop`-only path that aube used before this fix. Failing
1236/// closed would block lifecycle scripts entirely on those hosts,
1237/// which is a worse regression than the orphaning we're trying to
1238/// avoid.
1239async fn run_command_killing_descendants(
1240    mut cmd: tokio::process::Command,
1241    script_name: &str,
1242) -> Result<std::process::ExitStatus, Error> {
1243    let output_reporter = script_settings_state().output_reporter;
1244    if output_reporter.is_some() {
1245        cmd.stdout(std::process::Stdio::piped())
1246            .stderr(std::process::Stdio::piped());
1247    }
1248    let mut child = cmd
1249        .spawn()
1250        .map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()))?;
1251    #[cfg(windows)]
1252    let _job = match windows_job::JobObject::new() {
1253        Ok(job) => {
1254            // raw_handle() returns None only if the child has already
1255            // been reaped, which can't happen between spawn() and the
1256            // very next line.
1257            if let Some(handle) = child.raw_handle()
1258                && let Err(err) = job.assign(handle)
1259            {
1260                // Realistic causes: parent job created without
1261                // JOB_OBJECT_LIMIT_BREAKAWAY_OK (pre-Win8 nested-job
1262                // restrictions, enterprise policy), or the shell
1263                // already exited. In either case the kill-tree
1264                // guarantee is gone — log loud enough that CI logs
1265                // pick it up.
1266                tracing::warn!(
1267                    code = aube_codes::warnings::WARN_AUBE_WINDOWS_JOB_OBJECT_UNAVAILABLE,
1268                    "windows: AssignProcessToJobObject failed for `{script_name}` shell ({err}); \
1269                     grandchildren may be orphaned if the script is aborted"
1270                );
1271            }
1272            Some(job)
1273        }
1274        Err(err) => {
1275            tracing::warn!(
1276                code = aube_codes::warnings::WARN_AUBE_WINDOWS_JOB_OBJECT_UNAVAILABLE,
1277                "windows: CreateJobObjectW failed for `{script_name}` shell ({err}); \
1278                 running without orphan-reaping — grandchildren may leak if aborted"
1279            );
1280            None
1281        }
1282    };
1283    let Some(reporter) = output_reporter else {
1284        return child
1285            .wait()
1286            .await
1287            .map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()));
1288    };
1289    let stdout = child.stdout.take().ok_or_else(|| {
1290        Error::Spawn(
1291            script_name.to_string(),
1292            "failed to capture lifecycle stdout".to_string(),
1293        )
1294    })?;
1295    let stderr = child.stderr.take().ok_or_else(|| {
1296        Error::Spawn(
1297            script_name.to_string(),
1298            "failed to capture lifecycle stderr".to_string(),
1299        )
1300    })?;
1301    let (status, stdout_result, stderr_result) = tokio::join!(
1302        child.wait(),
1303        report_script_output(stdout, ScriptOutputStream::Stdout, reporter.clone()),
1304        report_script_output(stderr, ScriptOutputStream::Stderr, reporter),
1305    );
1306    stdout_result.map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()))?;
1307    stderr_result.map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()))?;
1308    status.map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()))
1309}
1310
1311async fn report_script_output<R: tokio::io::AsyncRead + Unpin>(
1312    reader: R,
1313    stream: ScriptOutputStream,
1314    reporter: std::sync::Arc<dyn ScriptOutputReporter>,
1315) -> std::io::Result<()> {
1316    let mut reader = tokio::io::BufReader::new(reader);
1317    let mut buffer = Vec::new();
1318    let mut continued_record = false;
1319    loop {
1320        buffer.clear();
1321        let mut limited = (&mut reader).take(MAX_SCRIPT_OUTPUT_RECORD_BYTES as u64);
1322        if limited.read_until(b'\n', &mut buffer).await? == 0 {
1323            return Ok(());
1324        }
1325        let record_terminated = buffer.last() == Some(&b'\n');
1326        if record_terminated {
1327            buffer.pop();
1328            if buffer.last() == Some(&b'\r') {
1329                buffer.pop();
1330            }
1331        }
1332        if !(continued_record && record_terminated && buffer.is_empty()) {
1333            reporter.report(stream, String::from_utf8_lossy(&buffer).into_owned());
1334        }
1335        continued_record = !record_terminated;
1336    }
1337}
1338
1339#[cfg(test)]
1340mod script_output_tests {
1341    use super::*;
1342    use tokio::io::AsyncWriteExt;
1343
1344    #[derive(Default)]
1345    struct RecordingReporter(std::sync::Mutex<Vec<String>>);
1346
1347    impl ScriptOutputReporter for RecordingReporter {
1348        fn report(&self, _stream: ScriptOutputStream, line: String) {
1349            self.0.lock().unwrap().push(line);
1350        }
1351    }
1352
1353    #[tokio::test]
1354    async fn unterminated_output_is_reported_in_bounded_chunks() {
1355        let reporter = std::sync::Arc::new(RecordingReporter::default());
1356        let (mut writer, reader) = tokio::io::duplex(1024);
1357        let mut output = vec![b'x'; MAX_SCRIPT_OUTPUT_RECORD_BYTES * 2 + 17];
1358        output.extend_from_slice(b"\nnext\n");
1359        let write = tokio::spawn(async move {
1360            writer.write_all(&output).await.unwrap();
1361        });
1362
1363        report_script_output(reader, ScriptOutputStream::Stdout, reporter.clone())
1364            .await
1365            .unwrap();
1366        write.await.unwrap();
1367
1368        let messages = reporter.0.lock().unwrap();
1369        assert_eq!(
1370            messages.iter().map(String::len).collect::<Vec<_>>(),
1371            [
1372                MAX_SCRIPT_OUTPUT_RECORD_BYTES,
1373                MAX_SCRIPT_OUTPUT_RECORD_BYTES,
1374                17,
1375                4,
1376            ]
1377        );
1378        assert_eq!(messages.last().map(String::as_str), Some("next"));
1379    }
1380}
1381
1382/// Run a single npm-style script line through `sh -c` with the usual
1383/// environment (`$PATH` extended with `node_modules/.bin`, `INIT_CWD`,
1384/// `npm_lifecycle_event`, `npm_package_name`, `npm_package_version`).
1385///
1386/// `extra_bin_dirs` are prepended to `PATH` in order, *before* the
1387/// project-level `.bin`. Dep lifecycle scripts pass the dep's own
1388/// sibling `node_modules/.bin/` so transitive binaries (e.g.
1389/// `prebuild-install`, `node-gyp`) declared in the dep's
1390/// `dependencies` are reachable, optionally followed by aube-owned
1391/// tool dirs (e.g. the bootstrapped node-gyp). Root scripts pass
1392/// `&[]` — their transitive bins are already hoisted into the
1393/// project-level `.bin`.
1394///
1395/// Inherits stdio from the parent so the user sees script output live, unless
1396/// an embedding host installed a [`ScriptOutputReporter`].
1397/// Returns Err on non-zero exit so install fails fast if a lifecycle
1398/// script breaks, matching pnpm.
1399#[allow(clippy::too_many_arguments)]
1400pub async fn run_script(
1401    script_dir: &Path,
1402    project_root: &Path,
1403    modules_dir_name: &str,
1404    manifest: &PackageJson,
1405    script_name: &str,
1406    script_cmd: &str,
1407    extra_bin_dirs: &[&Path],
1408    jail: Option<&ScriptJail>,
1409) -> Result<(), Error> {
1410    // Per-script diag span. Tags the package name (when present) and the
1411    // script name so the analyzer can attribute postinstall / preinstall /
1412    // build cost to the exact lifecycle entry rather than the aggregate
1413    // `dep_lifecycle` phase total.
1414    let _diag = aube_util::diag::Span::new(aube_util::diag::Category::Script, "run_script")
1415        .with_meta_fn(|| {
1416            let pkg = manifest.name.as_deref().unwrap_or("(root)");
1417            format!(
1418                r#"{{"pkg":{},"script":{}}}"#,
1419                aube_util::diag::jstr(pkg),
1420                aube_util::diag::jstr(script_name)
1421            )
1422        });
1423    // PATH prepends (most-local-first): `extra_bin_dirs` in caller
1424    // order, then the project root's `<modules_dir>/.bin`. For root
1425    // scripts `script_dir == project_root` and `extra_bin_dirs` is
1426    // empty, which matches the old behavior. `modules_dir_name`
1427    // honors pnpm's `modulesDir` setting — defaults to
1428    // `"node_modules"` at the call site, but a workspace may have
1429    // configured something else.
1430    let project_bin = project_root.join(modules_dir_name).join(".bin");
1431    let state = script_settings_state();
1432    let settings = &state.settings;
1433    let path = std::env::var_os("PATH").unwrap_or_default();
1434    let mut project_bins: Vec<PathBuf> = Vec::with_capacity(extra_bin_dirs.len() + 1);
1435    for dir in extra_bin_dirs {
1436        project_bins.push(dir.to_path_buf());
1437    }
1438    project_bins.push(project_bin);
1439    let mut entries = order_path_entries(
1440        project_bins,
1441        settings.node_bin_dir.as_deref(),
1442        state.node_bin_dir_precedes_project_bins,
1443    );
1444    entries.extend(std::env::split_paths(&path));
1445    let new_path = std::env::join_paths(entries).unwrap_or(path);
1446    let jail_home = jail.map(|j| jail_home(&j.package_dir));
1447    if let Some(home) = &jail_home {
1448        std::fs::create_dir_all(home)
1449            .map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()))?;
1450    }
1451    let mut cmd = match (jail, jail_home.as_deref()) {
1452        (Some(jail), Some(home)) => spawn_jailed_shell(script_cmd, settings, jail, home),
1453        _ => spawn_shell_with_settings(script_cmd, settings),
1454    };
1455    cmd.current_dir(script_dir)
1456        .stderr(child_stderr())
1457        .env("PATH", &new_path)
1458        .env("npm_lifecycle_event", script_name);
1459
1460    // Pass INIT_CWD the way npm/pnpm do — the directory the user
1461    // invoked the package manager from, *not* the script's own cwd.
1462    // Native-module build tooling (node-gyp, prebuild-install, etc.)
1463    // reads INIT_CWD to locate the project root when caching binaries.
1464    // Preserve if already set by a parent aube invocation so nested
1465    // scripts see the outermost cwd.
1466    if std::env::var_os("INIT_CWD").is_none() {
1467        cmd.env("INIT_CWD", project_root);
1468    }
1469
1470    if let (Some(jail), Some(home)) = (jail, jail_home.as_deref()) {
1471        apply_jail_env(
1472            &mut cmd,
1473            &new_path,
1474            home,
1475            project_root,
1476            manifest,
1477            script_name,
1478            &jail.env,
1479        );
1480        apply_script_settings_env(&mut cmd, settings);
1481    } else {
1482        // The lazy node-gyp shim needs the outer project for registry/auth
1483        // settings and bootstrap locking. The jailed branch restores this in
1484        // `apply_jail_env` after clearing the environment.
1485        cmd.env("AUBE_NODE_GYP_PROJECT_DIR", project_root);
1486    }
1487
1488    // npm-compat manifest env, applied last so it survives the jail's
1489    // `env_clear`: name/version/json plus the deep-flattened
1490    // engines/config/bin, and the raw script body (`npm_lifecycle_script`).
1491    apply_npm_manifest_env(&mut cmd, manifest, script_dir, script_cmd);
1492
1493    tracing::debug!("lifecycle: {script_name} → {script_cmd}");
1494    let status = run_command_killing_descendants(cmd, script_name).await?;
1495
1496    if !status.success() {
1497        return Err(Error::NonZeroExit {
1498            script: script_name.to_string(),
1499            code: status.code(),
1500        });
1501    }
1502
1503    Ok(())
1504}
1505
1506/// Run a lifecycle hook against the root package, if a script for it is
1507/// defined. Returns `Ok(false)` if the hook wasn't defined (no-op),
1508/// `Ok(true)` if it ran successfully.
1509///
1510/// The caller is responsible for gating on `--ignore-scripts`.
1511pub async fn run_root_hook(
1512    project_dir: &Path,
1513    modules_dir_name: &str,
1514    manifest: &PackageJson,
1515    hook: LifecycleHook,
1516) -> Result<bool, Error> {
1517    run_root_script_by_name(project_dir, modules_dir_name, manifest, hook.script_name()).await
1518}
1519
1520/// Run a named root-package script if it's defined. Used by commands
1521/// (pack, publish, version) that need to run lifecycle hooks outside
1522/// the install-focused [`LifecycleHook`] enum. Returns `Ok(false)` if
1523/// the script isn't defined.
1524///
1525/// The caller is responsible for gating on `--ignore-scripts`.
1526pub async fn run_root_script_by_name(
1527    project_dir: &Path,
1528    modules_dir_name: &str,
1529    manifest: &PackageJson,
1530    name: &str,
1531) -> Result<bool, Error> {
1532    let Some(script_cmd) = manifest.scripts.get(name) else {
1533        return Ok(false);
1534    };
1535    run_script(
1536        project_dir,
1537        project_dir,
1538        modules_dir_name,
1539        manifest,
1540        name,
1541        script_cmd,
1542        &[],
1543        None,
1544    )
1545    .await?;
1546    Ok(true)
1547}
1548
1549/// Single source of truth for the implicit `node-gyp rebuild`
1550/// fallback: returns `Some("node-gyp rebuild")` when the package ships
1551/// a `binding.gyp` at its root AND the manifest leaves both `install`
1552/// and `preinstall` empty (either one is the author's explicit
1553/// opt-out from the default).
1554///
1555/// `has_binding_gyp` is passed by the caller so this helper is
1556/// agnostic to *how* presence was detected — the install pipeline
1557/// stats the materialized package dir, while `aube ignored-builds`
1558/// reads the store `PackageIndex` since the package may not be
1559/// linked into `node_modules` yet. Both paths must agree on the gate
1560/// condition, so they both go through this.
1561pub fn implicit_install_script(
1562    manifest: &PackageJson,
1563    has_binding_gyp: bool,
1564) -> Option<&'static str> {
1565    if !has_binding_gyp {
1566        return None;
1567    }
1568    if manifest
1569        .scripts
1570        .contains_key(LifecycleHook::Install.script_name())
1571        || manifest
1572            .scripts
1573            .contains_key(LifecycleHook::PreInstall.script_name())
1574    {
1575        return None;
1576    }
1577    Some("node-gyp rebuild")
1578}
1579
1580/// Default `install` command for a materialized dependency directory.
1581/// Thin wrapper around [`implicit_install_script`] that supplies
1582/// `has_binding_gyp` by stat'ing `<package_dir>/binding.gyp`.
1583pub fn default_install_script(package_dir: &Path, manifest: &PackageJson) -> Option<&'static str> {
1584    implicit_install_script(manifest, package_dir.join("binding.gyp").is_file())
1585}
1586
1587/// True if [`run_dep_hook`] would actually execute something for this
1588/// package across any of the dependency lifecycle hooks. Callers use
1589/// this to skip fan-out work for packages that have nothing to run —
1590/// including the implicit `node-gyp rebuild` default.
1591pub fn has_dep_lifecycle_work(package_dir: &Path, manifest: &PackageJson) -> bool {
1592    if DEP_LIFECYCLE_HOOKS
1593        .iter()
1594        .any(|h| manifest.scripts.contains_key(h.script_name()))
1595    {
1596        return true;
1597    }
1598    default_install_script(package_dir, manifest).is_some()
1599}
1600
1601/// Run a lifecycle hook against an installed dependency's package
1602/// directory. Mirrors [`run_root_hook`] but spawns inside `package_dir`
1603/// (the actual linked package directory, e.g.
1604/// `node_modules/.aube/<dep_path>/node_modules/<name>`). The manifest
1605/// is the dependency's own `package.json`, *not* the project root's.
1606///
1607/// `dep_modules_dir` is the dep's sibling `node_modules/` — i.e.
1608/// `package_dir`'s parent for unscoped packages, or `package_dir`'s
1609/// grandparent for scoped (`@scope/name`). `<dep_modules_dir>/.bin`
1610/// is prepended to `PATH` so the dep's postinstall can spawn tools
1611/// declared in its own `dependencies` (the transitive-bin case —
1612/// `prebuild-install`, `node-gyp`, `napi-postinstall`). The install
1613/// driver writes shims there via `link_dep_bins`; `rebuild` mirrors
1614/// the same pass.
1615///
1616/// `<package_dir>/node_modules/.bin` is prepended ahead of it, for the
1617/// dependencies that live inside the package itself: bundled deps, and
1618/// under `nodeLinker=hoisted` any dep a version conflict nested there.
1619///
1620/// For the `install` hook specifically, if the manifest leaves both
1621/// `install` and `preinstall` empty but the package has a top-level
1622/// `binding.gyp`, this falls back to running `node-gyp rebuild` — the
1623/// node-gyp default that npm and pnpm both honor so native modules
1624/// without a prebuilt binary still compile on install.
1625///
1626/// `tool_bin_dirs` are prepended to `PATH` *after* the dep's own
1627/// `.bin` so that aube-bootstrapped tools (e.g. node-gyp) fill the
1628/// gap for deps that shell out to them without declaring them as
1629/// their own `dependencies`. The dep's local bin still wins if it
1630/// shipped its own copy.
1631///
1632/// The caller is responsible for gating on `BuildPolicy` and
1633/// `--ignore-scripts`. Returns `Ok(false)` if the hook wasn't defined.
1634#[allow(clippy::too_many_arguments)]
1635pub async fn run_dep_hook(
1636    package_dir: &Path,
1637    dep_modules_dir: &Path,
1638    project_root: &Path,
1639    modules_dir_name: &str,
1640    manifest: &PackageJson,
1641    hook: LifecycleHook,
1642    tool_bin_dirs: &[&Path],
1643    jail: Option<&ScriptJail>,
1644) -> Result<bool, Error> {
1645    let name = hook.script_name();
1646    let script_cmd: &str = match manifest.scripts.get(name) {
1647        Some(s) => s.as_str(),
1648        None => match hook {
1649            LifecycleHook::Install => match default_install_script(package_dir, manifest) {
1650                Some(s) => s,
1651                None => return Ok(false),
1652            },
1653            _ => return Ok(false),
1654        },
1655    };
1656    // Most-local-first, the way Node resolves and `@npmcli/run-script`
1657    // builds `PATH`: the package's *own* nested `node_modules/.bin`,
1658    // then the `.bin` of the directory the package sits in.
1659    //
1660    // The nested one matters under `nodeLinker=hoisted`. A version
1661    // conflict places the losing copy at
1662    // `<requester>/node_modules/<dep>`, so its bin is written to
1663    // `<requester>/node_modules/.bin` — one level *below* the `.bin`
1664    // that holds the requester's siblings. Without this entry the
1665    // requester's own install script couldn't see the dependency it
1666    // forced to nest. Nested `node_modules` is always literally
1667    // `node_modules` (Node looks for nothing else), so `modules_dir`
1668    // doesn't apply here.
1669    let nested_bin_dir = package_dir.join("node_modules").join(".bin");
1670    let dep_bin_dir = dep_modules_dir.join(".bin");
1671    let mut bin_dirs: Vec<&Path> = Vec::with_capacity(tool_bin_dirs.len() + 2);
1672    if nested_bin_dir != dep_bin_dir {
1673        bin_dirs.push(&nested_bin_dir);
1674    }
1675    bin_dirs.push(&dep_bin_dir);
1676    bin_dirs.extend(tool_bin_dirs.iter().copied());
1677    run_script(
1678        package_dir,
1679        project_root,
1680        modules_dir_name,
1681        manifest,
1682        name,
1683        script_cmd,
1684        &bin_dirs,
1685        jail,
1686    )
1687    .await?;
1688    Ok(true)
1689}
1690
1691#[derive(Debug, thiserror::Error, miette::Diagnostic)]
1692pub enum Error {
1693    #[error("failed to spawn script {0}: {1}")]
1694    #[diagnostic(code(ERR_AUBE_SCRIPT_SPAWN))]
1695    Spawn(String, String),
1696    #[error("script `{script}` exited with code {code:?}")]
1697    #[diagnostic(code(ERR_AUBE_SCRIPT_NON_ZERO_EXIT))]
1698    NonZeroExit { script: String, code: Option<i32> },
1699}
1700
1701#[cfg(test)]
1702mod user_agent_tests {
1703    use super::*;
1704
1705    #[test]
1706    fn user_agent_uses_node_style_platform_and_arch() {
1707        let ua = aube_user_agent();
1708        // Format: "aube/<version> <platform> <arch>"
1709        assert!(ua.starts_with("aube/"), "unexpected prefix: {ua}");
1710        let parts: Vec<&str> = ua.split(' ').collect();
1711        assert_eq!(parts.len(), 3, "expected 3 space-separated fields: {ua}");
1712        // Platform must be a Node-style token, not Rust's `macos`/`windows`.
1713        let platform = parts[1];
1714        assert!(
1715            matches!(
1716                platform,
1717                "darwin" | "linux" | "win32" | "freebsd" | "openbsd" | "netbsd" | "dragonfly"
1718            ),
1719            "platform `{platform}` should follow Node's `process.platform` vocabulary"
1720        );
1721        // Arch must be a Node-style token, not Rust's `x86_64`/`aarch64`.
1722        // Allowlist is the union of mapped outputs (`node_arch`) and the
1723        // pass-through tokens that already match Node's vocabulary.
1724        let arch = parts[2];
1725        assert!(
1726            matches!(
1727                arch,
1728                "x64"
1729                    | "arm64"
1730                    | "ia32"
1731                    | "arm"
1732                    | "ppc"
1733                    | "ppc64"
1734                    | "loong64"
1735                    | "mips"
1736                    | "riscv64"
1737                    | "s390x"
1738            ),
1739            "arch `{arch}` should follow Node's `process.arch` vocabulary"
1740        );
1741    }
1742}
1743
1744#[cfg(test)]
1745mod spawn_program_tests {
1746    use super::*;
1747
1748    fn env_keys(cmd: &tokio::process::Command) -> Vec<String> {
1749        let mut keys: Vec<String> = cmd
1750            .as_std()
1751            .get_envs()
1752            .map(|(k, _)| k.to_string_lossy().into_owned())
1753            .collect();
1754        keys.sort();
1755        keys
1756    }
1757
1758    /// The direct path must be indistinguishable from the shell path as
1759    /// far as the child's environment goes. Diffing the two commands
1760    /// pins that mechanically, rather than trusting that two call sites
1761    /// stamp the same list — `aube run` exports a documented `npm_*`
1762    /// surface that build tooling reads.
1763    #[tokio::test]
1764    async fn spawn_program_stamps_the_same_env_as_spawn_shell() {
1765        let settings = ScriptSettings {
1766            node_options: Some("--max-old-space-size=100".to_string()),
1767            node_program: Some(PathBuf::from("/usr/bin/node")),
1768            node_execpath: Some(PathBuf::from("/usr/bin/node")),
1769            command: Some("run-script".to_string()),
1770            http_proxy: Some("http://proxy.invalid".to_string()),
1771            https_proxy: Some("http://proxy.invalid".to_string()),
1772            ..ScriptSettings::default()
1773        };
1774        scope(async move {
1775            set_script_settings(settings);
1776            let shell = spawn_shell("tool --flag");
1777            let direct = spawn_program(Path::new("/usr/bin/tool"), "tool", ["--flag"]);
1778            assert_eq!(
1779                env_keys(&shell),
1780                env_keys(&direct),
1781                "direct exec must export the same env keys as `sh -c`"
1782            );
1783        })
1784        .await;
1785    }
1786
1787    /// A dep's own nested `node_modules/.bin` must beat the `.bin` of the
1788    /// directory the dep sits in. Under `nodeLinker=hoisted` a version
1789    /// conflict places the losing copy at `<requester>/node_modules/<dep>`,
1790    /// so the requester's install script has to look inside itself first
1791    /// — otherwise it silently runs whichever version won the hoist.
1792    /// Reproduced with `bcrypt`, whose `install` picked up
1793    /// `node-pre-gyp@2` from the root instead of its own `^1.0.5`.
1794    #[cfg(unix)]
1795    #[tokio::test]
1796    async fn dep_hook_prefers_the_packages_own_nested_bin() {
1797        // `tempfile` is not a dep of this crate; std::env::temp_dir plus
1798        // nanos is enough, matching `aborting_script_kills_grandchildren`.
1799        let nanos = std::time::SystemTime::now()
1800            .duration_since(std::time::UNIX_EPOCH)
1801            .unwrap_or_default()
1802            .as_nanos();
1803        let root = std::env::temp_dir().join(format!("aube-test-nested-bin-{nanos}"));
1804        let root = root.as_path();
1805        let package_dir = root.join("node_modules/requester");
1806        let marker = root.join("which-ran.txt");
1807
1808        // Sibling `.bin` (the hoist winner) and the requester's own nested
1809        // `.bin` (the copy it actually declares) both offer `tool`.
1810        for (bin_dir, tag) in [
1811            (root.join("node_modules/.bin"), "sibling"),
1812            (package_dir.join("node_modules/.bin"), "nested"),
1813        ] {
1814            std::fs::create_dir_all(&bin_dir).unwrap();
1815            let tool = bin_dir.join("tool");
1816            std::fs::write(
1817                &tool,
1818                format!("#!/bin/sh\nprintf {tag} > \"{}\"\n", marker.display()),
1819            )
1820            .unwrap();
1821            let mut perms = std::fs::metadata(&tool).unwrap().permissions();
1822            std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755);
1823            std::fs::set_permissions(&tool, perms).unwrap();
1824        }
1825
1826        let mut scripts = std::collections::BTreeMap::new();
1827        scripts.insert("postinstall".to_string(), "tool".to_string());
1828        let manifest = PackageJson {
1829            name: Some("requester".to_string()),
1830            version: Some("1.0.0".to_string()),
1831            scripts,
1832            ..PackageJson::default()
1833        };
1834
1835        let ran = run_dep_hook(
1836            &package_dir,
1837            // What `dep_modules_dir_for` yields for this package: the
1838            // `node_modules/` the package itself sits in.
1839            &root.join("node_modules"),
1840            root,
1841            "node_modules",
1842            &manifest,
1843            LifecycleHook::PostInstall,
1844            &[],
1845            None,
1846        )
1847        .await
1848        .unwrap();
1849
1850        let which_ran = std::fs::read_to_string(&marker);
1851        let _ = std::fs::remove_dir_all(root);
1852        assert!(ran, "postinstall is defined, so it should have run");
1853        assert_eq!(
1854            which_ran.unwrap(),
1855            "nested",
1856            "the package's own nested `.bin` must win over its siblings'"
1857        );
1858    }
1859
1860    #[cfg(unix)]
1861    #[tokio::test]
1862    async fn spawn_program_runs_the_program_with_its_args() {
1863        let mut cmd = spawn_program(Path::new("/bin/echo"), "echo", ["a b", "$HOME"]);
1864        let out = cmd.output().await.unwrap();
1865        assert!(out.status.success());
1866        // `$HOME` arrives literally: there is no shell to expand it.
1867        assert_eq!(String::from_utf8_lossy(&out.stdout), "a b $HOME\n");
1868    }
1869}
1870
1871#[cfg(test)]
1872mod jail_tests {
1873    use super::*;
1874
1875    #[test]
1876    fn jail_home_uses_full_package_path() {
1877        let a = jail_home(Path::new("/tmp/project/node_modules/@scope-a/native"));
1878        let b = jail_home(Path::new("/tmp/project/node_modules/@scope-b/native"));
1879
1880        assert_ne!(a, b);
1881        assert!(
1882            a.file_name()
1883                .unwrap()
1884                .to_string_lossy()
1885                .starts_with("native-")
1886        );
1887        assert!(
1888            b.file_name()
1889                .unwrap()
1890                .to_string_lossy()
1891                .starts_with("native-")
1892        );
1893    }
1894
1895    #[test]
1896    fn jail_home_cleanup_removes_temp_home() {
1897        let package_dir = std::env::temp_dir()
1898            .join("aube-jail-cleanup-test")
1899            .join(std::process::id().to_string())
1900            .join("node_modules")
1901            .join("native");
1902        let jail = ScriptJail::new(&package_dir);
1903        let home = jail_home(&package_dir);
1904        std::fs::create_dir_all(home.join(".cache")).unwrap();
1905        std::fs::write(home.join(".cache").join("marker"), "x").unwrap();
1906
1907        {
1908            let _cleanup = ScriptJailHomeCleanup::new(&jail);
1909        }
1910
1911        assert!(!home.exists());
1912    }
1913
1914    #[test]
1915    fn parent_env_cannot_override_explicit_jail_metadata() {
1916        for key in [
1917            "PATH",
1918            "HOME",
1919            "npm_lifecycle_event",
1920            "npm_package_name",
1921            "npm_package_version",
1922        ] {
1923            assert!(!inherit_jail_env_key(key, &[]));
1924        }
1925        assert!(inherit_jail_env_key("INIT_CWD", &[]));
1926        assert!(inherit_jail_env_key("npm_config_arch", &[]));
1927        assert!(!inherit_jail_env_key("npm_config__authToken", &[]));
1928        assert!(inherit_jail_env_key(
1929            "SHARP_DIST_BASE_URL",
1930            &["SHARP_DIST_BASE_URL".to_string()]
1931        ));
1932    }
1933
1934    #[test]
1935    fn jail_env_preserves_script_settings_after_clear() {
1936        let mut cmd = tokio::process::Command::new("node");
1937        let manifest = PackageJson {
1938            name: Some("pkg".to_string()),
1939            version: Some("1.2.3".to_string()),
1940            ..Default::default()
1941        };
1942        let settings = ScriptSettings {
1943            node_options: Some("--conditions=aube".to_string()),
1944            unsafe_perm: Some(false),
1945            shell_emulator: true,
1946            ..Default::default()
1947        };
1948
1949        apply_jail_env(
1950            &mut cmd,
1951            std::ffi::OsStr::new("/bin"),
1952            Path::new("/tmp/aube-jail/home"),
1953            Path::new("/tmp/project"),
1954            &manifest,
1955            "postinstall",
1956            &[],
1957        );
1958        apply_script_settings_env(&mut cmd, &settings);
1959
1960        let envs = cmd.as_std().get_envs().collect::<Vec<_>>();
1961        let env = |name: &str| {
1962            envs.iter()
1963                .find(|(key, _)| *key == std::ffi::OsStr::new(name))
1964                .and_then(|(_, val)| *val)
1965                .and_then(|val| val.to_str())
1966        };
1967
1968        assert_eq!(env("NODE_OPTIONS"), Some("--conditions=aube"));
1969        assert_eq!(env("npm_config_unsafe_perm"), Some("false"));
1970        assert_eq!(env("npm_config_shell_emulator"), Some("true"));
1971        assert_eq!(env("AUBE_NODE_GYP_PROJECT_DIR"), Some("/tmp/project"));
1972        assert_eq!(env("npm_lifecycle_event"), Some("postinstall"));
1973        assert_eq!(env("npm_package_name"), Some("pkg"));
1974        assert_eq!(env("npm_package_version"), Some("1.2.3"));
1975    }
1976
1977    #[test]
1978    fn embedder_env_overrides_jailed_node_gyp_project_default() {
1979        let mut cmd = tokio::process::Command::new("node");
1980        let settings = ScriptSettings {
1981            extra_env: vec![(
1982                "AUBE_NODE_GYP_PROJECT_DIR".into(),
1983                "/tmp/embedder-project".into(),
1984            )],
1985            ..Default::default()
1986        };
1987
1988        apply_jail_env(
1989            &mut cmd,
1990            std::ffi::OsStr::new("/bin"),
1991            Path::new("/tmp/aube-jail/home"),
1992            Path::new("/tmp/project"),
1993            &PackageJson::default(),
1994            "postinstall",
1995            &[],
1996        );
1997        apply_script_settings_env(&mut cmd, &settings);
1998
1999        let project_dir = cmd
2000            .as_std()
2001            .get_envs()
2002            .find(|(key, _)| *key == std::ffi::OsStr::new("AUBE_NODE_GYP_PROJECT_DIR"))
2003            .and_then(|(_, value)| value)
2004            .and_then(|value| value.to_str());
2005        assert_eq!(project_dir, Some("/tmp/embedder-project"));
2006    }
2007
2008    fn proxy_env(settings: ScriptSettings) -> impl Fn(&str) -> Option<String> {
2009        let mut cmd = tokio::process::Command::new("node");
2010        apply_script_settings_env(&mut cmd, &settings);
2011        let envs: Vec<_> = cmd
2012            .as_std()
2013            .get_envs()
2014            .map(|(k, v)| {
2015                (
2016                    k.to_string_lossy().into_owned(),
2017                    v.map(|v| v.to_string_lossy().into_owned()),
2018                )
2019            })
2020            .collect();
2021        move |name: &str| {
2022            envs.iter()
2023                .find(|(k, _)| k == name)
2024                .and_then(|(_, v)| v.clone())
2025        }
2026    }
2027
2028    #[test]
2029    fn proxy_vars_stamped_when_proxy_configured() {
2030        let env = proxy_env(ScriptSettings {
2031            https_proxy: Some("http://proxy.example:8080".to_string()),
2032            http_proxy: Some("http://proxy.example:8080".to_string()),
2033            no_proxy: Some("localhost,127.0.0.1".to_string()),
2034            ..Default::default()
2035        });
2036        assert_eq!(
2037            env("HTTPS_PROXY").as_deref(),
2038            Some("http://proxy.example:8080")
2039        );
2040        assert_eq!(
2041            env("HTTP_PROXY").as_deref(),
2042            Some("http://proxy.example:8080")
2043        );
2044        assert_eq!(env("NO_PROXY").as_deref(), Some("localhost,127.0.0.1"));
2045        // Node ignores the proxy vars unless this flag is set (Node 24+);
2046        // it must be the plain env var, not `--use-env-proxy`.
2047        assert_eq!(env("NODE_USE_ENV_PROXY").as_deref(), Some("1"));
2048    }
2049
2050    /// Standalone: the running binary *is* the package manager, so a
2051    /// script's `${npm_execpath} run …` reaches aube's own CLI.
2052    #[test]
2053    fn npm_execpath_defaults_to_the_running_binary() {
2054        let env = proxy_env(ScriptSettings::default());
2055        assert!(!aube_util::is_embedded());
2056        assert_eq!(
2057            env("npm_execpath").map(PathBuf::from),
2058            std::env::current_exe().ok()
2059        );
2060    }
2061
2062    /// Embedded, the caller hands over a shim that re-enters aube through
2063    /// the host — the host's own binary would parse `run verify-build` as
2064    /// one of *its* commands. Set inside an install scope, which is also
2065    /// what keeps it out of the sibling tests above.
2066    #[tokio::test]
2067    async fn pm_execpath_overrides_the_running_binary() {
2068        scope(async {
2069            set_pm_execpath(Some(PathBuf::from("/cache/aube/tools/pm-exec/aube")));
2070            let env = proxy_env(ScriptSettings::default());
2071            assert_eq!(
2072                env("npm_execpath").as_deref(),
2073                Some("/cache/aube/tools/pm-exec/aube")
2074            );
2075        })
2076        .await;
2077    }
2078
2079    /// The decision table `apply_script_settings_env` stamps from. The
2080    /// embedded-with-no-override row is the one that cannot be reached from
2081    /// a test process (registering a host profile is once-per-process), and
2082    /// it is the row that matters: nothing to name means nothing stamped.
2083    #[test]
2084    fn pm_execpath_resolution_table() {
2085        let exe = Some(PathBuf::from("/usr/bin/aube"));
2086        let shim = Some(PathBuf::from("/cache/aube/tools/pm-exec/aube"));
2087        assert_eq!(pm_execpath_for(None, false, exe.clone()), exe);
2088        assert_eq!(pm_execpath_for(None, true, exe.clone()), None);
2089        assert_eq!(pm_execpath_for(shim.clone(), true, exe.clone()), shim);
2090        assert_eq!(pm_execpath_for(shim.clone(), false, exe), shim);
2091        assert_eq!(pm_execpath_for(None, false, None), None);
2092    }
2093
2094    /// The shim resolves the dispatching executable from the environment
2095    /// rather than baking it in, so every script has to carry it.
2096    #[test]
2097    fn cli_exe_is_stamped_for_the_shim() {
2098        let env = proxy_env(ScriptSettings::default());
2099        assert_eq!(
2100            env(CLI_EXE_ENV).map(PathBuf::from),
2101            std::env::current_exe().ok()
2102        );
2103    }
2104
2105    #[test]
2106    fn proxy_block_skipped_when_no_proxy_configured() {
2107        // With no proxy resolved, none of the passthrough vars — and
2108        // crucially not the experimental `NODE_USE_ENV_PROXY` flag —
2109        // should be stamped onto the script env.
2110        let env = proxy_env(ScriptSettings::default());
2111        assert_eq!(env("HTTPS_PROXY"), None);
2112        assert_eq!(env("HTTP_PROXY"), None);
2113        assert_eq!(env("NO_PROXY"), None);
2114        assert_eq!(env("NODE_USE_ENV_PROXY"), None);
2115    }
2116
2117    #[test]
2118    fn no_proxy_alone_does_not_trigger_passthrough() {
2119        // `NO_PROXY` without an actual proxy URL is meaningless, and we
2120        // must not flip Node's env-proxy flag for a direct connection.
2121        let env = proxy_env(ScriptSettings {
2122            no_proxy: Some("example.com".to_string()),
2123            ..Default::default()
2124        });
2125        assert_eq!(env("NO_PROXY"), None);
2126        assert_eq!(env("NODE_USE_ENV_PROXY"), None);
2127    }
2128
2129    #[test]
2130    fn wrapper_node_and_execpath_are_stamped_distinctly() {
2131        // A wrapping embedder: `NODE` is the shim (so `$NODE` stays
2132        // wrapped) while `npm_node_execpath` is the real binary node-gyp
2133        // reads. Embedder `extra_env` lands last.
2134        let env = proxy_env(ScriptSettings {
2135            node_program: Some(PathBuf::from("/shim/node")),
2136            node_execpath: Some(PathBuf::from("/real/node-24.4.1/bin/node")),
2137            extra_env: vec![("MYTOOL_WRAPPED".into(), "1".into())],
2138            ..Default::default()
2139        });
2140        assert_eq!(env("NODE").as_deref(), Some("/shim/node"));
2141        assert_eq!(
2142            env("npm_node_execpath").as_deref(),
2143            Some("/real/node-24.4.1/bin/node")
2144        );
2145        assert_eq!(env("MYTOOL_WRAPPED").as_deref(), Some("1"));
2146    }
2147
2148    #[test]
2149    fn node_execpath_falls_back_to_node_program() {
2150        // A selector supplies only `node_program`; both vars point at it.
2151        let env = proxy_env(ScriptSettings {
2152            node_program: Some(PathBuf::from("/opt/node/bin/node")),
2153            ..Default::default()
2154        });
2155        assert_eq!(env("NODE").as_deref(), Some("/opt/node/bin/node"));
2156        assert_eq!(
2157            env("npm_node_execpath").as_deref(),
2158            Some("/opt/node/bin/node")
2159        );
2160    }
2161}
2162
2163#[cfg(all(test, windows))]
2164mod windows_quote_tests {
2165    use super::shell_quote_arg;
2166
2167    #[test]
2168    fn windows_path_backslash_not_doubled() {
2169        let q = shell_quote_arg(r"C:\Users\me\file.txt");
2170        assert_eq!(q, "\"C:\\Users\\me\\file.txt\"");
2171    }
2172
2173    #[test]
2174    fn windows_trailing_backslash_doubled_before_close_quote() {
2175        let q = shell_quote_arg(r"C:\path\");
2176        assert_eq!(q, "\"C:\\path\\\\\"");
2177    }
2178
2179    #[test]
2180    fn windows_quote_in_arg_escapes_with_backslash() {
2181        assert_eq!(shell_quote_arg(r#"a"b"#), "\"a\\\"b\"");
2182        assert_eq!(shell_quote_arg(r#"a\"b"#), "\"a\\\\\\\"b\"");
2183        assert_eq!(shell_quote_arg(r#"a\\"b"#), "\"a\\\\\\\\\\\"b\"");
2184    }
2185}
2186
2187// Regression test for Discussion #654: aborting the lifecycle JoinSet
2188// after a failed `aube add --global` left node-gyp / MSBuild / node
2189// running orphaned on Windows because `TerminateProcess` on the cmd.exe
2190// shell does not propagate to its descendants. The Job Object the
2191// spawn helper now attaches the shell to must reap the entire process
2192// tree when the parent future is dropped.
2193#[cfg(all(test, windows))]
2194mod windows_job_object_tests {
2195    use super::*;
2196    use std::time::{Duration, Instant};
2197    use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
2198    use windows_sys::Win32::System::Threading::{
2199        GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
2200    };
2201
2202    fn is_process_alive(pid: u32) -> bool {
2203        // SAFETY: documented entry points; we close any handle we
2204        // successfully obtain. `OpenProcess` returns NULL once the
2205        // pid has been reaped or never existed.
2206        unsafe {
2207            let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
2208            if handle.is_null() {
2209                return false;
2210            }
2211            let mut code: u32 = 0;
2212            let ok = GetExitCodeProcess(handle, &mut code);
2213            CloseHandle(handle);
2214            ok != 0 && code == STILL_ACTIVE as u32
2215        }
2216    }
2217
2218    async fn wait_until<F: Fn() -> bool>(check: F, timeout: Duration) -> bool {
2219        let start = Instant::now();
2220        while !check() {
2221            if start.elapsed() > timeout {
2222                return false;
2223            }
2224            tokio::time::sleep(Duration::from_millis(75)).await;
2225        }
2226        true
2227    }
2228
2229    #[tokio::test]
2230    async fn aborting_script_kills_grandchildren() {
2231        // Unique pid-file path per test run so concurrent test
2232        // executions don't stomp each other. `tempfile` is not a
2233        // dep of this crate; std::env::temp_dir + nanos is enough.
2234        let nanos = std::time::SystemTime::now()
2235            .duration_since(std::time::UNIX_EPOCH)
2236            .unwrap_or_default()
2237            .as_nanos();
2238        let pid_file = std::env::temp_dir().join(format!("aube-test-grandchild-{nanos}.pid"));
2239        // Background a hidden powershell that writes its own PID
2240        // and then sleeps long enough that the test will fail if it
2241        // isn't reaped. `start /b` detaches the powershell from the
2242        // cmd.exe shell — exactly the orphaned-grandchild shape that
2243        // node-gyp / MSBuild produce in Discussion #654. The trailing
2244        // `ping` keeps the shell itself alive for ~8s so the test
2245        // can race a liveness check against the running grandchild
2246        // before aborting the parent future.
2247        let script = format!(
2248            "start /b powershell -NoProfile -WindowStyle Hidden -Command \
2249             \"$pid | Out-File -Encoding ascii -FilePath '{}'; Start-Sleep 60\" \
2250             & ping -n 10 127.0.0.1 >nul",
2251            pid_file.display()
2252        );
2253        let cmd = spawn_shell_with_settings(&script, &ScriptSettings::default());
2254        let task = tokio::spawn(async move {
2255            let _ = run_command_killing_descendants(cmd, "test-grandchild").await;
2256        });
2257
2258        let appeared = wait_until(
2259            || {
2260                std::fs::read_to_string(&pid_file)
2261                    .ok()
2262                    .and_then(|pid| pid.trim().parse::<u32>().ok())
2263                    .is_some()
2264            },
2265            Duration::from_secs(20),
2266        )
2267        .await;
2268        assert!(appeared, "grandchild never wrote pid file at {pid_file:?}");
2269        let pid: u32 = std::fs::read_to_string(&pid_file)
2270            .expect("read pid file")
2271            .trim()
2272            .parse()
2273            .expect("pid file was parseable before reading");
2274        assert!(
2275            is_process_alive(pid),
2276            "grandchild pid {pid} not alive immediately after writing pid file"
2277        );
2278
2279        // Drop the future mid-`child.wait().await`. The `_job` local
2280        // in `run_command_killing_descendants` drops with it, which
2281        // closes the last handle and fires `KILL_ON_JOB_CLOSE` —
2282        // killing both the shell *and* the detached powershell.
2283        task.abort();
2284        let _ = task.await;
2285
2286        let reaped = wait_until(|| !is_process_alive(pid), Duration::from_secs(10)).await;
2287        let _ = std::fs::remove_file(&pid_file);
2288        assert!(
2289            reaped,
2290            "grandchild pid {pid} survived parent abort — job object did not kill the tree"
2291        );
2292    }
2293}