diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 209278a1f..663c7c098 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -894,7 +894,7 @@ Recognition rules that hold for every ecosystem: | Hosted: a discovered patch-host reference (or a live pre-v5 redirect-ledger record) | The installed copies the build **consumes** through the hosted wiring are hash-verified when any exist: the Go replacement module, never the pristine `M@v` in the module cache; the Socket-registry cargo source dir; maven's suffixed version. Installed evidence wins: `hash_mismatch` / `not_applied` are omitted. With **nothing installed**, a discovered reference whose lock pins the artifact (or whose format's rewriter never writes a pin) attests from that pin, which is the same evidence as in-run `scan --mode hosted --vex`. A pre-v5 ledger-only record, or a reference whose required pin is missing, stays `package_not_found`. So do purls that `--ecosystems` kept out of the crawl, because "not installed" has to mean the crawler looked. The same goes for npm purls when an installed pnpm tree records its virtual store outside the project (`enableGlobalVirtualStore`, or a `virtualStoreDir` that climbs out): transitive deps there are invisible to the crawler. A pnpm `modulesDir` inside the project is crawled. A Composer purl is omitted as `composer_install_unread` instead when `composer.json`'s `config.vendor-dir` puts the install outside the project (an absolute path, `~/…`, `$VAR/…`, or one that climbs out) and an install is there (its `composer/installed.json` exists, or the directory cannot be resolved): the crawler reads no tree outside the project that only a project file names, so that install was not checked and may predate the redirect (#686). While nothing is installed there the pin still attests, and with `COMPOSER_VENDOR_DIR` set to the directory the crawler reads it and the installed bytes decide. A yarn Plug'n'Play project (`.pnp.cjs` / `.pnp.js`) has no tree to crawl: an npm purl there attests from the lock's pin only when the PnP loader itself resolves it through the patch (berry names the hosted url, yarn 1 the resolved url's `#` in its cache folder). A loader written before the lock was rewired runs the registry copy, so the purl stays omitted until `yarn install` rewrites it (#519). | `(redirected)` | | Agent: a manifest record with no live hosted/vendored wiring | The installed tree, unchanged. **Every** installed copy the crawler finds for the purl (npm nests duplicates of one `name@version`; pnpm, vlt, Bun and Deno stores add peer-variant copies and copies bundled inside other packages) must hash to the patched bytes, as `apply` patches every copy (Maven: every copy a build consumes, Gradle hash dirs included — see [Gradle builds](#gradle-builds-v50)). One unpatched copy omits the purl with that copy's tag (`not_applied` / `hash_mismatch`). | none | -**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `@socket-+` for a release routed through the registry of its patch and `@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `@` entry stays in the store, pristine. An entry that no link leads into is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. For pnpm this applies to a package version only when its copies sit in two or more entries of one store and do not hold the same bytes in each; a version in one entry is hashed as before, linked or not, and so are copies that hold the same bytes (the peer variants of a package), since leaving one out would change no verdict; copies of more than 64 MB or 50,000 files are not compared and count as holding other bytes. For a version in two entries, every symbolic link is read below the scanned directory (or below the project that holds the store, when the scan started inside it), in every directory whatever its name; nothing above that directory is read. A link that leads nowhere (no target, a loop, a path through a file) is left out. An entry is hashed when a link outside the store's entries resolves into it, or a link inside a hashed entry does; the entries left out are those that only other left-out entries link, and only beside a hashed entry of the same version: when none of a version's entries is linked, all are hashed as before (a hosted scan leaves such a pair when the patched package is a peer dependency: the dependent gets a new entry, and its old entry keeps its link to the old one). A copy in the store but in none of its entries is always hashed. Only links are read, not a path to an entry that a file spells out or `NODE_PATH` names. Every store is judged once per run, by the same links for the record check and the hosted one. Where a link may have gone unread, every entry is hashed: on Windows; when the scanned directory and the store's project are unrelated (`--global`, a `node_modules` linked from another checkout), or the store's project lies above the git checkout the run started in; under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or the lockfile in the store is missing or unreadable, `pnpm-lock.yaml` is unreadable, or either lists its importers in a way pnpm does not write; when a lockfile names an importer that is not a directory inside the store's project (also a `modulesDir` of more than one level); when a directory or a link cannot be read, or the directory holds more than 500,000 directories and links; when a link resolves to a directory outside the directory that was read, to a file outside it that has a `node_modules` in a directory above it (the home directory and above are not looked at), to the store itself, or into the store by a path that names none of its entries (another spelling of the store's path or of an entry's name); and when no link resolves into any entry (`docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list). `rollback` and `remove` restore unlinked entries too. +**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `@socket-+` for a release routed through the registry of its patch and `@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `@` entry stays in the store, pristine. An entry that no link leads into is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. For pnpm this applies to a package version only when its copies sit in two or more entries of one store and do not hold the same bytes in each; a version in one entry is hashed as before, linked or not, and so are copies that hold the same bytes (the peer variants of a package), since leaving one out would change no verdict; copies of more than 64 MB or 50,000 files are not compared and count as holding other bytes. For a version in two entries, every symbolic link is read below the scanned directory (or below the project that holds the store, when the scan started inside it), in every directory whatever its name; nothing above that directory is read. A link that leads nowhere (no target, a loop, a path through a file) is left out. An entry is hashed when a link outside the store's entries resolves into it, or a link inside a hashed entry does; the entries left out are those that only other left-out entries link, and only beside a hashed entry of the same version: when none of a version's entries is linked, all are hashed as before (a hosted scan leaves such a pair when the patched package is a peer dependency: the dependent gets a new entry, and its old entry keeps its link to the old one). A copy in the store but in none of its entries is always hashed. Only links are read, not a path to an entry that a file spells out or `NODE_PATH` names. Every store is judged once per run, by the same links for the record check and the hosted one. Where a link may have gone unread, every entry is hashed: on Windows; when the scanned directory and the store's project are unrelated (`--global`, a `node_modules` linked from another checkout), or the store's project lies above the git checkout the run started in or, above the scanned directory, is the home directory or above it; under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or the lockfile in the store is missing or unreadable, `pnpm-lock.yaml` is unreadable, or either lists its importers in a way pnpm does not write; when a lockfile names an importer that is not a directory inside the workspace's root (under a `modulesDir` of more than one level, the directory whose `modulesDir` setting names the store's `node_modules`); when a directory or a link cannot be read, or the directory holds more than 500,000 directories and links; when a link resolves to a directory outside the directory that was read, to a file outside it that has a `node_modules` in a directory above it (the home directory and above are not looked at), to the store itself, or into the store by a path that names none of its entries (another spelling of the store's path or of an entry's name); and when no link resolves into any entry (`docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list). `rollback` and `remove` restore unlinked entries too. **Liveness gates.** These gates run before hashing, and `--no-verify` / `--vex-no-verify` skips only the hashing, never the gates: diff --git a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs index de10c2e2d..8a046719a 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs @@ -3938,11 +3938,13 @@ async fn pnpm11_registry_route_in_place_install_is_judged_by_every_link() { /// `node_modules/.pnpm`). The lockfile in the store still names the /// members by their paths from the workspace root, and none of them is a /// directory below `sub/`, the directory that holds the store's -/// `node_modules`. `vex` cannot tell which directory the members' links -/// are below, so it keeps every entry: the upstream entries the in-place -/// install left behind refuse both patches as `not_applied`, as before -/// #2353, although nothing links them. A run from a member finds no patch -/// to attest: the scan's files are the workspace root's. +/// `node_modules`. The root is the directory whose `modulesDir` setting +/// names that `node_modules`, and `vex` judges the store from there: the +/// upstream entries the in-place install left behind are left out, and +/// both patches are attested. A link to the upstream `leaf` from a +/// member's own modules dir refuses its patch until the link is gone. A +/// run from a member finds no patch to attest: the scan's files are the +/// workspace root's. #[cfg(unix)] async fn registry_route_in_place_install_under_a_nested_modules_dir(pm: &str, tag: &str) { if !has_corepack_pm(pm) { @@ -3993,18 +3995,41 @@ async fn registry_route_in_place_install_under_a_nested_modules_dir(pm: &str, ta "{tag}: {unpatched:?} hold the upstream leaf, unlinked: {reachable:?}" ); + let not_affected = |patch: &RoutePatch| (patch.advisory(), "not_affected".to_string()); let (code, attested, stderr) = route_vex(&proj, &server); - assert_ne!(code, 0, "{tag}: vex from the root: {attested:?}\n{stderr}"); - assert!(attested.is_empty(), "{tag}: {attested:?}\n{stderr}"); + assert_eq!(code, 0, "{tag}: vex from the root: {attested:?}\n{stderr}"); for patch in &ROUTE_PATCHES { - // Named as `@`, in a purl when it is the only one. - let release = format!("{}@{ROUTE_VERSION}", patch.name); assert!( - stderr.contains(&release) && stderr.contains("not_applied"), - "{tag}: every entry is judged, so {} is refused:\n{stderr}", + attested.contains(¬_affected(patch)), + "{tag}: {} must be attested under the nested modulesDir: {attested:?}\n{stderr}", patch.name ); } + // A link to the upstream leaf in a member's own modules dir is a way + // to load it: the independent reading finds it, and vex refuses the + // patch until the link is gone. + let link = proj.join("packages/a/sub/node_modules/old-leaf"); + std::os::unix::fs::symlink(store.join("leaf@1.0.0/node_modules/leaf"), &link).unwrap(); + let reachable = pnpm_links::reachable_store_entries(&proj, &store); + assert!( + reachable.contains("leaf@1.0.0"), + "{tag}: the independent reading must find the link: {reachable:?}" + ); + let (code, attested, stderr) = route_vex(&proj, &server); + assert_eq!(code, 0, "{tag}: vex with the link: {attested:?}\n{stderr}"); + assert!( + !attested.contains(¬_affected(leaf)) + && stderr.contains("leaf@1.0.0") + && stderr.contains("not_applied"), + "{tag}: a link from a member's modules dir must refuse leaf: {attested:?}\n{stderr}" + ); + std::fs::remove_file(&link).unwrap(); + let (code, attested, stderr) = route_vex(&proj, &server); + assert_eq!(code, 0, "{tag}: vex without the link:\n{stderr}"); + assert!( + attested.contains(¬_affected(leaf)), + "{tag}: without the link leaf is attested again: {attested:?}\n{stderr}" + ); let (code, attested, stderr) = route_vex(&proj.join("packages/b"), &server); assert_ne!(code, 0, "{tag}: vex from a member: {attested:?}\n{stderr}"); assert!(attested.is_empty(), "{tag}: {attested:?}\n{stderr}"); diff --git a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs index ee1eff81e..49d022f0b 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs @@ -2803,24 +2803,31 @@ fn pnpm_hosted_ref_is_hashed_in_a_store_reached_through_a_linked_node_modules() /// member's dependencies in `/` (real pnpm 12.25.1 /// layout). The lockfile in the store names the members from the /// workspace root, and none of them is a directory below `sub/`, which -/// holds the store's `node_modules`. The store's entries are not judged -/// then: the pristine upstream entry is hashed and refuses the patch, -/// although nothing links it. The same workspace without the setting is -/// judged, and attests. +/// holds the store's `node_modules`. The root is the directory whose +/// `modulesDir` setting names that `node_modules`: the store is judged +/// from there, the pristine upstream entry is left out, and the patch is +/// attested, until a link in the member's own modules dir reaches that +/// entry. With no setting to say where the root is, the store's entries +/// are not judged: the upstream entry is hashed and refuses the patch. #[cfg(unix)] #[test] -fn pnpm_hosted_ref_is_hashed_in_a_store_under_a_nested_modules_dir() { +fn pnpm_hosted_ref_in_a_store_under_a_nested_modules_dir_is_judged_from_the_root() { let (pristine, patched) = ( &b"module.exports = 'pristine'\n"[..], &b"module.exports = 'patched'\n"[..], ); let purl = "pkg:npm/left-pad@1.3.0"; let routed = format!("left-pad@socket-{}+1.3.0", &UUID[..8]); - for (modules_dir, attests) in [("node_modules", true), ("sub/node_modules", false)] { + for (modules_dir, setting, attests) in [ + ("node_modules", false, true), + ("sub/node_modules", true, true), + ("sub/node_modules", false, false), + ] { + let case = format!("{modules_dir}, setting {setting}"); let tmp = tempfile::tempdir().unwrap(); let cwd = &tmp.path().join("app"); write_pnpm_member_routing_left_pad(cwd); - if modules_dir != "node_modules" { + if setting { let workspace = cwd.join("pnpm-workspace.yaml"); let text = std::fs::read_to_string(&workspace).unwrap(); std::fs::write(workspace, format!("{text}modulesDir: {modules_dir}\n")).unwrap(); @@ -2835,26 +2842,41 @@ fn pnpm_hosted_ref_is_hashed_in_a_store_under_a_nested_modules_dir() { ); // From `packages/a/` up to the workspace root. let up = "../".repeat(2 + modules_dir.split('/').count()); + let member_nm = cwd.join("packages/a").join(modules_dir); pnpm_link( &format!("{up}{modules_dir}/.pnpm/{routed}/node_modules/left-pad"), - &cwd.join("packages/a").join(modules_dir).join("left-pad"), + &member_nm.join("left-pad"), ); let (_rt, server) = serve_patch_views(vec![( UUID.to_string(), one_file_view(UUID, purl, "package/index.js", pristine, patched), )]); - - let (code, env) = vex_json(cwd, &["--proxy-url", &server.uri()]); - if attests { - assert_attested(cwd, code, &env, UUID, modules_dir); - } else { - assert_eq!(code, Some(1), "{modules_dir}: {env}"); + let refused = |what: &str| { + let (code, env) = vex_json(cwd, &["--proxy-url", &server.uri()]); + assert_eq!(code, Some(1), "{case}, {what}: {env}"); assert_eq!( skipped_reason(&env, purl), "not_applied", - "{modules_dir}: {env}" + "{case}, {what}: {env}" ); + }; + + if !attests { + refused("the root is not known"); + continue; } + let (code, env) = vex_json(cwd, &["--proxy-url", &server.uri()]); + assert_attested(cwd, code, &env, UUID, &case); + // A link to the pristine entry in the member's own modules dir. + let old = member_nm.join("old-left-pad"); + pnpm_link( + &format!("{up}{modules_dir}/.pnpm/left-pad@1.3.0/node_modules/left-pad"), + &old, + ); + refused("a link in the member's modules dir"); + std::fs::remove_file(&old).unwrap(); + let (code, env) = vex_json(cwd, &["--proxy-url", &server.uri()]); + assert_attested(cwd, code, &env, UUID, &format!("{case}, the link removed")); } } diff --git a/crates/socket-patch-core/src/crawlers/npm_crawler.rs b/crates/socket-patch-core/src/crawlers/npm_crawler.rs index 7106de993..c2d25959a 100644 --- a/crates/socket-patch-core/src/crawlers/npm_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/npm_crawler.rs @@ -901,8 +901,9 @@ fn orphaned_pnpm_store_entry_sync( /// (`_@socket-+`), and its old entry keeps /// its link to the old one (measured on pnpm 11.29.0 and 12.25.1). /// -/// `tree` is the outer of the directory `scanned` and the directory that -/// holds the store's `node_modules`. A link outside it is not read (one +/// `tree` is the outer of the directory `scanned` and the workspace's +/// root (the directory that holds the store's `node_modules`, or the one +/// a `modulesDir` setting points from). A link outside it is not read (one /// in a `node_modules` above it, which pnpm does not write into this /// store, or in another checkout), so every entry is kept wherever pnpm /// may have written one there, or the links cannot all be read or @@ -912,11 +913,15 @@ fn orphaned_pnpm_store_entry_sync( /// - when neither of the two directories holds the other (a /// `node_modules` that is a link to another checkout's, a global /// install), or the directory that holds the store's `node_modules` -/// lies above the git checkout the scan runs in, which a project run -/// does not read +/// lies above the git checkout the scan runs in, or above the scanned +/// directory at or above the home directory, which a project run does +/// not read /// ([`upward_readable`](crate::utils::repo_root::upward_readable)); -/// - when the store is not the one `node_modules/.modules.yaml` records, -/// or the record is not of the isolated linker over a flat store (see +/// - when the install record beside the store (`.modules.yaml`) does not +/// name it, or there is none and neither does the one in the modules +/// dir that the settings beside the store name (pnpm before 10.12 +/// leaves the store where it is under a `modulesDir`), or the record +/// is not of the isolated linker over a flat store (see /// [`Layout::is_isolated`](crate::formats::pnpm::modules_yaml::Layout::is_isolated): /// `node-linker=hoisted` and `pnp`, whose loaders name store paths /// without a link, `shamefully-hoist`, another layout version); @@ -924,12 +929,13 @@ fn orphaned_pnpm_store_entry_sync( /// `pnpm-lock.yaml` cannot be read or lays its importers out in a way /// pnpm does not write; /// - when a workspace member one of the two lockfiles names is not a -/// directory inside the directory that holds the store's -/// `node_modules`. pnpm links each member's dependencies below the -/// member, so a member outside has links the sweep does not read, and -/// members that are not found there show that this directory is not -/// the workspace's root (a `modulesDir` of more than one level puts the -/// store below it); +/// directory inside the workspace's root. pnpm links each member's +/// dependencies below the member, so a member outside has links the +/// sweep does not read. The root is the directory that holds the +/// store's `node_modules`, or, under a `modulesDir` of more than one +/// level, the nearest directory above it whose `modulesDir` setting +/// names that `node_modules` (pnpm 10.12 and later put the store +/// there); with members found at neither, the root is not known; /// - when a directory below `tree`, the type of one of its children or /// the target of a link cannot be read, or `tree` holds more than /// [`LINK_SWEEP_BUDGET`] directories and links; @@ -964,28 +970,86 @@ fn live_pnpm_store_entries_sync( } let store = std::fs::canonicalize(store_path).ok()?; let nm = store.parent()?; - let project = nm.parent()?; + let beside = nm.parent()?; let scanned = std::fs::canonicalize(scanned).ok()?; - let tree = if project.starts_with(&scanned) { - scanned.as_path() - } else if scanned.starts_with(project) { - // The project above the scanned directory is read like any other - // file a project run looks up above it: not past the checkout. - if !upward_readable(ReadScope::Workspace, &scanned, project) { - return None; + // A directory of the project is read when it lies below the scanned + // directory, or holds it and may be read from there: like any other + // file a project run looks up above the scanned directory, not past + // the checkout, and not at the home directory. + let home = crate::utils::repo_root::home(); + let readable = |dir: &Path| { + dir.starts_with(&scanned) + || (scanned.starts_with(dir) + && (dir == scanned + || (!crate::utils::repo_root::at_or_above_home(dir, home.as_deref()) + && upward_readable(ReadScope::Workspace, &scanned, dir)))) + }; + // The workspace's root, which the lockfiles name their importers + // from: the directory beside `node_modules`, where `pnpm-lock.yaml` + // is. Under a `modulesDir` of more than one level there is none + // there (pnpm 10.12 and later put the store in `/.pnpm`), + // and the root is the nearest directory above whose own settings + // name that `node_modules` as its `modulesDir`. Nothing of a store + // is read before a root that may be read is found. + let beside_readable = readable(beside); + let lock_beside = beside_readable + && std::fs::metadata(beside.join(PNPM_LOCK)).is_ok_and(|lock| lock.is_file()); + let mut project = lock_beside.then_some(beside); + if project.is_none() { + for above in beside.ancestors().skip(1) { + // A level that neither holds the scanned directory nor lies + // below it says nothing: the root may be further up. + if !above.starts_with(&scanned) && !scanned.starts_with(above) { + continue; + } + if !readable(above) { + break; + } + let installs_here = super::pnpm_layout::declared_modules_dir(above) + .and_then(|dir| std::fs::canonicalize(dir).ok()) + .is_some_and(|dir| dir == nm); + if installs_here { + project = Some(above); + break; + } } - project - } else { - return None; + } + let project = match project { + Some(project) => project, + None if beside_readable => beside, + None => return None, + }; + // The install record of this store: the one beside it, which rules + // the store out when it is of another linker or names another store. + // Only where there is none beside it may a `modulesDir` have moved + // the links and the record but not the store (pnpm before 10.12): + // the record is then the one in the modules dir that the settings of + // the directory beside the store name. + let record_names_store = |modules_dir: &Path| -> Option { + let record = match read_regular_to_string_sync(&modules_dir.join(PNPM_MODULES_YAML)) { + Ok(record) => record, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None, + Err(_) => return Some(false), + }; + Some( + Layout::parse(&record) + .filter(Layout::is_isolated) + .and_then(|layout| layout.virtual_store_dir) + .and_then(|dir| std::fs::canonicalize(modules_dir.join(dir)).ok()) + .is_some_and(|recorded| recorded == store), + ) }; - let record = read_regular_to_string_sync(&nm.join(PNPM_MODULES_YAML)).ok()?; - let layout = Layout::parse(&record).filter(Layout::is_isolated)?; - if std::fs::canonicalize(nm.join(layout.virtual_store_dir?)).ok()? != store { + let recorded = record_names_store(nm).unwrap_or_else(|| { + super::pnpm_layout::declared_modules_dir(beside) + .is_some_and(|dir| record_names_store(&dir) == Some(true)) + }); + if !recorded { return None; } let current = read_regular_to_string_sync(&store.join("lock.yaml")) .ok() .filter(|text| is_pnpm_lock_text(text))?; + // Every importer of both lockfiles is a directory inside the root. let wanted = match read_regular_to_string_sync(&project.join(PNPM_LOCK)) { Ok(wanted) => Some(wanted), Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, @@ -1004,6 +1068,18 @@ fn live_pnpm_store_entries_sync( } } } + let tree = if project.starts_with(&scanned) { + scanned.as_path() + } else if scanned.starts_with(project) { + // The project above the scanned directory is read like any other + // file a project run looks up above it: not past the checkout. + if !upward_readable(ReadScope::Workspace, &scanned, project) { + return None; + } + project + } else { + return None; + }; let entries = pnpm_store_entry_names(list_dir_sync(&store))?; let links = sweeps .entry(tree.to_path_buf()) @@ -1017,7 +1093,6 @@ fn live_pnpm_store_entries_sync( // by identity, once (nothing is opened: a target may be a pipe). let store_id = file_id(&store)?; let mut elsewhere: HashSet<&Path> = HashSet::new(); - let home = crate::utils::repo_root::home(); // The directories above the files that links out of `tree` lead to. let mut above_files: HashSet<&Path> = HashSet::new(); for link in links.iter() { @@ -8400,11 +8475,17 @@ mod tests { /// `members` as importers. Returns `node_modules` and its store. fn pnpm_install(root: &Path, members: &[&str]) -> (PathBuf, PathBuf) { let nm = root.join("node_modules"); + let store = pnpm_install_into(&nm, members); + (nm, store) + } + + /// [`pnpm_install`] into the modules dir `nm`. Returns its store. + fn pnpm_install_into(nm: &Path, members: &[&str]) -> PathBuf { let store = nm.join(".pnpm"); std::fs::create_dir_all(&store).unwrap(); std::fs::write(nm.join(".modules.yaml"), PNPM_ISOLATED_RECORD).unwrap(); std::fs::write(store.join("lock.yaml"), pnpm_lock_of(members)).unwrap(); - (nm, store) + store } /// The package dir of `name@version` in the entry `entry` of `store`. @@ -9896,6 +9977,194 @@ mod tests { } } + /// #2353: under a `modulesDir` of more than one level, pnpm 10.12 and + /// later put the store in `/.pnpm` and each member's links + /// in `/` (measured with `sub/node_modules` on + /// 10.12.1, 10.34.9, 11.29.0 and 12.25.1). The lockfile in the store + /// names the members from the workspace's root, which is the directory + /// whose `modulesDir` setting names that `node_modules`, not the one + /// beside it. The store is judged from there: the leftover is left + /// out, and a link in a member's own modules dir keeps it. Without the + /// setting the root is not known, and every entry is kept. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_under_a_nested_modules_dir_is_judged_from_the_root() { + for (settings, text) in [ + ( + "pnpm-workspace.yaml", + "packages:\n - packages/*\nmodulesDir: sub/node_modules\n", + ), + (".npmrc", "modules-dir=sub/node_modules\n"), + ] { + let (_tmp, _, root) = pnpm_project_dir(); + std::fs::write(root.join(settings), text).unwrap(); + let nm = root.join("sub/node_modules"); + let store = pnpm_install_into(&nm, &["packages/a"]); + let stale = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); + let routed = pnpm_entry(&store, ROUTED_ENTRY, "minimist", "1.2.2"); + write_pkg(&root.join("packages/a"), "a", "1.0.0"); + let member_nm = root.join("packages/a/sub/node_modules"); + abs_link(&routed, &member_nm.join("minimist")); + let copies: [&PathBuf; 2] = [&stale, &routed]; + let both = vec![stale.clone(), routed.clone()]; + + assert_eq!( + live_copies(&root, &copies).await, + vec![routed.clone()], + "{settings}" + ); + let link = abs_link(&stale, &member_nm.join("old")); + assert_eq!( + live_copies(&root, &copies).await, + both, + "{settings}: linked" + ); + std::fs::remove_file(link).unwrap(); + + // A member that is not on disk at the root either. + std::fs::write( + store.join("lock.yaml"), + pnpm_lock_of(&["packages/a", "packages/gone"]), + ) + .unwrap(); + assert_eq!( + live_copies(&root, &copies).await, + both, + "{settings}: a member gone" + ); + std::fs::write(store.join("lock.yaml"), pnpm_lock_of(&["packages/a"])).unwrap(); + + // A member that either lockfile names outside the root. The + // lockfile in the store may name the root alone: the one at + // the root is still read. + std::fs::create_dir_all(root.parent().unwrap().join("shared")).unwrap(); + std::fs::write(store.join("lock.yaml"), pnpm_lock_of(&[])).unwrap(); + assert_eq!( + live_copies(&root, &copies).await, + vec![routed.clone()], + "{settings}: the root alone" + ); + std::fs::write(root.join("pnpm-lock.yaml"), pnpm_lock_of(&["../shared"])).unwrap(); + assert_eq!( + live_copies(&root, &copies).await, + both, + "{settings}: a member outside" + ); + std::fs::remove_file(root.join("pnpm-lock.yaml")).unwrap(); + std::fs::write(store.join("lock.yaml"), pnpm_lock_of(&["packages/a"])).unwrap(); + + // The setting in a file above the root says nothing of it. + let text = std::fs::read_to_string(root.join(settings)).unwrap(); + std::fs::remove_file(root.join(settings)).unwrap(); + std::fs::write(root.parent().unwrap().join(settings), &text).unwrap(); + assert_eq!( + live_copies(&root, &copies).await, + both, + "{settings}: set above the root" + ); + std::fs::remove_file(root.parent().unwrap().join(settings)).unwrap(); + + // No setting names the modules dir: the root is not known. + assert_eq!( + live_copies(&root, &copies).await, + both, + "{settings}: no setting" + ); + } + } + + /// #2353: a `modulesDir` of three levels, and a scan that starts in a + /// directory of the workspace that neither holds the store nor lies + /// beside it. The root is still the directory whose setting names the + /// store's `node_modules`, however many levels lie between. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_under_a_deep_modules_dir_is_judged_from_a_member() { + let (_tmp, _, root) = pnpm_project_dir(); + std::fs::write( + root.join("pnpm-workspace.yaml"), + "packages:\n - packages/*\nmodulesDir: a/b/node_modules\n", + ) + .unwrap(); + let store = pnpm_install_into(&root.join("a/b/node_modules"), &["packages/a"]); + let stale = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); + let routed = pnpm_entry(&store, ROUTED_ENTRY, "minimist", "1.2.2"); + write_pkg(&root.join("packages/a"), "a", "1.0.0"); + let member_nm = root.join("packages/a/a/b/node_modules"); + abs_link(&routed, &member_nm.join("minimist")); + let copies: [&PathBuf; 2] = [&stale, &routed]; + + for scanned in [root.clone(), root.join("packages"), root.join("packages/a")] { + assert_eq!( + live_copies(&scanned, &copies).await, + vec![routed.clone()], + "{scanned:?}" + ); + } + abs_link(&stale, &member_nm.join("old")); + assert_eq!( + live_copies(&root.join("packages"), &copies).await, + vec![stale, routed] + ); + } + + /// #2353: before pnpm 10.12 a `modulesDir` moves the links and the + /// install record, and the store stays in `node_modules/.pnpm` + /// (measured with `sub/node_modules` on 9.15.9 and 10.11.1). The record + /// in the modules dir names the store, so the store is judged; a + /// record that names another one, or none, keeps every entry. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_beside_a_modules_dir_that_holds_its_record_is_judged() { + let (_tmp, _, root) = pnpm_project_dir(); + std::fs::write( + root.join("pnpm-workspace.yaml"), + "packages:\n - packages/*\nmodulesDir: sub/node_modules\n", + ) + .unwrap(); + let store = pnpm_install_into(&root.join("node_modules"), &["packages/a"]); + std::fs::remove_file(root.join("node_modules/.modules.yaml")).unwrap(); + let record = |store_dir: &str| { + let record = PNPM_ISOLATED_RECORD.replace( + r#""virtualStoreDir":".pnpm""#, + &format!(r#""virtualStoreDir":"{store_dir}""#), + ); + assert_ne!(record, PNPM_ISOLATED_RECORD); + let modules_dir = root.join("sub/node_modules"); + std::fs::create_dir_all(&modules_dir).unwrap(); + std::fs::write(modules_dir.join(".modules.yaml"), record).unwrap(); + }; + let stale = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); + let routed = pnpm_entry(&store, ROUTED_ENTRY, "minimist", "1.2.2"); + write_pkg(&root.join("packages/a"), "a", "1.0.0"); + let member_nm = root.join("packages/a/sub/node_modules"); + abs_link(&routed, &member_nm.join("minimist")); + abs_link(&routed, &root.join("sub/node_modules/minimist")); + let copies: [&PathBuf; 2] = [&stale, &routed]; + let both = vec![stale.clone(), routed.clone()]; + + // No record anywhere yet. + assert_eq!(live_copies(&root, &copies).await, both); + record("../../node_modules/.pnpm"); + assert_eq!(live_copies(&root, &copies).await, vec![routed.clone()]); + let link = abs_link(&stale, &member_nm.join("old")); + assert_eq!(live_copies(&root, &copies).await, both); + std::fs::remove_file(link).unwrap(); + record("../../elsewhere/.pnpm"); + assert_eq!(live_copies(&root, &copies).await, both); + + // A record beside the store decides, whatever an older one in the + // modules dir says: one of another linker rules the store out. + record("../../node_modules/.pnpm"); + assert_eq!(live_copies(&root, &copies).await, vec![routed.clone()]); + std::fs::write( + root.join("node_modules/.modules.yaml"), + PNPM_ISOLATED_RECORD.replace(r#""nodeLinker":"isolated""#, r#""nodeLinker":"pnp""#), + ) + .unwrap(); + assert_eq!(live_copies(&root, &copies).await, both); + } + /// #2353: a `node_modules` that is a link to another checkout's (a git /// worktree that shares the main checkout's install) belongs to a /// project elsewhere. Its store is in neither the scanned worktree nor diff --git a/crates/socket-patch-core/src/crawlers/pnpm_layout.rs b/crates/socket-patch-core/src/crawlers/pnpm_layout.rs index 5e69ddebe..245841d65 100644 --- a/crates/socket-patch-core/src/crawlers/pnpm_layout.rs +++ b/crates/socket-patch-core/src/crawlers/pnpm_layout.rs @@ -50,6 +50,21 @@ pub(crate) fn configured_modules_dirs(project: &Path) -> Vec { dirs } +/// The modules dir that the settings files of `project` itself name +/// (`modulesDir:` in its `pnpm-workspace.yaml`, else `modules-dir` in its +/// `.npmrc`), resolved against it like pnpm does and honored only +/// strictly inside it. Unlike [`configured_modules_dirs`], no directory +/// above `project` is read and no child is listed: `None` when the +/// project's own files do not say. +pub(crate) fn declared_modules_dir(project: &Path) -> Option { + let read = |name: &str| crate::utils::fs::read_regular_to_string_sync(&project.join(name)).ok(); + let raw = setting_from( + read("pnpm-workspace.yaml").as_deref(), + read(".npmrc").as_deref(), + )?; + Some(project.join(super::npm_crawler::resolve_modules_folder(&[], &raw)?)) +} + /// Whether the project holds an installed pnpm store: a [`MODULES_YAML`] /// record or a `.pnpm` virtual store in `node_modules` or in one of its /// [`configured_modules_dirs`]. The configured dirs are read only when diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1a83dce0b..b74e0ef43 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -935,10 +935,11 @@ judged, as before: inside it: a `--global` run, or a `node_modules` that is a link to another checkout's (a git worktree that shares an install); - when the project that holds the store lies above the git checkout the - run started in: a project run reads no project file outside its - checkout; -- when the install record (`node_modules/.modules.yaml`) is missing or - unreadable, or records `node-linker=hoisted` or `pnp`, `shamefully-hoist` + run started in, or above the scanned directory at or above the home + directory: a project run reads no project file outside its checkout, + nor the home directory or above when the run started below it; +- when the install record (`.modules.yaml`) is missing or unreadable, or + records `node-linker=hoisted` or `pnp`, `shamefully-hoist` (a `publicHoistPattern` of `*`), a store layout other than the one pnpm 6 to 12 write, or another virtual store (`virtualStoreDir`); - when the lockfile pnpm writes in the store @@ -947,14 +948,17 @@ judged, as before: importers the way pnpm writes them (a merge conflict left in the file, for one); - when an importer that either lockfile names is not a directory inside - the project that holds the store: one outside it (`../shared`, an - absolute path, a link that leads out), one that is not on disk (a - checkout of part of a workspace), or a file. pnpm links each importer's - dependencies below the importer, so such links would not be read. A - `modulesDir` of more than one level falls under this too: pnpm 10.12 - and later put the store in `/.pnpm` and each member's links - in `/`, so no member is below the directory that - holds the store; + the workspace's root: one outside it (`../shared`, an absolute path, a + link that leads out), one that is not on disk (a checkout of part of a + workspace), or a file. pnpm links each importer's dependencies below + the importer, so such links would not be read. The root is the + directory that holds the store's `node_modules`. Under a `modulesDir` + of more than one level it is the nearest directory above that one + whose `modulesDir` setting (`pnpm-workspace.yaml`, or `modules-dir` in + `.npmrc`) names the store's `node_modules`: pnpm 10.12 and later put + the store in `/.pnpm` and each member's links in + `/`. Where the setting comes from somewhere the + project's files do not show, the root is not known; - when a directory below the one that is read, the type of one of its children or the target of a link cannot be read, or it holds more than 500,000 directories and links. A link that leads nowhere is left out: diff --git a/docs/testing/pnpm-compatibility.md b/docs/testing/pnpm-compatibility.md index e053b5133..f95d17c0c 100644 --- a/docs/testing/pnpm-compatibility.md +++ b/docs/testing/pnpm-compatibility.md @@ -403,13 +403,16 @@ one. `pnpm prune` removes the entry at once (measured on 11.29.0 and 12.25.1, on the registry route), and a clean `node_modules` has no such entry. -One such layout is a workspace with a `modulesDir` of more than one level. -Measured with `modulesDir: sub/node_modules`: pnpm 10.12.1, 10.34.9, 11.29.0 -and 12.25.1 put the virtual store in `sub/node_modules/.pnpm` and each -member's links in `/sub/node_modules`; pnpm 9.15.9 and 10.11.1 put -the links and the install record there too, but keep the virtual store in -`node_modules/.pnpm`. Either way every entry is judged, so the upstream -entry refuses the patch until it is gone. +A workspace with a `modulesDir` of more than one level is judged from the +workspace's root. Measured with `modulesDir: sub/node_modules`: pnpm 10.12.1, +10.34.9, 11.29.0 and 12.25.1 put the virtual store in +`sub/node_modules/.pnpm` and each member's links in +`/sub/node_modules`; pnpm 9.15.9 and 10.11.1 put the links and the +install record there too, but keep the virtual store in `node_modules/.pnpm`. +The lockfile in the store names the members from the root either way, and +the root is found through the `modulesDir` setting of `pnpm-workspace.yaml` +or `.npmrc`; the record of the older layout is read from the modules dir and +has to name the store. The registry-route legs above and the vendored capstone (`e2e_vendor_pnpm_build`, on each pnpm of its matrix from 9 up) run that @@ -422,8 +425,9 @@ hoisted and is also the peer dependency of a tarball package `*_in_place_install_under_a_nested_modules_dir`; not on Windows): `vex` attests both patches; a link to the upstream entry from `vendor/`, `dist/`, a hidden directory or a package's own `node_modules` refuses the patch -until the link is gone; and under the nested `modulesDir` the patches stay -refused. Where `vex` attests, a second reading of the links +until the link is gone; and under the nested `modulesDir` both patches are +attested as well, until a link in a member's own modules dir reaches the +upstream entry. Where `vex` attests, a second reading of the links (`tests/common/pnpm_links.rs`, which shares no code with the CLI) checks that no path from outside the store's entries leads into an entry that holds the upstream bytes, and where a link was added it must find that