aube 1.14.0

Aube — a fast Node.js package manager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! `aube approve-builds` — flip packages to `true` in the workspace
//! yaml's `allowBuilds` map so their install scripts run on the next
//! `aube install`. Writes to `aube-workspace.yaml` by default, or
//! mutates an existing `pnpm-workspace.yaml` in place.
//!
//! Walks the lockfile via `ignored_builds::collect_ignored`, presents an
//! interactive multi-select picker (or approves everything under
//! `--all`), then merges the selections into the workspace yaml's
//! `allowBuilds` map. Matches pnpm v11, which collapsed the old
//! allow/deny list keys into one review map. Entries are added as bare
//! package names so a future resolution of the same dep under a
//! different version keeps working without re-prompting.

use clap::Args;
use miette::{Context, IntoDiagnostic, miette};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::io::{IsTerminal, Write};
use std::path::Path;

const INTERACTIVE_TTY_ERROR: &str = "approve-builds needs stdin and stderr to be TTYs for the interactive picker; pass `--all` or name packages positionally to approve non-interactively";

#[derive(Debug, Args)]
pub struct ApproveBuildsArgs {
    /// Approve every pending ignored build without prompting.
    #[arg(long)]
    pub all: bool,

    /// Operate on globally-installed packages instead of the current project.
    #[arg(short = 'g', long)]
    pub global: bool,

    /// Packages to approve directly, skipping the picker.
    ///
    /// Each name must match a currently-ignored build. Unknown names
    /// are rejected so a typo cannot silently no-op.
    #[arg(value_name = "PKG")]
    pub packages: Vec<String>,
}

pub async fn run(args: ApproveBuildsArgs) -> miette::Result<()> {
    if args.global {
        return run_global(args);
    }

    let cwd = crate::dirs::project_root()?;
    let _lock = super::take_project_lock(&cwd)?;
    run_project(&cwd, args.all, args.packages)
}

fn run_project(cwd: &Path, all: bool, packages: Vec<String>) -> miette::Result<()> {
    let ignored = super::ignored_builds::collect_ignored(cwd)?;
    if ignored.is_empty() {
        println!("No ignored builds to approve.");
        return Ok(());
    }

    let selected = select_project(&ignored, all, packages)?;

    if selected.is_empty() {
        println!("No packages selected.");
        return Ok(());
    }

    let written = aube_manifest::workspace::add_to_allow_builds(cwd, &selected)
        .into_diagnostic()
        .wrap_err("failed to update workspace yaml")?;

    let rel = written
        .strip_prefix(cwd)
        .unwrap_or(written.as_path())
        .display();
    println!("Approved {} package(s) in {rel}:", selected.len());
    for name in &selected {
        println!("  {name}");
    }
    println!("Run `aube install` (or `aube rebuild`) to execute their scripts.");
    Ok(())
}

fn run_global(args: ApproveBuildsArgs) -> miette::Result<()> {
    let global_ignored = collect_global_ignored()?;
    if global_ignored.is_empty() {
        println!("No ignored builds to approve.");
        return Ok(());
    }

    let selected = if args.all {
        if !args.packages.is_empty() {
            return Err(miette!(
                "`--all` and positional package names are mutually exclusive"
            ));
        }
        global_ignored
            .iter()
            .map(|entry| {
                (
                    entry.install_dir.clone(),
                    entry.ignored.iter().map(|i| i.name.clone()).collect(),
                )
            })
            .collect()
    } else if !args.packages.is_empty() {
        select_global_packages(&global_ignored, args.packages)?
    } else {
        if !std::io::stdin().is_terminal() || !std::io::stderr().is_terminal() {
            return Err(miette!(INTERACTIVE_TTY_ERROR));
        }
        pick_global_interactively(&global_ignored)?
    };

    if selected.is_empty() {
        println!("No packages selected.");
        return Ok(());
    }

    let mut approved = 0usize;
    let mut written_dirs = 0usize;
    for (install_dir, names) in selected {
        let written = aube_manifest::workspace::add_to_allow_builds(&install_dir, &names)
            .into_diagnostic()
            .wrap_err("failed to update global install workspace yaml")?;
        written_dirs += 1;
        approved += names.len();
        println!(
            "Approved {} package(s) in {}:",
            names.len(),
            written.display()
        );
        for name in &names {
            println!("  {name}");
        }
    }

    println!("Approved {approved} package(s) across {written_dirs} global install(s).");
    println!("Run `aube -C <global-install-dir> install` (or `rebuild`) to execute their scripts.");
    Ok(())
}

