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    match script_settings_lock().write() {
43        Ok(mut guard) => *guard = settings,
44        Err(poisoned) => *poisoned.into_inner() = settings,
45    }
46}
47
48fn script_settings() -> ScriptSettings {
49    match script_settings_lock().read() {
50        Ok(guard) => guard.clone(),
51        Err(poisoned) => poisoned.into_inner().clone(),
52    }
53}
54
55/// Prepend `bin_dir` to the current `PATH` using the platform's path
56/// separator (`:` on Unix, `;` on Windows).
57pub fn prepend_path(bin_dir: &Path) -> std::ffi::OsString {
58    let path = std::env::var_os("PATH").unwrap_or_default();
59    let mut entries = vec![bin_dir.to_path_buf()];
60    entries.extend(std::env::split_paths(&path));
61    std::env::join_paths(entries).unwrap_or(path)
62}
63
64/// Spawn a shell command line. On Unix we go through `sh -c`, on
65/// Windows through `cmd.exe /d /s /c` — matching what npm passes in
66/// `@npmcli/run-script`.
67///
68/// On Windows, the script command line is appended with
69/// [`std::os::windows::process::CommandExt::raw_arg`] instead of
70/// the normal `.arg()` path. `.arg()` would run the string through
71/// Rust's `CommandLineToArgvW`-oriented encoder, which wraps it in
72/// `"..."` and escapes interior `"` as `\"` — but `cmd.exe` parses
73/// command lines with a different set of rules and does not
74/// understand `\"`, so a script like
75/// `node -e "require('is-odd')(3)"` arrives mangled. `raw_arg`
76/// hands the command line to `CreateProcessW` verbatim, so we
77/// control the exact bytes cmd.exe sees. We wrap the whole script
78/// in an outer pair of double quotes, which `/s` tells cmd.exe to
79/// strip (just those outer quotes — the rest of the string is
80/// preserved literally). This is the same trick
81/// `@npmcli/run-script` and `node-cross-spawn` use.
82pub fn spawn_shell(script_cmd: &str) -> tokio::process::Command {
83    let settings = script_settings();
84    #[cfg(unix)]
85    {
86        let mut cmd = tokio::process::Command::new(
87            settings
88                .script_shell
89                .as_deref()
90                .unwrap_or_else(|| Path::new("sh")),
91        );
92        cmd.arg("-c").arg(script_cmd);
93        apply_script_settings_env(&mut cmd, &settings);
94        cmd
95    }
96    #[cfg(windows)]
97    {
98        let mut cmd = tokio::process::Command::new(
99            settings
100                .script_shell
101                .as_deref()
102                .unwrap_or_else(|| Path::new("cmd.exe")),
103        );
104        if settings.script_shell.is_some() {
105            cmd.arg("-c").arg(script_cmd);
106        } else {
107            // `/d` skips AutoRun, `/s` flips the quote-stripping rule
108            // so only the *outer* `"..."` pair is removed, `/c` runs
109            // the command and exits. Build the raw argv tail manually
110            // so cmd.exe sees the original script bytes.
111            cmd.raw_arg("/d /s /c \"").raw_arg(script_cmd).raw_arg("\"");
112        }
113        apply_script_settings_env(&mut cmd, &settings);
114        cmd
115    }
116}
117
118/// Shell-quote one arg for safe splicing into a shell command line.
119///
120/// Used by `aube run <script> -- args`. Args get joined into the
121/// script string, then sh -c or cmd /c reparses the whole thing. If
122/// user arg contains $, backticks, ;, |, &, (, ), etc, the shell
123/// interprets those as metacharacters. That is shell injection.
124/// `aube run echo 'hello; rm -rf ~'` would run two commands. Same
125/// issue npm had pre-2016. Quote each arg so shell treats it as one
126/// literal token.
127///
128/// Unix: wrap in single quotes. sh treats interior of '...' as pure
129/// literal with one exception, embedded single quote. Handle that
130/// with the standard '\'' escape trick: close the single-quoted
131/// string, emit an escaped quote, reopen. Works in every POSIX sh.
132///
133/// Windows cmd.exe: wrap in double quotes. cmd interprets many
134/// metachars even inside double quotes, but CreateProcessW hands the
135/// string to our spawn_shell that uses `/d /s /c "..."`, the outer
136/// quotes get stripped per /s rule and the content runs. Escape
137/// interior " and backslash per CommandLineToArgvW. Full cmd.exe
138/// metachar caret-escaping is a rabbit hole, so this is best-effort,
139/// works for the common cases, matches what node's shell-quote does.
140pub fn shell_quote_arg(arg: &str) -> String {
141    #[cfg(unix)]
142    {
143        let mut out = String::with_capacity(arg.len() + 2);
144        out.push('\'');
145        for ch in arg.chars() {
146            if ch == '\'' {
147                out.push_str("'\\''");
148            } else {
149                out.push(ch);
150            }
151        }
152        out.push('\'');
153        out
154    }
155    #[cfg(windows)]
156    {
157        let mut out = String::with_capacity(arg.len() + 2);
158        out.push('"');
159        for ch in arg.chars() {
160            match ch {
161                '"' => out.push_str("\\\""),
162                '\\' => out.push_str("\\\\"),
163                // cmd.exe expands %VAR% even inside double quotes.
164                // Outer `/s /c "..."` only strips the outermost
165                // quote pair, the shell still runs env expansion
166                // on the body. Argument like `%COMSPEC%` would
167                // otherwise get replaced with the shell path
168                // before the child saw it. Double the percent so
169                // cmd passes a literal `%` through. Full
170                // caret-escaping of `^ & | < > ( )` is a deeper
171                // rabbit hole, this handles the common injection
172                // vector.
173                '%' => out.push_str("%%"),
174                _ => out.push(ch),
175            }
176        }
177        out.push('"');
178        out
179    }
180}
181
182/// Translate child ExitStatus to a parent exit code.
183///
184/// On Unix a signal-killed child has None from .code(). Old code
185/// collapsed that to 1. That loses signal identity: SIGKILL (OOM
186/// killer, exit 137), SIGSEGV (139), Ctrl-C (130) all look like
187/// plain exit 1. CI pipelines watching for 137 to detect OOM cannot
188/// distinguish it from a normal script error anymore. Bash convention
189/// is 128 + signum, match that.
190///
191/// Windows has no signal concept so .code() is always Some, the
192/// fallback 1 is dead code there but keeps the function total.
193pub fn exit_code_from_status(status: std::process::ExitStatus) -> i32 {
194    if let Some(code) = status.code() {
195        return code;
196    }
197    #[cfg(unix)]
198    {
199        use std::os::unix::process::ExitStatusExt;
200        if let Some(sig) = status.signal() {
201            return 128 + sig;
202        }
203    }
204    1
205}
206
207fn apply_script_settings_env(cmd: &mut tokio::process::Command, settings: &ScriptSettings) {
208    // Strip credentials that aube itself owns before we spawn any
209    // lifecycle script. AUBE_AUTH_TOKEN is aube's own registry login
210    // token. No transitive postinstall has any business reading it.
211    // NPM_TOKEN and NODE_AUTH_TOKEN stay untouched because release
212    // flows ("npm publish" in a postpublish script) genuinely need
213    // them. Matches what pnpm does today.
214    cmd.env_remove("AUBE_AUTH_TOKEN");
215    if let Some(node_options) = settings.node_options.as_deref() {
216        cmd.env("NODE_OPTIONS", node_options);
217    }
218    if let Some(unsafe_perm) = settings.unsafe_perm {
219        cmd.env(
220            "npm_config_unsafe_perm",
221            if unsafe_perm { "true" } else { "false" },
222        );
223    }
224    if settings.shell_emulator {
225        cmd.env("npm_config_shell_emulator", "true");
226    }
227}
228
229/// Lifecycle hooks that `aube install` runs against the root package's
230/// `scripts` field, in this order: `preinstall` → (dependencies link) →
231/// `install` → `postinstall` → `prepare`. Matches pnpm / npm.
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub enum LifecycleHook {
234    PreInstall,
235    Install,
236    PostInstall,
237    Prepare,
238}
239
240impl LifecycleHook {
241    pub fn script_name(self) -> &'static str {
242        match self {
243            Self::PreInstall => "preinstall",
244            Self::Install => "install",
245            Self::PostInstall => "postinstall",
246            Self::Prepare => "prepare",
247        }
248    }
249}
250
251/// Dependency lifecycle hooks, in the order aube runs them for each
252/// allowlisted package. `prepare` is intentionally omitted — it's meant
253/// for the root package and git-dep preparation, not installed tarballs.
254pub const DEP_LIFECYCLE_HOOKS: [LifecycleHook; 3] = [
255    LifecycleHook::PreInstall,
256    LifecycleHook::Install,
257    LifecycleHook::PostInstall,
258];
259
260/// Holds the real stderr fd saved before `aube` redirects fd 2 to
261/// `/dev/null` under `--silent`. Child processes spawned through
262/// `child_stderr()` get a fresh dup of this fd so their stderr still
263/// reaches the user's terminal — `--silent` only silences aube's own
264/// output, not the scripts / binaries it invokes (matches `pnpm
265/// --loglevel silent`). A value of `-1` means silent mode is off and
266/// children should inherit stderr normally.
267#[cfg(unix)]
268static SAVED_STDERR_FD: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1);
269
270/// Called once by `aube` after it saves + redirects fd 2. Passing
271/// the caller-owned saved fd here means child processes spawned via
272/// `child_stderr()` will write to the real terminal stderr instead of
273/// `/dev/null`.
274#[cfg(unix)]
275pub fn set_saved_stderr_fd(fd: std::os::fd::RawFd) {
276    SAVED_STDERR_FD.store(fd, std::sync::atomic::Ordering::SeqCst);
277}
278
279/// Windows has no equivalent fd-based silencing plumbing: aube's
280/// `SilentStderrGuard` is `libc::dup`/`libc::dup2` on fd 2, and those
281/// calls are gated to unix in `aube`. The stub keeps the public
282/// API shape identical so call sites compile unchanged.
283#[cfg(not(unix))]
284pub fn set_saved_stderr_fd(_fd: i32) {}
285
286/// Returns a `Stdio` suitable for a child process's stderr. When silent
287/// mode is active, this dups the saved real-stderr fd so the child
288/// bypasses the `/dev/null` redirect on fd 2. Otherwise returns
289/// `Stdio::inherit()`.
290#[cfg(unix)]
291pub fn child_stderr() -> std::process::Stdio {
292    let fd = SAVED_STDERR_FD.load(std::sync::atomic::Ordering::SeqCst);
293    if fd < 0 {
294        return std::process::Stdio::inherit();
295    }
296    // SAFETY: `fd` was registered by `set_saved_stderr_fd` from a live
297    // `dup` that `aube`'s `SilentStderrGuard` keeps open for the
298    // duration of main. `BorrowedFd` only borrows, so this does not
299    // transfer ownership.
300    let borrowed = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) };
301    match borrowed.try_clone_to_owned() {
302        Ok(owned) => std::process::Stdio::from(owned),
303        Err(_) => std::process::Stdio::inherit(),
304    }
305}
306
307#[cfg(not(unix))]
308pub fn child_stderr() -> std::process::Stdio {
309    std::process::Stdio::inherit()
310}
311
312/// Run a single npm-style script line through `sh -c` with the usual
313/// environment (`$PATH` extended with `node_modules/.bin`, `INIT_CWD`,
314/// `npm_lifecycle_event`, `npm_package_name`, `npm_package_version`).
315///
316/// `extra_bin_dirs` are prepended to `PATH` in order, *before* the
317/// project-level `.bin`. Dep lifecycle scripts pass the dep's own
318/// sibling `node_modules/.bin/` so transitive binaries (e.g.
319/// `prebuild-install`, `node-gyp`) declared in the dep's
320/// `dependencies` are reachable, optionally followed by aube-owned
321/// tool dirs (e.g. the bootstrapped node-gyp). Root scripts pass
322/// `&[]` — their transitive bins are already hoisted into the
323/// project-level `.bin`.
324///
325/// Inherits stdio from the parent so the user sees script output live.
326/// Returns Err on non-zero exit so install fails fast if a lifecycle
327/// script breaks, matching pnpm.
328pub async fn run_script(
329    script_dir: &Path,
330    project_root: &Path,
331    modules_dir_name: &str,
332    manifest: &PackageJson,
333    script_name: &str,
334    script_cmd: &str,
335    extra_bin_dirs: &[&Path],
336) -> Result<(), Error> {
337    // PATH prepends (most-local-first): `extra_bin_dirs` in caller
338    // order, then the project root's `<modules_dir>/.bin`. For root
339    // scripts `script_dir == project_root` and `extra_bin_dirs` is
340    // empty, which matches the old behavior. `modules_dir_name`
341    // honors pnpm's `modulesDir` setting — defaults to
342    // `"node_modules"` at the call site, but a workspace may have
343    // configured something else.
344    let project_bin = project_root.join(modules_dir_name).join(".bin");
345    let path = std::env::var_os("PATH").unwrap_or_default();
346    let mut entries: Vec<PathBuf> = Vec::with_capacity(extra_bin_dirs.len() + 1);
347    for dir in extra_bin_dirs {
348        entries.push(dir.to_path_buf());
349    }
350    entries.push(project_bin);
351    entries.extend(std::env::split_paths(&path));
352    let new_path = std::env::join_paths(entries).unwrap_or(path);
353
354    let mut cmd = spawn_shell(script_cmd);
355    cmd.current_dir(script_dir)
356        .stderr(child_stderr())
357        .env("PATH", &new_path)
358        .env("npm_lifecycle_event", script_name);
359
360    // Pass INIT_CWD the way npm/pnpm do — the directory the user
361    // invoked the package manager from, *not* the script's own cwd.
362    // Native-module build tooling (node-gyp, prebuild-install, etc.)
363    // reads INIT_CWD to locate the project root when caching binaries.
364    // Preserve if already set by a parent aube invocation so nested
365    // scripts see the outermost cwd.
366    if std::env::var_os("INIT_CWD").is_none() {
367        cmd.env("INIT_CWD", project_root);
368    }
369
370    if let Some(ref name) = manifest.name {
371        cmd.env("npm_package_name", name);
372    }
373    if let Some(ref version) = manifest.version {
374        cmd.env("npm_package_version", version);
375    }
376
377    tracing::debug!("lifecycle: {script_name} → {script_cmd}");
378    let status = cmd
379        .status()
380        .await
381        .map_err(|e| Error::Spawn(script_name.to_string(), e.to_string()))?;
382
383    if !status.success() {
384        return Err(Error::NonZeroExit {
385            script: script_name.to_string(),
386            code: status.code(),
387        });
388    }
389
390    Ok(())
391}
392
393/// Run a lifecycle hook against the root package, if a script for it is
394/// defined. Returns `Ok(false)` if the hook wasn't defined (no-op),
395/// `Ok(true)` if it ran successfully.
396///
397/// The caller is responsible for gating on `--ignore-scripts`.
398pub async fn run_root_hook(
399    project_dir: &Path,
400    modules_dir_name: &str,
401    manifest: &PackageJson,
402    hook: LifecycleHook,
403) -> Result<bool, Error> {
404    run_root_script_by_name(project_dir, modules_dir_name, manifest, hook.script_name()).await
405}
406
407/// Run a named root-package script if it's defined. Used by commands
408/// (pack, publish, version) that need to run lifecycle hooks outside
409/// the install-focused [`LifecycleHook`] enum. Returns `Ok(false)` if
410/// the script isn't defined.
411///
412/// The caller is responsible for gating on `--ignore-scripts`.
413pub async fn run_root_script_by_name(
414    project_dir: &Path,
415    modules_dir_name: &str,
416    manifest: &PackageJson,
417    name: &str,
418) -> Result<bool, Error> {
419    let Some(script_cmd) = manifest.scripts.get(name) else {
420        return Ok(false);
421    };
422    run_script(
423        project_dir,
424        project_dir,
425        modules_dir_name,
426        manifest,
427        name,
428        script_cmd,
429        &[],
430    )
431    .await?;
432    Ok(true)
433}
434
435/// Single source of truth for the implicit `node-gyp rebuild`
436/// fallback: returns `Some("node-gyp rebuild")` when the package ships
437/// a `binding.gyp` at its root AND the manifest leaves both `install`
438/// and `preinstall` empty (either one is the author's explicit
439/// opt-out from the default).
440///
441/// `has_binding_gyp` is passed by the caller so this helper is
442/// agnostic to *how* presence was detected — the install pipeline
443/// stats the materialized package dir, while `aube ignored-builds`
444/// reads the store `PackageIndex` since the package may not be
445/// linked into `node_modules` yet. Both paths must agree on the gate
446/// condition, so they both go through this.
447pub fn implicit_install_script(
448    manifest: &PackageJson,
449    has_binding_gyp: bool,
450) -> Option<&'static str> {
451    if !has_binding_gyp {
452        return None;
453    }
454    if manifest
455        .scripts
456        .contains_key(LifecycleHook::Install.script_name())
457        || manifest
458            .scripts
459            .contains_key(LifecycleHook::PreInstall.script_name())
460    {
461        return None;
462    }
463    Some("node-gyp rebuild")
464}
465
466/// Default `install` command for a materialized dependency directory.
467/// Thin wrapper around [`implicit_install_script`] that supplies
468/// `has_binding_gyp` by stat'ing `<package_dir>/binding.gyp`.
469pub fn default_install_script(package_dir: &Path, manifest: &PackageJson) -> Option<&'static str> {
470    implicit_install_script(manifest, package_dir.join("binding.gyp").is_file())
471}
472
473/// True if [`run_dep_hook`] would actually execute something for this
474/// package across any of the dependency lifecycle hooks. Callers use
475/// this to skip fan-out work for packages that have nothing to run —
476/// including the implicit `node-gyp rebuild` default.
477pub fn has_dep_lifecycle_work(package_dir: &Path, manifest: &PackageJson) -> bool {
478    if DEP_LIFECYCLE_HOOKS
479        .iter()
480        .any(|h| manifest.scripts.contains_key(h.script_name()))
481    {
482        return true;
483    }
484    default_install_script(package_dir, manifest).is_some()
485}
486
487/// Run a lifecycle hook against an installed dependency's package
488/// directory. Mirrors [`run_root_hook`] but spawns inside `package_dir`
489/// (the actual linked package directory, e.g.
490/// `node_modules/.aube/<dep_path>/node_modules/<name>`). The manifest
491/// is the dependency's own `package.json`, *not* the project root's.
492///
493/// `dep_modules_dir` is the dep's sibling `node_modules/` — i.e.
494/// `package_dir`'s parent for unscoped packages, or `package_dir`'s
495/// grandparent for scoped (`@scope/name`). `<dep_modules_dir>/.bin`
496/// is prepended to `PATH` so the dep's postinstall can spawn tools
497/// declared in its own `dependencies` (the transitive-bin case —
498/// `prebuild-install`, `node-gyp`, `napi-postinstall`). The install
499/// driver writes shims there via `link_dep_bins`; `rebuild` mirrors
500/// the same pass.
501///
502/// For the `install` hook specifically, if the manifest leaves both
503/// `install` and `preinstall` empty but the package has a top-level
504/// `binding.gyp`, this falls back to running `node-gyp rebuild` — the
505/// node-gyp default that npm and pnpm both honor so native modules
506/// without a prebuilt binary still compile on install.
507///
508/// `tool_bin_dirs` are prepended to `PATH` *after* the dep's own
509/// `.bin` so that aube-bootstrapped tools (e.g. node-gyp) fill the
510/// gap for deps that shell out to them without declaring them as
511/// their own `dependencies`. The dep's local bin still wins if it
512/// shipped its own copy.
513///
514/// The caller is responsible for gating on `BuildPolicy` and
515/// `--ignore-scripts`. Returns `Ok(false)` if the hook wasn't defined.
516pub async fn run_dep_hook(
517    package_dir: &Path,
518    dep_modules_dir: &Path,
519    project_root: &Path,
520    modules_dir_name: &str,
521    manifest: &PackageJson,
522    hook: LifecycleHook,
523    tool_bin_dirs: &[&Path],
524) -> Result<bool, Error> {
525    let name = hook.script_name();
526    let script_cmd: &str = match manifest.scripts.get(name) {
527        Some(s) => s.as_str(),
528        None => match hook {
529            LifecycleHook::Install => match default_install_script(package_dir, manifest) {
530                Some(s) => s,
531                None => return Ok(false),
532            },
533            _ => return Ok(false),
534        },
535    };
536    let dep_bin_dir = dep_modules_dir.join(".bin");
537    let mut bin_dirs: Vec<&Path> = Vec::with_capacity(tool_bin_dirs.len() + 1);
538    bin_dirs.push(&dep_bin_dir);
539    bin_dirs.extend(tool_bin_dirs.iter().copied());
540    run_script(
541        package_dir,
542        project_root,
543        modules_dir_name,
544        manifest,
545        name,
546        script_cmd,
547        &bin_dirs,
548    )
549    .await?;
550    Ok(true)
551}
552
553#[derive(Debug, thiserror::Error)]
554pub enum Error {
555    #[error("failed to spawn script {0}: {1}")]
556    Spawn(String, String),
557    #[error("script `{script}` exited with code {code:?}")]
558    NonZeroExit { script: String, code: Option<i32> },
559}