diff --git a/apps/desktop/loopx-control-plane/README.md b/apps/desktop/loopx-control-plane/README.md index deac5411c4..050ca96ee9 100644 --- a/apps/desktop/loopx-control-plane/README.md +++ b/apps/desktop/loopx-control-plane/README.md @@ -315,8 +315,18 @@ shell, and a shell update does not certify Goal acceptance or provider readiness The release workflow packages both layers from one Git revision. The installer and App-owned services use the same bounded tool search, -including standard Homebrew locations on macOS, without loading interactive -shell profiles. Finder launches therefore do not depend on terminal PATH setup. +including standard Homebrew locations on macOS and nvm-managed Node +directories on Unix, without loading interactive shell profiles. Finder +launches therefore do not depend on terminal PATH setup. nvm resolution is +read-only and never runs nvm or sources a startup file. An `NVM_BIN` the +launching shell exported stays first while it still matches the Node that PATH +selects; once the shell selects a different Node, the variable is stale and its +directory drops to the last resort, behind every discovered nvm location. nvm +locations this App discovers on disk — the recorded `default` alias, then the +installed versions newest-first — are appended behind Homebrew and the +inherited PATH, so an inferred stale default cannot displace a Node the host +already provides, while a host whose only Node is nvm-managed still gets one. +Each directory appears once in the search. When preparing the first App-owned snapshot, an already selected managed CLI's recorded Python is reused if the App has no interpreter record of its own. This leaves that CLI's launcher and installation owner unchanged. diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/services.rs b/apps/desktop/loopx-control-plane/src-tauri/src/services.rs index 633fd66171..138eec8bb1 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/services.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/services.rs @@ -1088,38 +1088,247 @@ fn configure_codex_chat_home( } } +// Alias files chain (`default` -> `lts/*` -> `lts/krypton` -> `v24.22.1`). +// Read a bounded chain instead of running nvm, so a missing, cyclic or +// malformed chain just falls through to installed-version discovery. +#[cfg(unix)] +const NVM_ALIAS_DEPTH_LIMIT: usize = 8; + +// `v24.22.1`, `24.22.1` and the alias targets that name them are the only +// accepted forms; anything else is a non-version alias name to follow. +#[cfg(unix)] +fn nvm_version(name: &str) -> Option<(u64, u64, u64)> { + let trimmed = name.trim().strip_prefix('v').unwrap_or(name.trim()); + let mut fields = trimmed.split('.'); + let major = fields.next()?.parse().ok()?; + let minor = fields.next()?.parse().ok()?; + let patch = fields.next()?.parse().ok()?; + fields.next().is_none().then_some((major, minor, patch)) +} + +// Alias names are file names under `$NVM_DIR/alias`; keep the read inside that +// directory instead of letting a crafted alias escape it. +#[cfg(unix)] +fn is_bounded_nvm_alias(name: &str) -> bool { + !name.is_empty() + && !name.contains('\0') + && Path::new(name) + .components() + .all(|component| matches!(component, std::path::Component::Normal(_))) +} + +#[cfg(unix)] +fn resolve_nvm_alias(root: &Path, alias: &str, depth: usize) -> Option { + if depth >= NVM_ALIAS_DEPTH_LIMIT { + return None; + } + let name = alias.trim(); + if !is_bounded_nvm_alias(name) { + return None; + } + if let Some((major, minor, patch)) = nvm_version(name) { + // nvm names its version directories with the `v` prefix, whatever + // form the alias chain used to reach them. + return Some(format!("v{major}.{minor}.{patch}")); + } + let target = fs::read_to_string(root.join("alias").join(name)).ok()?; + resolve_nvm_alias(root, &target, depth + 1) +} + +#[cfg(unix)] +fn installed_nvm_versions(root: &Path) -> Vec { + let Ok(entries) = fs::read_dir(root.join("versions/node")) else { + return Vec::new(); + }; + let mut versions: Vec<_> = entries + .flatten() + .filter_map(|entry| { + let name = entry.file_name().to_string_lossy().into_owned(); + nvm_version(&name).map(|version| (version, name)) + }) + .collect(); + versions.sort_by_key(|(version, _)| std::cmp::Reverse(*version)); + versions.into_iter().map(|(_, name)| name).collect() +} + +// nvm activates a Node by prepending `$NVM_BIN` to the interactive shell +// PATH. Finder/launchd never load that activation, so a host whose only Node +// is nvm-managed looks Node-less to the private installer and the owned +// services. Resolve the same bounded locations the Lark CLI resolver uses, +// without executing nvm or sourcing any startup file. +// +// An activation inherited from the launching shell (`nvm use`, or a +// terminal-launched App) is explicit intent, but only while it still matches +// the Node that PATH selects. A shell can keep a stale `NVM_BIN` after putting +// another Node first, and preferring the stale directory there would replace a +// working Node with an unsupported one. Without that agreement the directory is +// only a fallback, ranked behind every discovered nvm location. +#[cfg(unix)] +fn explicit_nvm_directories( + nvm_bin: Option<&std::ffi::OsStr>, + inherited: Option<&std::ffi::OsStr>, +) -> Vec { + let Some(active) = nvm_bin.filter(|value| !value.is_empty()) else { + return Vec::new(); + }; + let directory = PathBuf::from(active); + if !nvm_bin_agrees_with_inherited_node(&directory, inherited) { + return Vec::new(); + } + let mut directories = Vec::new(); + push_tool_directory(&mut directories, directory); + directories +} + +// `NVM_BIN` agrees when the inherited PATH has no Node of its own, or when the +// Node it resolves to is the same executable nvm activated. Anything else means +// the shell moved on and left the variable behind. +#[cfg(unix)] +fn nvm_bin_agrees_with_inherited_node(nvm_bin: &Path, inherited: Option<&std::ffi::OsStr>) -> bool { + match resolve_executable_path("node", inherited) { + Some(inherited_node) => paths_refer_to_same_file( + &inherited_node.to_string_lossy(), + &nvm_bin.join("node").to_string_lossy(), + ), + None => true, + } +} + +// Discovered, never activated: the recorded `default` alias first, then the +// installed versions newest-first. Appended behind the known runtimes and the +// inherited PATH, so a stale default cannot hide a supported Homebrew or +// inherited Node, and a host without any other Node still finds nvm. A +// demoted `NVM_BIN` ranks last: it is an explicit location the host no longer +// selects, so a newer installed version must win before it. +#[cfg(unix)] +fn discovered_nvm_directories(nvm_root: &Path, demoted_nvm_bin: Option<&Path>) -> Vec { + let mut directories = Vec::new(); + if let Some(version) = resolve_nvm_alias(nvm_root, "default", 0) { + push_tool_directory( + &mut directories, + nvm_root.join("versions/node").join(version).join("bin"), + ); + } + for version in installed_nvm_versions(nvm_root) { + push_tool_directory( + &mut directories, + nvm_root.join("versions/node").join(version).join("bin"), + ); + } + if let Some(demoted) = demoted_nvm_bin { + push_tool_directory(&mut directories, demoted.to_path_buf()); + } + directories +} + +#[cfg(unix)] +fn push_tool_directory(directories: &mut Vec, candidate: PathBuf) { + if candidate.is_dir() && !directories.contains(&candidate) { + directories.push(candidate); + } +} + +// One tool search, one copy of each directory: a candidate discovered twice +// (an activated version that is also the recorded default, or an inherited +// entry this App also adds) must not appear twice in the search path. +fn extend_unique(paths: &mut Vec, candidates: impl IntoIterator) { + for candidate in candidates { + if !paths.contains(&candidate) { + paths.push(candidate); + } + } +} + +#[cfg(unix)] +fn nvm_root(home: Option<&std::ffi::OsStr>) -> Option { + if let Some(configured) = env::var_os("NVM_DIR").filter(|value| !value.is_empty()) { + return Some(PathBuf::from(configured)); + } + home.map(|home| PathBuf::from(home).join(".nvm")) +} + fn runtime_search_path( home: Option, inherited: Option, +) -> std::ffi::OsString { + #[cfg(unix)] + let nvm_root = nvm_root(home.as_deref()); + #[cfg(unix)] + let nvm_bin = env::var_os("NVM_BIN").filter(|value| !value.is_empty()); + runtime_search_path_from( + home, + inherited, + #[cfg(unix)] + nvm_root.as_deref(), + #[cfg(unix)] + nvm_bin.as_deref(), + ) +} + +// The nvm inputs are parameters so a test can pin them without mutating the +// process environment that parallel tests read. +fn runtime_search_path_from( + home: Option, + inherited: Option, + #[cfg(unix)] nvm_root: Option<&Path>, + #[cfg(unix)] nvm_bin: Option<&std::ffi::OsStr>, ) -> std::ffi::OsString { let mut paths = Vec::new(); - if let Some(home) = home { + if let Some(ref home) = home { paths.push(PathBuf::from(home).join(".local/bin")); } - if cfg!(target_os = "macos") { - paths.extend([ - PathBuf::from("/opt/homebrew/bin"), - PathBuf::from("/usr/local/bin"), - // Homebrew's supported LTS Node formulae are keg-only. Finder - // does not inherit the shell PATH that activates those runtimes. - // Use the same bounded search for the private installer and the - // services it starts; Core still qualifies the actual version. - PathBuf::from("/opt/homebrew/opt/node@24/bin"), - PathBuf::from("/usr/local/opt/node@24/bin"), - PathBuf::from("/opt/homebrew/opt/node@22/bin"), - PathBuf::from("/usr/local/opt/node@22/bin"), - ]); + // An activation the launching shell exported keeps the precedence the + // inherited PATH already gave it, but only while it still agrees with the + // Node that PATH selects. + #[cfg(unix)] + let explicit_nvm_bin = nvm_bin.and_then(|nvm_bin| { + explicit_nvm_directories(Some(nvm_bin), inherited.as_deref()) + .into_iter() + .next() + }); + #[cfg(unix)] + if let Some(nvm_bin) = explicit_nvm_bin.as_deref() { + extend_unique(&mut paths, [nvm_bin.to_path_buf()]); } - for path in inherited - .as_deref() - .map(env::split_paths) - .into_iter() - .flatten() - { - if !paths.contains(&path) { - paths.push(path); - } + if cfg!(target_os = "macos") { + extend_unique( + &mut paths, + [ + PathBuf::from("/opt/homebrew/bin"), + PathBuf::from("/usr/local/bin"), + // Homebrew's supported LTS Node formulae are keg-only. Finder + // does not inherit the shell PATH that activates those runtimes. + // Use the same bounded search for the private installer and the + // services it starts; Core still qualifies the actual version. + PathBuf::from("/opt/homebrew/opt/node@24/bin"), + PathBuf::from("/usr/local/opt/node@24/bin"), + PathBuf::from("/opt/homebrew/opt/node@22/bin"), + PathBuf::from("/usr/local/opt/node@22/bin"), + ], + ); } + // A `NVM_BIN` the host no longer selects is demoted to the last resort, + // behind the discovered versions so a newer install still wins over it. + #[cfg(unix)] + let demoted_nvm_bin = nvm_bin + .filter(|nvm_bin| explicit_nvm_bin.as_deref() != Some(Path::new(nvm_bin))) + .map(PathBuf::from); + #[cfg(unix)] + let discovered = nvm_root + .map(|nvm_root| discovered_nvm_directories(nvm_root, demoted_nvm_bin.as_deref())) + .unwrap_or_default(); + extend_unique( + &mut paths, + inherited + .as_deref() + .map(env::split_paths) + .into_iter() + .flatten(), + ); + // Inferred nvm locations are the last resort: they extend the search for a + // host that has no other Node, and never displace one that already exists. + #[cfg(unix)] + extend_unique(&mut paths, discovered); env::join_paths(paths).unwrap_or_else(|_| inherited.unwrap_or_default()) } diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs index ecb7547f7b..55fee497a3 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs @@ -107,6 +107,12 @@ fn status_readiness_is_explicit_and_fails_closed() { #[test] #[cfg(target_os = "macos")] fn finder_runtime_path_includes_tools_without_loading_shell_profiles() { + // An nvm-activated test shell would prepend its own NVM_BIN to this + // fixture home's search path, so the fixed-position assertions below only + // hold for a process started without that activation. + if ambient_nvm_activation() { + return; + } let path = runtime_search_path( Some("/fixture/user".into()), Some("/usr/bin:/bin:/usr/sbin:/sbin".into()), @@ -134,6 +140,370 @@ fn finder_runtime_path_includes_tools_without_loading_shell_profiles() { assert_eq!(again, path, "tool search must be idempotent"); } +#[cfg(unix)] +fn nvm_fixture(root: &Path, default: &str) -> PathBuf { + let versions = root.join("versions/node"); + for version in ["v24.22.1", "v22.14.0", "v20.18.0"] { + fs::create_dir_all(versions.join(version).join("bin")).expect("nvm version bin"); + } + let alias = root.join("alias"); + fs::create_dir_all(alias.join("lts")).expect("nvm alias directory"); + fs::write(alias.join("default"), format!("{default}\n")).expect("default alias"); + fs::write(alias.join("lts/*"), "lts/krypton\n").expect("lts alias"); + fs::write(alias.join("lts/krypton"), "v24.22.1\n").expect("lts codename alias"); + root.to_path_buf() +} + +// A real Node stand-in so a resolution assertion doubles as a version +// qualification: the search order decides which executable Core would probe. +#[cfg(unix)] +fn node_fixture(bin: &Path, version: &str) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + fs::create_dir_all(bin).expect("node fixture bin"); + let executable = bin.join("node"); + fs::write(&executable, format!("#!/bin/sh\nprintf 'v{version}\\n'\n")) + .expect("node fixture executable"); + fs::set_permissions(&executable, fs::Permissions::from_mode(0o755)).expect("node fixture mode"); + executable +} + +// An nvm-activated test shell would resolve this fixture home against the +// developer's own NVM_DIR/NVM_BIN, so the fixed-position assertions below only +// hold for a process started without that activation. +#[cfg(unix)] +fn ambient_nvm_activation() -> bool { + env::var_os("NVM_DIR").is_some() || env::var_os("NVM_BIN").is_some() +} + +#[test] +#[cfg(unix)] +fn finder_runtime_path_finds_nvm_managed_node() { + let home = tempfile::tempdir().expect("home fixture"); + let nvm_root = nvm_fixture(&home.path().join(".nvm"), "v24.22.1"); + let path = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some("/usr/bin:/bin:/usr/sbin:/sbin".into()), + Some(&nvm_root), + None, + ); + let paths: Vec<_> = env::split_paths(&path).collect(); + let default_bin = nvm_root.join("versions/node/v24.22.1/bin"); + let position = |candidate: &Path| { + paths + .iter() + .position(|p| p == candidate) + .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) + }; + assert_eq!(paths[0], home.path().join(".local/bin")); + // A host whose only Node is nvm-managed must still be found from Finder. + assert!(paths.contains(&default_bin)); + // Inferred nvm is the last resort: behind every candidate the host already + // provides, and behind the inherited PATH a terminal launch contributes. + // The Homebrew entries are only added on macOS, so they are asserted there. + let mut existing: Vec<&Path> = vec![Path::new("/usr/bin"), Path::new("/bin")]; + #[cfg(target_os = "macos")] + existing.extend([ + Path::new("/opt/homebrew/bin"), + Path::new("/usr/local/bin"), + Path::new("/opt/homebrew/opt/node@24/bin"), + Path::new("/usr/local/opt/node@24/bin"), + Path::new("/opt/homebrew/opt/node@22/bin"), + Path::new("/usr/local/opt/node@22/bin"), + ]); + for existing in existing { + assert!( + position(existing) < position(&default_bin), + "inferred nvm must stay behind the existing candidate {}", + existing.display() + ); + } + assert!( + position(&nvm_root.join("versions/node/v22.14.0/bin")) > position(&default_bin), + "the recorded default alias leads the discovered versions" + ); + assert!( + position(&nvm_root.join("versions/node/v20.18.0/bin")) + > position(&nvm_root.join("versions/node/v22.14.0/bin")), + "installed nvm versions are discovered newest-first" + ); + let mut unique = paths.clone(); + unique.sort(); + unique.dedup(); + assert_eq!( + unique.len(), + paths.len(), + "one tool search must not repeat a directory: {paths:?}" + ); + assert_eq!( + paths.iter().filter(|p| *p == &default_bin).count(), + 1, + "the recorded default alias is also an installed version and must appear once" + ); + let again = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(path.clone()), + Some(&nvm_root), + None, + ); + assert_eq!(again, path, "tool search must be idempotent"); +} + +// A terminal activation is authoritative only while it still matches the Node +// the inherited PATH selects. A shell that put another Node first after `nvm +// use` leaves a stale `NVM_BIN` behind, and preferring it would replace a +// working Node with an unsupported one. +#[test] +#[cfg(unix)] +fn stale_nvm_bin_yields_to_the_node_the_shell_selected() { + let home = tempfile::tempdir().expect("home fixture"); + let nvm_root = nvm_fixture(&home.path().join(".nvm"), "v24.22.1"); + let stale = nvm_root.join("versions/node/v20.18.0/bin"); + node_fixture(&stale, "20.18.0"); + let selected = node_fixture(&home.path().join("selected/node/bin"), "24.22.1"); + let selected_bin = selected.parent().expect("selected bin").to_path_buf(); + + // Still the selected Node: the activation keeps terminal-launch precedence. + let agreed = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(selected_bin.to_string_lossy().into_owned().into()), + Some(&nvm_root), + Some(selected_bin.as_os_str()), + ); + let agreed_paths: Vec<_> = env::split_paths(&agreed).collect(); + let position = |candidate: &Path| { + agreed_paths + .iter() + .position(|p| p == candidate) + .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) + }; + assert_eq!( + position(selected_bin.as_path()), + 1, + "an activation that still matches the selected Node keeps its precedence" + ); + assert_demoted_nvm_bin_is_last_resort(&nvm_root, &stale, agreed.as_os_str()); + + // No longer the selected Node: the stale directory becomes a last resort. + let stale_nvm_bin = stale.as_os_str(); + let demoted = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(selected_bin.to_string_lossy().into_owned().into()), + Some(&nvm_root), + Some(stale_nvm_bin), + ); + let demoted_paths: Vec<_> = env::split_paths(&demoted).collect(); + let demoted_position = |candidate: &Path| { + demoted_paths + .iter() + .position(|p| p == candidate) + .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) + }; + assert!( + demoted_position(selected_bin.as_path()) < demoted_position(&stale), + "a stale NVM_BIN must not precede the Node the shell selected" + ); + assert!( + demoted_position(&nvm_root.join("versions/node/v24.22.1/bin")) < demoted_position(&stale), + "a newer installed version outranks a demoted NVM_BIN" + ); + assert_demoted_nvm_bin_is_last_resort(&nvm_root, &stale, demoted.as_os_str()); + + // Nothing else on the PATH: the activation is the only candidate, so it + // stays authoritative and nvm-only hosts keep working. + let only_nvm = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some("/usr/bin:/bin".into()), + Some(&nvm_root), + Some(stale_nvm_bin), + ); + let only_nvm_paths: Vec<_> = env::split_paths(&only_nvm).collect(); + assert!( + only_nvm_paths.contains(&stale), + "an activation with no competing Node stays in the search" + ); + let mut unique = only_nvm_paths.clone(); + unique.sort(); + unique.dedup(); + assert_eq!( + unique.len(), + only_nvm_paths.len(), + "no duplicate directories" + ); +} + +// An inferred nvm candidate may only be selected when no other candidate +// exists on the host. That rule must hold on any machine, with or without a +// Homebrew Node, so the oracle checks the host instead of assuming one. +#[cfg(unix)] +fn assert_inferred_nvm_never_displaces_existing( + nvm_root: &Path, + stale_default_bin: &Path, + search: &std::ffi::OsStr, +) { + let resolved = + resolve_executable_path("node", Some(search)).expect("the search must resolve a Node"); + let host_has_other_node = env::split_paths(search) + .any(|directory| !directory.starts_with(nvm_root) && directory.join("node").is_file()); + if host_has_other_node { + assert_ne!( + resolved, + stale_default_bin.join("node"), + "an inferred stale nvm default must not displace a candidate the host already provides" + ); + assert!( + !resolved.starts_with(nvm_root), + "resolution must come from an existing candidate, not the inferred default: {}", + resolved.display() + ); + } else { + assert_eq!( + resolved, + stale_default_bin.join("node"), + "nvm-managed Node stays discoverable when nothing else provides one" + ); + } +} + +// A demoted `NVM_BIN` may only be selected when nothing else can be: a Node +// the host provides, or a newer nvm install, must win first. The oracle reads +// the host instead of assuming which candidate that is. +#[cfg(unix)] +fn assert_demoted_nvm_bin_is_last_resort( + nvm_root: &Path, + stale_bin: &Path, + search: &std::ffi::OsStr, +) { + let resolved = + resolve_executable_path("node", Some(search)).expect("the search must resolve a Node"); + let host_candidate = env::split_paths(search) + .find(|directory| !directory.starts_with(nvm_root) && directory.join("node").is_file()); + match host_candidate { + Some(directory) => assert_eq!( + resolved, + directory.join("node"), + "a demoted NVM_BIN must yield to the Node the host provides" + ), + None => assert_ne!( + resolved, + stale_bin.join("node"), + "a demoted NVM_BIN may only be selected when nothing else can be" + ), + } +} + +// The reviewer's regression: a Finder launch with no NVM_BIN, an nvm `default` +// that predates the supported minimum, and a Node the host already provides. +// The inferred default must be discovered, never preferred. +#[test] +#[cfg(unix)] +fn inferred_nvm_default_cannot_shadow_an_existing_qualified_node() { + let home = tempfile::tempdir().expect("home fixture"); + let nvm_root = nvm_fixture(&home.path().join(".nvm"), "v20.18.0"); + let stale_default = nvm_root.join("versions/node/v20.18.0/bin"); + node_fixture(&stale_default, "20.18.0"); + // A supported Node the host already provides, the way Homebrew or an + // inherited terminal PATH would. + let qualified = node_fixture(&home.path().join("qualified/node/bin"), "24.22.1"); + let qualified_bin = qualified.parent().expect("qualified bin").to_path_buf(); + let with_candidate = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(qualified_bin.to_string_lossy().into_owned().into()), + Some(&nvm_root), + None, + ); + assert_inferred_nvm_never_displaces_existing( + &nvm_root, + &stale_default, + with_candidate.as_os_str(), + ); + + // The ordering guarantee behind that resolution: every non-nvm candidate, + // including the Homebrew entries this App adds, precedes the inferred one. + let paths: Vec<_> = env::split_paths(&with_candidate).collect(); + let position = |candidate: &Path| { + paths + .iter() + .position(|p| p == candidate) + .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) + }; + // The Homebrew entries only exist on macOS, so they are asserted there. + let local_bin = home.path().join(".local/bin"); + let mut existing: Vec<&Path> = vec![local_bin.as_path(), qualified_bin.as_path()]; + #[cfg(target_os = "macos")] + existing.extend([ + Path::new("/opt/homebrew/bin"), + Path::new("/usr/local/bin"), + Path::new("/opt/homebrew/opt/node@24/bin"), + Path::new("/usr/local/opt/node@24/bin"), + Path::new("/opt/homebrew/opt/node@22/bin"), + Path::new("/usr/local/opt/node@22/bin"), + ]); + for existing in existing { + assert!( + position(existing) < position(&stale_default), + "inferred nvm must stay behind the existing candidate {}", + existing.display() + ); + } + + // Without any other Node on the host, the same stale default is still the + // only candidate, so nvm remains discoverable rather than invisible. + let isolated = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some("/usr/bin:/bin".into()), + Some(&nvm_root), + None, + ); + assert!(env::split_paths(&isolated).any(|directory| directory == stale_default)); + assert_inferred_nvm_never_displaces_existing(&nvm_root, &stale_default, isolated.as_os_str()); +} + +#[test] +#[cfg(unix)] +fn nvm_alias_chain_resolves_versions_and_rejects_escapes() { + let root = tempfile::tempdir().expect("nvm fixture"); + let nvm_root = nvm_fixture(root.path(), "lts/*"); + assert_eq!( + resolve_nvm_alias(&nvm_root, "default", 0).as_deref(), + Some("v24.22.1"), + "the default alias chain resolves to the recorded version" + ); + assert_eq!( + resolve_nvm_alias(&nvm_root, "22.14.0", 0).as_deref(), + Some("v22.14.0"), + "a version without the v prefix still names nvm's directory" + ); + for alias in ["", "missing", "../outside", "/etc/passwd", "lts/../default"] { + assert_eq!( + resolve_nvm_alias(&nvm_root, alias, 0), + None, + "alias {alias:?} must not resolve" + ); + } + fs::write(nvm_root.join("alias/cycle"), "cycle").expect("cyclic alias"); + assert_eq!(resolve_nvm_alias(&nvm_root, "cycle", 0), None); + assert!(installed_nvm_versions(&nvm_root) + .iter() + .zip(["v24.22.1", "v22.14.0", "v20.18.0"]) + .all(|(found, expected)| found == expected)); + assert_eq!(nvm_version("v24.22.1"), Some((24, 22, 1))); + assert_eq!(nvm_version("not-a-version"), None); + assert_eq!(nvm_version("v24.22"), None); +} + +#[test] +#[cfg(unix)] +fn nvm_root_follows_configured_directory_and_conventional_home() { + match env::var_os("NVM_DIR").filter(|value| !value.is_empty()) { + Some(configured) => assert_eq!(nvm_root(None), Some(PathBuf::from(configured))), + None => assert_eq!( + nvm_root(Some(std::ffi::OsStr::new("/fixture/user"))), + Some(PathBuf::from("/fixture/user/.nvm")), + "an unset NVM_DIR keeps the conventional location" + ), + } +} + #[cfg(not(windows))] fn spawn_listener_fixture( executable: &Path,