fn select_project(
    ignored: &[super::ignored_builds::IgnoredEntry],
    all: bool,
    packages: Vec<String>,
) -> miette::Result<Vec<String>> {
    if all {
        if !packages.is_empty() {
            return Err(miette!(
                "`--all` and positional package names are mutually exclusive"
            ));
        }
        return Ok(ignored.iter().map(|e| e.name.clone()).collect());
    }
    if !packages.is_empty() {
        let known: HashSet<&str> = ignored.iter().map(|e| e.name.as_str()).collect();
        let unknown: Vec<&str> = packages
            .iter()
            .filter(|p| !known.contains(p.as_str()))
            .map(String::as_str)
            .collect();
        if !unknown.is_empty() {
            return Err(miette!(
                "not in the ignored-builds set: {}. Run `aube ignored-builds` to see candidates.",
                unknown.join(", ")
            ));
        }
        return Ok(dedupe(packages));
    }
    if !std::io::stdin().is_terminal() || !std::io::stderr().is_terminal() {
        return Err(miette!(INTERACTIVE_TTY_ERROR));
    }
    pick_interactively(ignored)
}

#[derive(Debug)]
struct GlobalIgnored {
    install_dir: std::path::PathBuf,
    aliases: Vec<String>,
    ignored: Vec<super::ignored_builds::IgnoredEntry>,
}

fn collect_global_ignored() -> miette::Result<Vec<GlobalIgnored>> {
    let layout = super::global::GlobalLayout::resolve()?;
    let mut seen = BTreeSet::new();
    let mut out = Vec::new();
    for info in super::global::scan_packages(&layout.pkg_dir) {
        if !seen.insert(info.install_dir.clone()) {
            continue;
        }
        let ignored = super::ignored_builds::collect_ignored(&info.install_dir)?;
        if ignored.is_empty() {
            continue;
        }
        out.push(GlobalIgnored {
            install_dir: info.install_dir,
            aliases: info.aliases,
            ignored,
        });
    }
    out.sort_by(|a, b| a.install_dir.cmp(&b.install_dir));
    Ok(out)
}

fn select_global_packages(
    global_ignored: &[GlobalIgnored],
    packages: Vec<String>,
) -> miette::Result<BTreeMap<std::path::PathBuf, Vec<String>>> {
    let wanted = dedupe(packages);
    let known: HashSet<&str> = global_ignored
        .iter()
        .flat_map(|entry| entry.ignored.iter().map(|ignored| ignored.name.as_str()))
        .collect();
    let unknown: Vec<&str> = wanted
        .iter()
        .filter(|name| !known.contains(name.as_str()))
        .map(String::as_str)
        .collect();
    if !unknown.is_empty() {
        return Err(miette!(
            "not in the ignored-builds set: {}. Run `aube ignored-builds -g` to see candidates.",
            unknown.join(", ")
        ));
    }

    let wanted: HashSet<&str> = wanted.iter().map(String::as_str).collect();
    let mut selected = BTreeMap::new();
    for entry in global_ignored {
        let names: Vec<String> = entry
            .ignored
            .iter()
            .filter(|ignored| wanted.contains(ignored.name.as_str()))
            .map(|ignored| ignored.name.clone())
            .collect();
        if !names.is_empty() {
            selected.insert(entry.install_dir.clone(), names);
        }
    }
    Ok(selected)
}

fn dedupe(packages: Vec<String>) -> Vec<String> {
    let mut seen = HashSet::new();
    packages
        .into_iter()
        .filter(|p| seen.insert(p.clone()))
        .collect()
}

/// Show a `demand::MultiSelect` picker seeded with every ignored package
/// and return the names the user accepted. Using bare names (not
/// `name@version`) keeps the written allowBuilds entry broad, so the
/// next resolution with a patch-level bump doesn't silently drop back
/// into the ignored set.
///
/// When any entry carries content-sniff suspicions, a one-shot summary
/// is printed to stderr before the picker opens so the user sees the
/// full list of flagged signals (the picker label only has room for
/// a short tag). The picker entry itself is annotated with `⚠
/// suspicious: <category>` so flagged rows stand out while scrolling.
fn pick_interactively(
    ignored: &[super::ignored_builds::IgnoredEntry],
) -> miette::Result<Vec<String>> {
    print_suspicion_summary(ignored);
    let mut picker = demand::MultiSelect::new("Choose which packages to allow building")
        .description("Space to toggle, Enter to confirm")
        .min(1);
    for entry in ignored {
        let label = format_picker_label(&entry.name, &entry.version, &entry.suspicions);
        picker = picker.option(demand::DemandOption::new(entry.name.clone()).label(&label));
    }
    picker
        .run()
        .into_diagnostic()
        .wrap_err("failed to read approve-builds selection")
}

