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 `pnpm-workspace.yaml`, or the escape-hatch
12//!   `--dangerously-allow-all-builds` flag.
13//! - `--ignore-scripts` forces everything off, matching pnpm/npm.
14
15pub mod policy;
16
17pub use policy::{AllowDecision, BuildPolicy, BuildPolicyError};
18
19use aube_manifest::PackageJson;
20use std::path::{Path, PathBuf};
21
22/// Settings that affect every package-script shell aube spawns.
23#[derive(Debug, Clone, Default)]
24pub struct ScriptSettings {
25    pub node_options: Option<String>,
26    pub script_shell: Option<PathBuf>,
27    pub unsafe_perm: Option<bool>,
28    pub shell_emulator: bool,
29}
30
31static SCRIPT_SETTINGS: std::sync::OnceLock<std::sync::RwLock<ScriptSettings>> =
32    std::sync::OnceLock::new();
33
34fn script_settings_lock() -> &'static std::sync::RwLock<ScriptSettings> {
35    SCRIPT_SETTINGS.get_or_init(|| std::sync::RwLock::new(ScriptSettings::default()))
36}
37
38/// Replace the process-wide script settings snapshot. CLI commands call
39/// this after resolving `.npmrc` / workspace settings for the active
40/// project.
41pub fn set_script_settings(settings: ScriptSettings) {
42    *script_settings_lock()
43        .write()
44        .expect("script settings lock poisoned") = settings;
45}
46
47fn script_settings() -> ScriptSettings {
48    script_settings_lock()
49        .read()
50        .expect("script settings lock poisoned")
51        .clone()
52}
53
54/// Prepend `bin_dir` to the current `PATH` using the platform's path
55/// separator (`:` on Unix, `;` on Windows).
56pub fn prepend_path(bin_dir: &Path) -> std::ffi::OsString {
57    let path = std::env::var_os("PATH").unwrap_or_default();
58    let mut entries = vec![bin_dir.to_path_buf()];
59    entries.extend(std::env::split_paths(&path));
60    std::env::join_paths(entries).unwrap_or(path)
61}
62
63/// Spawn a shell command line. On Unix we go through `sh -c`, on
64/// Windows through `cmd.exe /d /s /c` — matching what npm passes in
65/// `@npmcli/run-script`.
66///
67/// On Windows, the script command line is appended with
68/// [`std::os::windows::process::CommandExt::raw_arg`] instead of
69/// the normal `.arg()` path. `.arg()` would run the string through
70/// Rust's `CommandLineToArgvW`-oriented encoder, which wraps it in
71/// `"..."` and escapes interior `"` as `\"` — but `cmd.exe` parses
72/// command lines with a different set of rules and does not
73/// understand `\"`, so a script like
74/// `node -e "require('is-odd')(3)"` arrives mangled. `raw_arg`
75/// hands the command line to `CreateProcessW` verbatim, so we
76/// control the exact bytes cmd.exe sees. We wrap the whole script
77/// in an outer pair of double quotes, which `/s` tells cmd.exe to
78/// strip (just those outer quotes — the rest of the string is
79/// preserved literally). This is the same trick
80/// `@npmcli/run-script` and `node-cross-spawn` use.
81pub fn spawn_shell(script_cmd: &str) -> tokio::process::Command {
82    let settings = script_settings();
83    #[cfg(unix)]
84    {
85        let mut cmd = tokio::process::Command::new(
86            settings
87                .script_shell
88                .as_deref()
89                .unwrap_or_else(|| Path::new("sh")),
90        );
91        cmd.arg("-c").arg(script_cmd);
92        apply_script_settings_env(&mut cmd, &settings);
93        cmd
94    }
95    #[cfg(windows)]
96    {
97        let mut cmd = tokio::process::Command::new(
98            settings
99                .script_shell
100                .as_deref()
101                .unwrap_or_else(|| Path::new("cmd.exe")),
102        );
103        if settings.script_shell.is_some() {
104            cmd.arg("-c").arg(script_cmd);
105        } else {
106            // `/d` skips AutoRun, `/s` flips the quote-stripping rule
107            // so only the *outer* `"..."` pair is removed, `/c` runs
108            // the command and exits. Build the raw argv tail manually
109            // so cmd.exe sees the original script bytes.
110            cmd.raw_arg("/d /s /c \"").raw_arg(script_cmd).raw_arg("\"");
111        }
112        apply_script_settings_env(&mut cmd, &settings);
113        cmd
114    }
115}
116
117fn apply_script_settings_env(cmd: &mut tokio::process::Command, settings: &ScriptSettings) {
118    if let Some(node_options) = settings.node_options.as_deref() {
119        cmd.env("NODE_OPTIONS", node_options);
120    }
121    if let Some(unsafe_perm) = settings.unsafe_perm {
122        cmd.env(
123            "npm_config_unsafe_perm",
124            if unsafe_perm { "true" } else { "false" },
125        );
126    }
127    if settings.shell_emulator {
128        cmd.env("npm_config_shell_emulator", "true");
129    }
130}
131
132/// Lifecycle hooks that `aube install` runs against the root package's
133/// `scripts` field, in this order: `preinstall` → (dependencies link) →
134/// `install` → `postinstall` → `prepare`. Matches pnpm / npm.
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum LifecycleHook {
137    PreInstall,
138    Install,
139    PostInstall,
140    Prepare,
141}
142
143impl LifecycleHook {
144    pub fn script_name(self) -> &'static str {
145        match self {
146            Self::PreInstall => "preinstall",
147            Self::Install => "install",
148            Self::PostInstall => "postinstall",
149            Self::Prepare => "prepare",
150        }
151    }
152}
153
154/// Dependency lifecycle hooks, in the order aube runs them for each
155/// allowlisted package. `prepare` is intentionally omitted — it's meant
156/// for the root package and git-dep preparation, not installed tarballs.
157pub const DEP_LIFECYCLE_HOOKS: [LifecycleHook; 3] = [
158    LifecycleHook::PreInstall,
159    LifecycleHook::Install,
160    LifecycleHook::PostInstall,
161];
162
163/// Holds the real stderr fd saved before `aube` redirects fd 2 to
164/// `/dev/null` under `--silent`. Child processes spawned through
165/// `child_stderr()` get a fresh dup of this fd so their stderr still
166/// reaches the user's terminal — `--silent` only silences aube's own
167/// output, not the scripts / binaries it invokes (matches `pnpm
168/// --loglevel silent`). A value of `-1` means silent mode is off and
169/// children should inherit stderr normally.
170#[cfg(unix)]
171static SAVED_STDERR_FD: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1);
172
173/// Called once by `aube` after it saves + redirects fd 2. Passing
174/// the caller-owned saved fd here means child processes spawned via
175/// `child_stderr()` will write to the real terminal stderr instead of
176/// `/dev/null`.
177#[cfg(unix)]
178pub fn set_saved_stderr_fd(fd: std::os::fd::RawFd) {
179    SAVED_STDERR_FD.store(fd, std::sync::atomic::Ordering::SeqCst);
180}
181
182/// Windows has no equivalent fd-based silencing plumbing: aube's
183/// `SilentStderrGuard` is `libc::dup`/`libc::dup2` on fd 2, and those
184/// calls are gated to unix in `aube`. The stub keeps the public
185/// API shape identical so call sites compile unchanged.
186#[cfg(not(unix))]
187pub fn set_saved_stderr_fd(_fd: i32) {}
188
189/// Returns a `Stdio` suitable for a child process's stderr. When silent
190/// mode is active, this dups the saved real-stderr fd so the child
191/// bypasses the `/dev/null` redirect on fd 2. Otherwise returns
192/// `Stdio::inherit()`.
193#[cfg(unix)]
194pub fn child_stderr() -> std::process::Stdio {
195    let fd = SAVED_STDERR_FD.load(std::sync::atomic::Ordering::SeqCst);
196    if fd < 0 {
197        return std::process::Stdio::inherit();
198    }
199    // SAFETY: `fd` was registered by `set_saved_stderr_fd` from a live
200    // `dup` that `aube`'s `SilentStderrGuard` keeps open for the
201    // duration of main. `BorrowedFd` only borrows, so this does not
202    // transfer ownership.
203    let borrowed = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) };
204    match borrowed.try_clone_to_owned() {
205        Ok(owned) => std::process::Stdio::from(owned),
206        Err(_) => std::process::Stdio::inherit(),
207    }
208}
209
210#[cfg(not(unix))]
211pub fn child_stderr() -> std::process::Stdio {
212    std::process::Stdio::inherit()
213}
214
215/// Run a single npm-style script line through `sh -c` with the usual
216/// environment (`$PATH` extended with `node_modules/.bin`, `INIT_CWD`,
217/// `npm_lifecycle_event`, `npm_package_name`, `npm_package_version`).
218///
219/// `extra_bin_dir` is an optional directory prepended to `PATH` *before*
220/// the project-level `.bin`. Dep lifecycle scripts pass the dep's own
221/// sibling `node_modules/.bin/` so transitive binaries (e.g.
222/// `prebuild-install`, `node-gyp`) declared in the dep's
223/// `dependencies` are reachable. Root scripts pass `None` — their
224/// transitive bins are already hoisted into the project-level `.bin`.
225///
226/// Inherits stdio from the parent so the user sees script output live.
227/// Returns Err on non-zero exit so install fails fast if a lifecycle
228/// script breaks, matching pnpm.
229pub async fn run_script(
230    script_dir: &Path,
231    project_root: &Path,
232    modules_dir_name: &str,
233    manifest: &PackageJson,
234    script_name: &str,
235    script_cmd: &str,
236    extra_bin_dir: Option<&Path>,
237) -> Result<(), Error> {
238    // PATH prepends (most-local-first): optional `extra_bin_dir` for
239    // dep-local transitive bins, then the project root's
240    // `<modules_dir>/.bin`. For root scripts `script_dir ==
241    // project_root` and `extra_bin_dir` is `None`, which matches the
242    // old behavior. `modules_dir_name` honors pnpm's `modulesDir`
243    // setting — defaults to `"node_modules"` at the call site, but a
244    // workspace may have configured something else.
245    let project_bin = project_root.join(modules_dir_name).join(".bin");
246    let path = std::env::var_os("PATH").unwrap_or_default();
247    let mut entries: Vec<PathBuf> = Vec::new();
248    if let Some(dir) = extra_bin_dir {
249        entries.push(dir.to_path_buf());
250    }
251    entries.push(project_bin);
252    entries.extend(std::env::split_paths(&path));
253    let new_path = std::env::join_paths(entries).unwrap_or(path);
254
255    let mut cmd = spawn_shell(script_cmd);
256    cmd.current_dir(script_dir)
257        .stderr(child_stderr())
258        .env("PATH", &new_path)
259        .env("npm_lifecycle_event", script_name);
260
261    // Pass INIT_CWD the way npm/pnpm do — the directory the user
262    // invoked the package manager from, *not* the script's own cwd.
263    // Native-module build tooling (node-gyp, prebuild-install, etc.)
264    // reads INIT_CWD to locate the project root when caching binaries.
265    // Preserve if already set by a parent aube invocation so nested
266    // scripts see the outermost cwd.
267    if std::env::var_os("INIT_CWD").is_none() {
268        cmd.env("INIT_CWD", project_root);
269    }
270
271    if let Some(ref name) = manifest.name {
272        cmd.env("npm_package_name", name);
273    }
274    if let Some(ref version) = manifest.version {
275        cmd.env("npm_package_version", version);
276    }
277
278    tracing::debug!("lifecycle: {script_name} → {script_cmd}");
279    let status = cmd
280        .status()
281        .await
282        .map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()))?;
283
284    if !status.success() {
285        return Err(Error::NonZeroExit {
286            script: script_name.to_string(),
287            code: status.code(),
288        });
289    }
290
291    Ok(())
292}
293
294/// Run a lifecycle hook against the root package, if a script for it is
295/// defined. Returns `Ok(false)` if the hook wasn't defined (no-op),
296/// `Ok(true)` if it ran successfully.
297///
298/// The caller is responsible for gating on `--ignore-scripts`.
299pub async fn run_root_hook(
300    project_dir: &Path,
301    modules_dir_name: &str,
302    manifest: &PackageJson,
303    hook: LifecycleHook,
304) -> Result<bool, Error> {
305    let name = hook.script_name();
306    let Some(script_cmd) = manifest.scripts.get(name) else {
307        return Ok(false);
308    };
309    run_script(
310        project_dir,
311        project_dir,
312        modules_dir_name,
313        manifest,
314        name,
315        script_cmd,
316        None,
317    )
318    .await?;
319    Ok(true)
320}
321
322/// Single source of truth for the implicit `node-gyp rebuild`
323/// fallback: returns `Some("node-gyp rebuild")` when the package ships
324/// a `binding.gyp` at its root AND the manifest leaves both `install`
325/// and `preinstall` empty (either one is the author's explicit
326/// opt-out from the default).
327///
328/// `has_binding_gyp` is passed by the caller so this helper is
329/// agnostic to *how* presence was detected — the install pipeline
330/// stats the materialized package dir, while `aube ignored-builds`
331/// reads the store `PackageIndex` since the package may not be
332/// linked into `node_modules` yet. Both paths must agree on the gate
333/// condition, so they both go through this.
334pub fn implicit_install_script(
335    manifest: &PackageJson,
336    has_binding_gyp: bool,
337) -> Option<&'static str> {
338    if !has_binding_gyp {
339        return None;
340    }
341    if manifest
342        .scripts
343        .contains_key(LifecycleHook::Install.script_name())
344        || manifest
345            .scripts
346            .contains_key(LifecycleHook::PreInstall.script_name())
347    {
348        return None;
349    }
350    Some("node-gyp rebuild")
351}
352
353/// Default `install` command for a materialized dependency directory.
354/// Thin wrapper around [`implicit_install_script`] that supplies
355/// `has_binding_gyp` by stat'ing `<package_dir>/binding.gyp`.
356pub fn default_install_script(package_dir: &Path, manifest: &PackageJson) -> Option<&'static str> {
357    implicit_install_script(manifest, package_dir.join("binding.gyp").is_file())
358}
359
360/// True if [`run_dep_hook`] would actually execute something for this
361/// package across any of the dependency lifecycle hooks. Callers use
362/// this to skip fan-out work for packages that have nothing to run —
363/// including the implicit `node-gyp rebuild` default.
364pub fn has_dep_lifecycle_work(package_dir: &Path, manifest: &PackageJson) -> bool {
365    if DEP_LIFECYCLE_HOOKS
366        .iter()
367        .any(|h| manifest.scripts.contains_key(h.script_name()))
368    {
369        return true;
370    }
371    default_install_script(package_dir, manifest).is_some()
372}
373
374/// Run a lifecycle hook against an installed dependency's package
375/// directory. Mirrors [`run_root_hook`] but spawns inside `package_dir`
376/// (the actual linked package directory, e.g.
377/// `node_modules/.aube/<dep_path>/node_modules/<name>`). The manifest
378/// is the dependency's own `package.json`, *not* the project root's.
379///
380/// `dep_modules_dir` is the dep's sibling `node_modules/` — i.e.
381/// `package_dir`'s parent for unscoped packages, or `package_dir`'s
382/// grandparent for scoped (`@scope/name`). `<dep_modules_dir>/.bin`
383/// is prepended to `PATH` so the dep's postinstall can spawn tools
384/// declared in its own `dependencies` (the transitive-bin case —
385/// `prebuild-install`, `node-gyp`, `napi-postinstall`). The install
386/// driver writes shims there via `link_dep_bins`; `rebuild` mirrors
387/// the same pass.
388///
389/// For the `install` hook specifically, if the manifest leaves both
390/// `install` and `preinstall` empty but the package has a top-level
391/// `binding.gyp`, this falls back to running `node-gyp rebuild` — the
392/// node-gyp default that npm and pnpm both honor so native modules
393/// without a prebuilt binary still compile on install.
394///
395/// The caller is responsible for gating on `BuildPolicy` and
396/// `--ignore-scripts`. Returns `Ok(false)` if the hook wasn't defined.
397pub async fn run_dep_hook(
398    package_dir: &Path,
399    dep_modules_dir: &Path,
400    project_root: &Path,
401    modules_dir_name: &str,
402    manifest: &PackageJson,
403    hook: LifecycleHook,
404) -> Result<bool, Error> {
405    let name = hook.script_name();
406    let script_cmd: &str = match manifest.scripts.get(name) {
407        Some(s) => s.as_str(),
408        None => match hook {
409            LifecycleHook::Install => match default_install_script(package_dir, manifest) {
410                Some(s) => s,
411                None => return Ok(false),
412            },
413            _ => return Ok(false),
414        },
415    };
416    let dep_bin_dir = dep_modules_dir.join(".bin");
417    run_script(
418        package_dir,
419        project_root,
420        modules_dir_name,
421        manifest,
422        name,
423        script_cmd,
424        Some(&dep_bin_dir),
425    )
426    .await?;
427    Ok(true)
428}
429
430#[derive(Debug, thiserror::Error)]
431pub enum Error {
432    #[error("failed to spawn script {0}: {1}")]
433    Spawn(String, String),
434    #[error("script `{script}` exited with code {code:?}")]
435    NonZeroExit { script: String, code: Option<i32> },
436}