/// `name@version` plus a compact suspicious-shape tag when the
/// content-sniff fired against any of the package's lifecycle
/// scripts. One picker row is narrow, so only the first match's
/// category gets a tag; `+N more` follows when more than one
/// matched. The full breakdown lives in `print_suspicion_summary`.
fn format_picker_label(
    name: &str,
    version: &str,
    suspicions: &[aube_scripts::Suspicion],
) -> String {
    if suspicions.is_empty() {
        return format!("{name}@{version}");
    }
    let first = suspicions[0].kind.category();
    let extra = suspicions.len() - 1;
    if extra == 0 {
        format!("{name}@{version}  ⚠ suspicious: {first}")
    } else {
        format!("{name}@{version}  ⚠ suspicious: {first} +{extra} more")
    }
}

/// Print every flagged package's full suspicion list to stderr before
/// the picker takes over the screen. No-op when nothing flagged so
/// the clean case stays terse.
fn print_suspicion_summary(ignored: &[super::ignored_builds::IgnoredEntry]) {
    let flagged: Vec<&super::ignored_builds::IgnoredEntry> = ignored
        .iter()
        .filter(|e| !e.suspicions.is_empty())
        .collect();
    if flagged.is_empty() {
        return;
    }
    let mut stderr = std::io::stderr().lock();
    let _ = writeln!(
        stderr,
        "{} package(s) have lifecycle scripts that matched dangerous-shape heuristics:",
        flagged.len()
    );
    for entry in flagged {
        let _ = writeln!(stderr, "  {}@{}", entry.name, entry.version);
        for sus in &entry.suspicions {
            let _ = writeln!(stderr, "{}{}", sus.hook, sus.kind.description());
        }
    }
    let _ = writeln!(
        stderr,
        "  Inspect each script in `node_modules/.aube/<dep_path>/node_modules/<name>/package.json` before approving."
    );
}

fn pick_global_interactively(
    global_ignored: &[GlobalIgnored],
) -> miette::Result<BTreeMap<std::path::PathBuf, Vec<String>>> {
    for entry in global_ignored {
        print_suspicion_summary(&entry.ignored);
    }
    let mut picker = demand::MultiSelect::new("Choose which global packages to allow building")
        .description("Space to toggle, Enter to confirm")
        .min(1);
    for (idx, entry) in global_ignored.iter().enumerate() {
        let aliases = entry.aliases.join(", ");
        for ignored in &entry.ignored {
            // split_once below keeps the full package name even if a
            // private registry allows ':' inside it.
            let value = format!("{idx}:{}", ignored.name);
            let base = format_picker_label(&ignored.name, &ignored.version, &ignored.suspicions);
            let label = format!("{aliases}: {base}");
            picker = picker.option(demand::DemandOption::new(value).label(&label));
        }
    }

    let picked: Vec<String> = picker
        .run()
        .into_diagnostic()
        .wrap_err("failed to read approve-builds selection")?;
    let mut selected: BTreeMap<std::path::PathBuf, Vec<String>> = BTreeMap::new();
    for item in picked {
        let Some((idx, name)) = item.split_once(':') else {
            continue;
        };
        let Ok(idx) = idx.parse::<usize>() else {
            continue;
        };
        let Some(entry) = global_ignored.get(idx) else {
            continue;
        };
        selected
            .entry(entry.install_dir.clone())
            .or_default()
            .push(name.to_string());
    }
    Ok(selected)
}

#[cfg(test)]
mod tests {
    use super::format_picker_label;
    use aube_scripts::{Suspicion, SuspicionKind};

    #[test]
    fn label_for_clean_package_is_bare_spec() {
        assert_eq!(
            format_picker_label("esbuild", "0.20.2", &[]),
            "esbuild@0.20.2"
        );
    }

    #[test]
    fn label_for_single_suspicion_shows_category() {
        let s = vec![Suspicion {
            kind: SuspicionKind::ShellPipe,
            hook: "postinstall",
        }];
        assert_eq!(
            format_picker_label("lodash", "1.0.0", &s),
            "lodash@1.0.0  ⚠ suspicious: curl|sh"
        );
    }

    #[test]
    fn label_for_multiple_suspicions_shows_first_plus_count() {
        let s = vec![
            Suspicion {
                kind: SuspicionKind::ShellPipe,
                hook: "postinstall",
            },
            Suspicion {
                kind: SuspicionKind::SecretEnvRead,
                hook: "postinstall",
            },
            Suspicion {
                kind: SuspicionKind::ExfilEndpoint,
                hook: "postinstall",
            },
        ];
        assert_eq!(
            format_picker_label("evil-pkg", "9.9.9", &s),
            "evil-pkg@9.9.9  ⚠ suspicious: curl|sh +2 more"
        );
    }
}