diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 10b3aecec..4dc1d332a 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -357,6 +357,8 @@ The route is taken only when **all** of these hold; otherwise the run takes the **pnpm per-branch locks (#556)**: with `gitBranchLockfile` on (a top-level `gitBranchLockfile: true` in the root `pnpm-workspace.yaml`; when the YAML leaves the key unset, `git-branch-lockfile=true` in the root `.npmrc`, as pnpm 10 and older read it; on disk also `pnpm_config_git_branch_lockfile` (pnpm 11 and newer) or `npm_config_git_branch_lockfile` (pnpm 10 and older; either when the major is unknown, read as for the `lockfile` setting above) set to `true`; a workspace member with no `pnpm-workspace.yaml` of its own reads the governing ancestor's file and the `.npmrc` beside it), pnpm installs a git branch from its own `pnpm-lock..yaml` whenever that lock exists, in every directory it installs a lock from: the root, and under `sharedWorkspaceLockfile: false` each member's (#492). When the setting is on AND at least one such `pnpm-lock..yaml` exists (at the root, or in a member that installs from its own lock), hosted mode leaves every root pnpm lock (`pnpm-lock.yaml`, `shrinkwrap.yaml`) and `pnpm-workspace.yaml` untouched (every member lock too), confirms no npm pin from them and warns `redirect_pnpm_git_branch_lockfile` (in place of `redirect_pnpm_no_lockfile` when the branch lock is the only one); the detail names the setting and the branch lock(s), and the remedy is to turn `gitBranchLockfile` off and fold the branch locks into `pnpm-lock.yaml` with `pnpm install --merge-git-branch-lockfiles`, then re-run. A vendored→hosted takeover of a pnpm-vendored purl is refused with the same code (the vendored wiring and ledger stay byte-for-byte). Vendored mode refuses the same projects with `vendor_pnpm_git_branch_lockfile`, before any write and in the pre-flight. The setting with no branch lock (main, or a branch whose dependencies never changed) installs from `pnpm-lock.yaml`, which both modes wire as usual; a stray branch lock with the setting off is ignored. The in-memory engine fetches root `pnpm-lock.*.yaml` names presence-only and refuses the same way. `vex` omits every pin of those pnpm locks (`vex_pnpm_git_branch_lockfile`) whenever such a branch lock exists, whatever the setting says (fail-closed; read from the project's files only, not the environment); see **Unattested references**. +**pnpm: a hosted package over a local dependency (#2263)**: pnpm 12.23 and newer refuse a lock in which a package that is not local depends on a local file unless they can tie the workspace override to that package, and they cannot for a package a hosted patch pins (the tarball of its pin, or of the named registry of the registry route): every install then fails with `ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED`, frozen or not. A vendored patch is a `file:` tarball its dependents are pointed at, so for 9.0 locks neither mode creates the pair, whatever pnpm the project pins. Hosted mode refuses a pin that would make a hosted package of one whose `snapshots:` entry (any peer context) has a `file:` dependency: `redirect_pnpm_local_dependency`, one warning per lock that has the dependency, nothing rewritten in any lock and the patch not confirmed. A package an earlier hosted patch already pins is re-pinned as before, and a `link:` dependency (a peer a workspace project satisfies) refuses nothing. Vendored mode refuses to vendor a package (`vendor_lock_entry_unsupported`, before anything is staged and in the pre-flight; Rush locks included) when a registry-keyed dependent of it resolves to a hosted patch's tarball. A dependent that is local itself (a vendored one among them), on the default registry, or on any other tarball URL (`lockfileIncludeTarballUrl`) is not in the way. A hosted → vendored takeover in `scan` / `get --mode vendored` judges each pin against the lock as the run found it, so a hosted dependency of a hosted package stays hosted in the run that vendors the package and is vendored by the next run (the first run exits 1); two hosted packages that depend on each other are refused on every such run. A plain `vendor` eject restores every pin first and vendors them in one run. The remedy for either refusal is one mode for the package and its dependency. + `redirect_pnpm_no_lockfile` names pnpm when installer markers exist without a lock; `redirect_pnpm_entry_vendored` identifies a vendored entry instead of reporting it missing. Supported `shrinkwrap.yaml` files are writable lockfiles, not read-only markers, when no `pnpm-lock.yaml` sits beside them. pnpm >= 3 never reads a `shrinkwrap.yaml` it has a `pnpm-lock.yaml` for, so that one is shadowed (unless the project pins pnpm 1 or 2 in `node_modules/.modules.yaml` or package.json's `packageManager`: those read only `shrinkwrap.yaml`, so there the stray `pnpm-lock.yaml` is the shadowed one): hosted mode never rewrites it and leaves it out of the all-or-nothing gate, so an entry it cannot repoint (or pnpm 1's early shrinkwrap head) refuses nothing, and `vex` only sweeps it for stale Socket identities. Vendored mode never writes it either, and refuses a project that pins pnpm 1 or 2 beside a `shrinkwrap.yaml` (`vendor_lockfile_version_unsupported`: it does not write the shrinkwrap grammar, and the stray `pnpm-lock.yaml` would patch nothing pnpm installs). **vlt hosted-mode contract**: `scan` / `get --mode hosted` rewrite, in `vlt-lock.json`, every default-registry node of a granted `name@version` (the `''` / `npm` segment or a URL segment equal to the lock's scalar `registry`, both DepID grammars, every peer and modifier variant): slot [2] becomes the granted sha512 and slot [3] the hosted URL (appended to a 3-tuple); the DepID, flags and trailing slots, the line ending and every other byte stay. `options` is never edited and `vlt.json` is only read. A lock with another `lockfileVersion` (decided on the raw JSON token), a BOM, a non-object body or a `nodes` section outside vlt's one-node-per-line layout refuses the whole lock (`redirect_vlt_lock_unsupported`). **Confirmation**: vlt drives when its install state (`node_modules/.vlt-lock.json` or `node_modules/.vlt/`) is present or no other npm-family lock is; then only `vlt-lock.json` confirms a uuid. Otherwise every lock is rewritten, `redirect_vlt_sibling_lockfiles` warns, and the other locks' rules confirm, including a dep `vlt-lock.json` merely does not wire (`redirect_vlt_entry_not_found`, `redirect_vlt_entry_vendored`, or `redirect_vlt_custom_registry_skipped` alone). Whichever lock drives, a dep the vlt rewriter refuses (`redirect_vlt_missing_sha512`, `redirect_vlt_unsupported_lock_key`) is never confirmed by any lock, although a sibling lock may already carry its rewritten URL. **Artifacts**: the scan never downloads the hosted artifacts; the patch server sends them unencoded (`Cache-Control: no-transform`), and vlt verifies slot [2] against the bytes it receives at install time. **Heal**: an installed copy is stale when vlt's hidden lock (`node_modules/.vlt-lock.json`) does not record its DepID at the integrity the lock pins, and cannot be checked without a readable hidden lock; stale installed copies of Socket-owned nodes are removed so the next `vlt install` extracts the patched bytes, and `rollback` / `remove` do the same for the registry bytes (`--no-vlt-install-cleanup` keeps them; optional dependencies' copies are always kept); `redirect_vlt_reinstall_required` says what happened and what to run. The same-run `--vex` never attests a vlt package whose installed copy is stale or unchecked, whose lock a vlt release may ignore (`redirect_vlt_lockfile_version_missing`, `redirect_vlt_old_lockfile_ignored`, `redirect_vlt_scalar_registry_ignored`), or which also resolves from a non-default registry (`redirect_vlt_custom_registry_skipped`). `vlt.json` or vlt install state without `vlt-lock.json` warns `redirect_vlt_no_lockfile` instead of `redirect_npm_no_lockfile`. `rollback` / `remove` restore each hosted node's slots [2] and [3] from the version document of the registry the node resolves against (slot [3] is its `dist.tarball`, as vlt writes it; `upstream_registry_fallback` when that registry can't be read), following the lock's own slot-[3] convention (see "Hosted unwind coverage"). Tested releases: `docs/testing/vlt-compatibility.md`. @@ -2474,6 +2476,7 @@ command's integration tests check its output. | `hosted_restore_refused` / `hosted_write_failed` | `failed` (`details.mode: "hosted"`) | rollback (v5.0): a hosted pin's upstream restore was refused (detail names the `git checkout` remedy), or writing the restored lockfiles failed (artifact-level, no `purl`; on `--dry-run`: would fail). That write is all or nothing, so no pin of the run is `rolledBack` / `verified` beside it; the detail ends `nothing was written` / `nothing was changed`, or names each file that could not be put back (see "Hosted unwind coverage"). Exit 1. | | `gc_skipped` | rollback `warnings[]` | rollback (v5.0): the artifact GC could not run (a before-blob gate abort, an unreadable vendor ledger); `gc` is absent. Not raised under `--preserve-state`, which never asks for one. | | `registry_entry_unused` | `removed` (`verified` on dry-run; artifact-level, no `purl`) | repair, scan (and `get --mode hosted`, which runs the same rewrite): an entry of hosted mode's pnpm registry route that no lockfile uses any more was taken out of pnpm-workspace.yaml or a pnpm lock (`details: {mode: "hosted", file, entry, key, value?}`; `entry` is `registry`, `override`, `lockOverride` or `lockKey`). A registry's address is never in the event. Bumps no `summary` counter; counted in `gc.removedRegistryEntries` where the run reports a `gc`. See "pnpm registry route", *Cleanup*. | +| `redirect_pnpm_local_dependency` | `warnings[]` (warning, one per lock) | scan/get `--mode hosted` (pnpm, 9.0 locks): the pin would make a hosted package of one whose `snapshots:` entry depends on a local `file:` package (a vendored one among them). pnpm 12.23 and newer refuse that lock on every install (`ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED`), so nothing is rewritten in any lock and the patch is `skipped` / `redirect_unconfirmed`. The detail names the lock and the dependency; patch both in one mode (`scan --mode hosted` takes a vendored dependency over). See "pnpm: a hosted package over a local dependency". | | `redirect_pnpm_registry_held` | `warnings[]` (warning) | scan/get `--mode hosted` (pnpm): a release the project routes through its patch's registry has a newer patch, and this run does not update pnpm-workspace.yaml (`--no-trust-lockfile-config`, an unreadable file, a lock that could not be converted back). The newer patch's tarball under the old patch's registry would not install, so the lock entry is left on the patch it is routed to and the newer patch is `skipped` / `redirect_unconfirmed`. The detail names the releases and, under the opt-out, says to re-run without the flag. See "pnpm registry route", *Cleanup*. | | `registry_cleanup_unknown_host` | repair + scan run-level `warnings[]` | repair, `scan --prune`, a hosted scan that crawled no package: pnpm-workspace.yaml declares registries in the shape of a patch's registry (`socket-` at a patch's directory with matching digits) on a host this run was not given as a patch server. They were left alone, as a registry of the project's own is, so nothing of them was tidied. One warning per host; the detail gives the count, the host's origin (never the address) and `--patch-server-url ` / `SOCKET_PATCH_SERVER_URL` as what lets the command tidy them. The run continues and exits 0. See "pnpm registry route", *Cleanup* (Limits). | | `registry_cleanup_skipped` / `registry_cleanup_failed` | repair + scan run-level `warnings[]` | repair, `scan --prune`, a hosted scan that crawled no package: the cleanup of unused pnpm registry entries could not read the pnpm locks or pnpm-workspace.yaml to tell what still uses the route (`…_skipped`; nothing was removed), or could not write the cleaned files (`…_failed`; they are as they were, or the detail names each one that is not). `…_failed` is also what a hosted scan reports when it could not delete a pnpm-workspace.yaml a run created and it has emptied (the file is left holding its `packages:` list; the detail says to delete it). The run continues and exits 0. | 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 fa651a5d0..c1bcc90de 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs @@ -2055,6 +2055,209 @@ async fn pnpm11_registry_route_survives_resolution_and_cleans_up() { registry_route_survives_resolution_and_cleans_up(PNPM_TERTIARY, "pnpm11-route").await; } +/// A HOSTED PATCH OVER A VENDORED DEPENDENCY against a real pnpm (#2263). +/// +/// `peer-user` depends on `leaf`. pnpm 12.23 refuses a lock in which a +/// package fetched from a hosted patch depends on a vendored `file:` +/// tarball (`ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED`), frozen or not, and it +/// writes that very lock itself for the workspace file the two modes +/// leave together. So whichever of `get --mode hosted` and +/// `get --mode vendored` runs second: +/// +/// * is refused with a code that says why, and changes not a byte of +/// package.json, the lock or the workspace file; +/// * leaves a project a fresh checkout installs frozen from an empty +/// store, with the first patch's bytes; +/// * and `scan --mode hosted`, the remedy both refusals name, then patches +/// both packages in a project that still installs frozen; +/// * which a `scan --mode vendored` over it leaves as it is, since it can +/// vendor `leaf` but not `peer-user`. +async fn hosted_patch_over_a_vendored_dependency(pm: &str, tag: &str, hosted_first: bool) { + if !has_corepack_pm(pm) { + println!("SKIP {tag}: `corepack {pm}` unavailable"); + return; + } + let registry = MockServer::start().await; + mount_route_registry(®istry).await; + let server = MockServer::start().await; + mount_route_patch_server(&server).await; + + let tmp = tempfile::tempdir().unwrap(); + let cache = tmp.path().join("pnpm-cache"); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("package.json"), + r#"{"name":"app","version":"1.0.0","private":true,"dependencies":{"host":"1.0.0","peer-user":"1.0.0"}}"#, + ) + .unwrap(); + std::fs::write( + proj.join(".npmrc"), + format!("registry={}/\n", registry.uri()), + ) + .unwrap(); + let store = |label: &str| format!("--store-dir={}", tmp.path().join(label).display()); + let chatter = |out: &Output| { + format!( + "stdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ) + }; + let install = route_pnpm(&cache, &proj, pm, &["install", &store("store-fixture")]); + if !install.status.success() { + assert!( + !pnpm_required(), + "fixture install failed:\n{}", + chatter(&install) + ); + println!("SKIP {tag}: fixture install failed:\n{}", chatter(&install)); + return; + } + + let env = vec![ + ("SOCKET_PATCH_SERVER_URL".to_string(), server.uri()), + ("SOCKET_NPM_REGISTRY".to_string(), registry.uri()), + ]; + let server_uri = server.uri(); + let socket = |args: &[&str]| { + let mut args = args.to_vec(); + args.extend_from_slice(&[ + "--json", + "--yes", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + &server_uri, + "--org", + ORG, + "--api-token", + "fake", + ]); + run_socket_env(&proj, &args, &env) + }; + const FILES: [&str; 3] = ["package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"]; + let committed = || FILES.map(|file| std::fs::read(proj.join(file)).ok()); + // A fresh checkout of what is committed, installed frozen from an + // empty store; `patched` are the packages whose bytes must be the + // patch's. + let frozen_install = |label: &str, patched: &[&str]| { + let fresh = tmp.path().join(format!("fresh-{label}")); + std::fs::create_dir_all(&fresh).unwrap(); + for file in FILES.into_iter().chain([".npmrc"]) { + if proj.join(file).exists() { + std::fs::copy(proj.join(file), fresh.join(file)).unwrap(); + } + } + if proj.join(".socket").exists() { + fs_tree::copy_tree(&proj.join(".socket"), &fresh.join(".socket")); + } + let out = route_pnpm( + &cache, + &fresh, + pm, + &[ + "install", + "--frozen-lockfile", + &store(&format!("store-{label}")), + ], + ); + assert!( + out.status.success(), + "{tag} {label}: the frozen install must accept what is committed.\n{}", + chatter(&out) + ); + for name in ["peer-user", "leaf"] { + let index = installed_index(&fresh, "peer-user", name); + assert_eq!( + index.starts_with(MARKER), + patched.contains(&name), + "{tag} {label}: {name} installed as:\n{index}" + ); + } + }; + + let [leaf, peer_user] = &ROUTE_PATCHES; + let (first, first_mode, second, second_mode, refusal) = if hosted_first { + ( + peer_user, + "hosted", + leaf, + "vendored", + "vendor_lock_entry_unsupported", + ) + } else { + ( + leaf, + "vendored", + peer_user, + "hosted", + "redirect_pnpm_local_dependency", + ) + }; + let (code, stdout, stderr) = socket(&["get", first.uuid, "--mode", first_mode]); + assert_eq!( + code, 0, + "{tag}: get {} --mode {first_mode} failed.\nstdout:\n{stdout}\nstderr:\n{stderr}", + first.name + ); + let after_first = committed(); + + let (code, stdout, stderr) = socket(&["get", second.uuid, "--mode", second_mode]); + assert!( + stdout.contains(refusal) && stdout.contains("ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED"), + "{tag}: get {} --mode {second_mode} must be refused as {refusal} (exit {code}).\n\ + stdout:\n{stdout}\nstderr:\n{stderr}", + second.name + ); + assert!( + committed() == after_first, + "{tag}: the refused get {} --mode {second_mode} must change nothing; the lock is now:\n{}", + second.name, + std::fs::read_to_string(proj.join("pnpm-lock.yaml")).unwrap() + ); + frozen_install("refused", &[first.name]); + + // The remedy: both patches in hosted mode. + let (code, stdout, stderr) = socket(&["scan", "--mode", "hosted"]); + assert_eq!( + code, 0, + "{tag}: the hosted scan failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + frozen_install("both-hosted", &["peer-user", "leaf"]); + + // A takeover that cannot vendor `peer-user` (its snapshot key carries a + // peer context) does not vendor `leaf` under it either: both stay + // hosted. + let both_hosted = committed(); + let (code, stdout, stderr) = socket(&["scan", "--mode", "vendored"]); + assert_eq!( + code, 1, + "{tag}: the vendored scan must fail.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert!( + committed() == both_hosted, + "{tag}: the refused takeover must change nothing; the lock is now:\n{}", + std::fs::read_to_string(proj.join("pnpm-lock.yaml")).unwrap() + ); + frozen_install("takeover-refused", &["peer-user", "leaf"]); +} + +#[tokio::test(flavor = "multi_thread")] +#[serial_test::serial] +#[ignore = "wall-bound real-pnpm installs (~30s); runs on all 3 OSes as an e2e CI matrix leg"] +async fn pnpm12_vendored_dependency_of_a_hosted_patch_is_refused() { + hosted_patch_over_a_vendored_dependency(PNPM_NAMED_REGISTRY, "pnpm12-hosted-first", true).await; +} + +#[tokio::test(flavor = "multi_thread")] +#[serial_test::serial] +#[ignore = "wall-bound real-pnpm installs (~30s); runs on all 3 OSes as an e2e CI matrix leg"] +async fn pnpm12_hosted_patch_over_a_vendored_dependency_is_refused() { + hosted_patch_over_a_vendored_dependency(PNPM_NAMED_REGISTRY, "pnpm12-vendored-first", false) + .await; +} + /// CLEANUP OF THE REGISTRY ROUTE against a real pnpm: once a hosted patch /// is no longer needed, `scan` and `repair` take every unused entry of the /// route out, and what they leave is a project pnpm installs frozen. diff --git a/crates/socket-patch-cli/tests/in_process_vendor_pnpm_parent_child.rs b/crates/socket-patch-cli/tests/in_process_vendor_pnpm_parent_child.rs index 6f7f3de17..ccf28e40f 100644 --- a/crates/socket-patch-cli/tests/in_process_vendor_pnpm_parent_child.rs +++ b/crates/socket-patch-cli/tests/in_process_vendor_pnpm_parent_child.rs @@ -456,6 +456,166 @@ async fn hosted_takeover_migrates_parent_and_child() { assert!(vendored_uuids(root).is_empty()); } +/// The npm registry's version documents the upstream restore re-resolves +/// the pristine entries from, on the API's mock server. +async fn mock_registry(server: &MockServer) { + for purl in [DEBUG, MS] { + let (name, version, _) = parts(purl); + let integrity = LOCK + .split(&format!( + " {name}@{version}:\n resolution: {{integrity: " + )) + .nth(1) + .and_then(|rest| rest.split('}').next()) + .expect("the fixture lock's integrity"); + Mock::given(method("GET")) + .and(path(format!("/{name}/{version}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "name": name, + "version": version, + "dist": { + "tarball": format!("https://registry.npmjs.org/{name}/-/{name}-{version}.tgz"), + "integrity": integrity, + } + }))) + .mount(server) + .await; + } +} + +/// Run `args` against the mock API, which is the npm registry too; a +/// vendoring run downloads from a prebuilt fixture of the project's +/// manifest. +fn run_api(root: &Path, api: &str, args: &[&str]) -> (i32, Value) { + let mut args = args.to_vec(); + args.extend([ + "--json", + "--yes", + "--api-url", + api, + "--api-token", + "fake", + "--org", + ORG, + "--cwd", + root.to_str().unwrap(), + ]); + let vendoring = args[0] == "vendor" || args.contains(&"vendored"); + let fixture = vendoring.then(|| prebuilt_common::Server::project_with_env(root, &[])); + if let Some(fixture) = &fixture { + args.extend(["--vendor-url", &fixture.uri]); + } + let mut cmd = hermetic::binary_command(); + cmd.current_dir(root) + .env("SOCKET_TELEMETRY_DISABLED", "1") + .env("SOCKET_NPM_REGISTRY", api) + .args(&args); + let out = cmd.output().expect("spawn socket-patch binary"); + let stdout = String::from_utf8_lossy(&out.stdout); + let env: Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| { + let stderr = String::from_utf8_lossy(&out.stderr); + panic!("{args:?} must emit a JSON envelope: {e}\nstdout:\n{stdout}\nstderr:\n{stderr}") + }); + (out.status.code().unwrap_or(-1), env) +} + +/// The project with both packages pinned in hosted mode. +fn hosted_project(root: &Path, api: &str) { + write_project(root); + let (code, env) = run_api(root, api, &["scan", "--mode", "hosted"]); + assert_eq!(code, 0, "{env:#}"); + let lock = read_lock(root); + for purl in [DEBUG, MS] { + assert!(lock.contains(&hosted_url(purl)), "{purl} pinned:\n{lock}"); + } +} + +fn vendored_key(purl: &str) -> String { + let (name, version, uuid) = parts(purl); + format!(" {name}@file:.socket/vendor/npm/{uuid}/{name}-{version}.tgz:") +} + +/// #2263: pnpm 12.23 refuses a lock in which a package fetched from a +/// tarball URL depends on a local file, so `ms` is not vendored under a +/// `debug` that is still hosted. `scan --mode vendored` judges each hosted +/// pin against the lock as the run found it: the first run vendors `debug` +/// and keeps `ms` hosted (a vendored package over a hosted one installs), +/// and the next run vendors `ms`. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_takeover_keeps_the_child_hosted_until_the_parent_is_vendored() { + let server = MockServer::start().await; + mock_api(&server).await; + mock_registry(&server).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + hosted_project(root, &server.uri()); + + let (code, env) = run_api(root, &server.uri(), &["scan", "--mode", "vendored"]); + assert_eq!(code, 1, "{env:#}"); + let refused: Vec<&Value> = env["events"] + .as_array() + .unwrap() + .iter() + .filter(|e| e["action"] == "failed") + .collect(); + let [refusal] = refused.as_slice() else { + panic!("one refusal: {env:#}"); + }; + assert_eq!(refusal["purl"], MS, "{env:#}"); + assert_eq!(refusal["errorCode"], "vendor_lock_entry_unsupported"); + let detail = refusal["error"].as_str().unwrap(); + assert!( + detail.contains("installs debug@4.3.4 from a hosted patch") + && detail.contains("ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED"), + "{detail}" + ); + let lock = read_lock(root); + assert!( + lock.contains(&vendored_key(DEBUG)), + "debug vendored:\n{lock}" + ); + assert!(lock.contains(&hosted_url(MS)), "ms stays hosted:\n{lock}"); + assert!(!lock.contains(&hosted_url(DEBUG)), "{lock}"); + assert_eq!(vendored_uuids(root), [DEBUG_UUID]); + assert_snapshot_refs_resolve(&lock); + + let (code, env) = run_api(root, &server.uri(), &["scan", "--mode", "vendored"]); + assert_eq!(code, 0, "{env:#}"); + let lock = read_lock(root); + for purl in [DEBUG, MS] { + assert!( + lock.contains(&vendored_key(purl)), + "{purl} vendored:\n{lock}" + ); + assert!(!lock.contains(&hosted_url(purl)), "{lock}"); + } + assert_snapshot_refs_resolve(&lock); +} + +/// The eject (`vendor` over hosted pins) restores every pin before it +/// vendors any, so it moves the parent and its dependency in one run. +#[tokio::test(flavor = "multi_thread")] +async fn eject_vendors_a_hosted_parent_and_child_in_one_run() { + let server = MockServer::start().await; + mock_api(&server).await; + mock_registry(&server).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + hosted_project(root, &server.uri()); + + let (code, env) = run_api(root, &server.uri(), &["vendor"]); + assert_eq!(code, 0, "{env:#}"); + let lock = read_lock(root); + for purl in [DEBUG, MS] { + assert!( + lock.contains(&vendored_key(purl)), + "{purl} vendored:\n{lock}" + ); + assert!(!lock.contains(&hosted_url(purl)), "{lock}"); + } + assert_snapshot_refs_resolve(&lock); +} + /// How many hosted pins the run wrote (`applied`) or, on a dry run, would /// write (`verified`): the `details.mode: "hosted"` events (v5.0's /// `redirect.redirected`). diff --git a/crates/socket-patch-core/src/formats/pnpm/hosted.rs b/crates/socket-patch-core/src/formats/pnpm/hosted.rs index c71430fef..9490588c7 100644 --- a/crates/socket-patch-core/src/formats/pnpm/hosted.rs +++ b/crates/socket-patch-core/src/formats/pnpm/hosted.rs @@ -11,6 +11,7 @@ use serde_json::Value; use crate::patch::redirect::{full_name, DepOverride, FileEdit, RewriteResult, RewriteWarning}; use super::grammar as pnpm; +use super::lines::{parse_key_line, unquote_value}; use super::plan::{hosted_refuses_lock, match_hosted_key, planned_locks, KeyMatch, Target}; /// Whether `entry` resolves to exactly `artifact_url` — the per-instance @@ -19,6 +20,36 @@ fn pnpm_resolves_to(entry: &pnpm::Entry<'_>, artifact_url: &str) -> bool { pnpm::resolution(entry).is_some_and(|r| r.tarball() == Some(artifact_url)) } +/// The first dependency of `fname@version` that a `snapshots:` section of +/// `text` (lockfileVersion 9) installs from a local `file:` path, as +/// `dep: value`. A registry package only gets one from an override, a +/// vendored package's among them. A `link:` value is not one: pnpm writes +/// it for a peer a workspace project satisfies. +fn local_dependency(text: &str, fname: &str, version: &str) -> Option { + let mut in_snapshots = false; + let mut in_entry = false; + for line in text.lines() { + if !line.is_empty() && !line.starts_with([' ', '#']) { + in_snapshots = line == "snapshots:"; + continue; + } + if !in_snapshots { + continue; + } + if let Some((key, _, _)) = parse_key_line(line, 2) { + in_entry = pnpm::hosted_suffix(key, fname, version).is_some(); + } else if in_entry { + if let Some((dep, _, value)) = parse_key_line(line, 6) { + let value = unquote_value(value); + if value.starts_with("file:") { + return Some(format!("{dep}: {value}")); + } + } + } + } + None +} + /// One pnpm lock under rewrite. `text` is the lock as of the last /// materialization; `pending` holds the resolution splices committed since, /// in `text`'s byte coordinates, and `spliced` the entries they touch. @@ -237,6 +268,9 @@ pub(crate) fn plan_hosted( type Splice = (usize, std::ops::Range, String); let mut planned: Vec<(usize, Vec, Vec)> = Vec::new(); let mut residuals: Vec<(&str, Vec)> = Vec::new(); + // The locks in which the pin would leave a hosted package + // depending on a local file, with that dependency. + let mut local_dependencies: Vec<(&str, String)> = Vec::new(); for (idx, (lock, hits)) in locks.iter().zip(&hits).enumerate() { // (entry, byte range to replace, replacement text) per instance, // plus one FileEdit per instance keyed by the canonical instance @@ -253,6 +287,11 @@ pub(crate) fn plan_hosted( // instance keep installing the unpatched upstream tarball, so // the dep is refused instead. let mut leftover: Vec = Vec::new(); + // Whether a splice makes a hosted pin of an instance that is + // not one yet: one whose tarball already names a patch (a uuid + // segment, which no registry tarball has) is re-pinned as it + // was. + let mut newly_hosted = false; for &i in hits { let entry = lock.entry(i); let suffix = pnpm::hosted_suffix(entry.key, &fname, &dep.version) @@ -289,6 +328,11 @@ pub(crate) fn plan_hosted( if rebuilt == original { continue; } + newly_hosted |= !resolution.tarball().is_some_and(|tarball| { + tarball + .split('/') + .any(crate::patch::path_safety::is_canonical_uuid) + }); instance_edits.push(FileEdit { path: lock.path.clone(), kind: "redirect_pnpm_resolution".into(), @@ -303,6 +347,11 @@ pub(crate) fn plan_hosted( residuals.push((lock.path.as_str(), leftover)); continue; } + if newly_hosted { + if let Some(local) = local_dependency(&lock.text, &fname, &dep.version) { + local_dependencies.push((lock.path.as_str(), local)); + } + } if !splices.is_empty() { planned.push((idx, splices, instance_edits)); } @@ -329,6 +378,34 @@ pub(crate) fn plan_hosted( } continue; } + // pnpm 12.23 refuses a lock in which a package that is not local + // depends on a local file, unless it can tie the workspace override + // to that package (ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED). It cannot + // for a package fetched from a hosted patch, which the pin makes + // of this one, so every install would fail, frozen or not (#2263, + // verified against pnpm 12.23.0). The dep is refused across the + // whole lock set, as for a residual; the vendored backend refuses + // the same pair from its side (`vendor::pnpm_lock`). + if !local_dependencies.is_empty() { + result.refused_pnpm_uuids.insert(dep.patch_uuid.clone()); + for (lock_key, local) in &local_dependencies { + result.warnings.push(RewriteWarning { + code: "redirect_pnpm_local_dependency".into(), + detail: format!( + "{fname}@{} depends on a local package in {lock_key} (`{local}`). \ + pnpm 12.23 and newer refuse a lock in which a package fetched \ + from a hosted patch depends on a local file \ + (ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED), so the dep is left \ + unredirected in EVERY lock (nothing rewritten, nothing \ + confirmed). If socket-patch vendored that dependency, move it \ + to hosted mode as well (`socket-patch scan --mode hosted` takes \ + it over) and re-run", + dep.version + ), + }); + } + continue; + } for (idx, splices, mut instance_edits) in planned { let lock = &mut locks[idx]; for (i, range, replacement) in splices { diff --git a/crates/socket-patch-core/src/formats/pnpm/mod.rs b/crates/socket-patch-core/src/formats/pnpm/mod.rs index 0913ce64e..fe6f0a343 100644 --- a/crates/socket-patch-core/src/formats/pnpm/mod.rs +++ b/crates/socket-patch-core/src/formats/pnpm/mod.rs @@ -1164,10 +1164,12 @@ mod architecture_tests { const WRITERS: &[(&str, usize, &str)] = &[ ( "vendor/pnpm_lock.rs", - 4, + 5, "vendored planner (both dialects): the shared lookup and rekey \ over line blocks (`lock_has_target_package`, `edit_packages`, \ - `LockIndex`), keys read with `plan::match_key`; and the revert's \ + `LockIndex`), keys read with `plan::match_key`; the ref gate's \ + look at a dependent's block on the lines it gates, when they \ + have no index (`check_hosted_dependents`); and the revert's \ check, on the lines it is editing, that the registry entry is \ back before references are pointed at it \ (`restore_unrecorded_refs`)", diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index e68276918..0f7a5ebf3 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -1043,8 +1043,14 @@ pub async fn lock_text_refusals( /// /// Evaluating the gates on the still-hosted lock is exact for pnpm: the /// hosted restore only splices each entry's `resolution:` value, which no -/// pnpm gate reads (coordinates, CRLF, catalogs, overrides, entry presence -/// and ref rewritability all key on other text). The one difference is a +/// pnpm gate reads of the candidate itself (coordinates, CRLF, catalogs, +/// overrides, entry presence and ref rewritability all key on other text). +/// One gate reads the resolution of the candidate's DEPENDENTS +/// (`pnpm_lock::check_hosted_dependents`, #2263): a dependent that is +/// itself a candidate of this takeover is still hosted in this text, so +/// its dependency is refused for this run and vendored by the next, once +/// the dependent is. That holds whatever order the run takes them in; the +/// eject restores every pin before it asks. The one other difference is a /// `pnpm-workspace.yaml` scaffold hosted mode created, which the restore /// deletes; a gate that depended on it would make this under-predict, and /// the wet run still refuses. diff --git a/crates/socket-patch-core/src/vendor/pnpm_lock.rs b/crates/socket-patch-core/src/vendor/pnpm_lock.rs index 55542a31f..7e0cd8461 100644 --- a/crates/socket-patch-core/src/vendor/pnpm_lock.rs +++ b/crates/socket-patch-core/src/vendor/pnpm_lock.rs @@ -905,6 +905,9 @@ fn preflight_package( if let Err(detail) = check_rewritable_refs_with(lines, name, version, lines.index()) { return Err(Box::new(refused("vendor_lock_entry_unsupported", detail))); } + if let Err(detail) = check_hosted_dependents(lines, name, version, lines.index()) { + return Err(Box::new(refused("vendor_lock_entry_unsupported", detail))); + } } ProjectLock::Legacy(lock) => { super::pnpm_lock_legacy::preflight_package(lock, name, version)?; @@ -2057,6 +2060,110 @@ fn check_rewritable_refs_with( Ok(()) } +/// Pre-flight guard for the dependents of `name@version` that a hosted +/// patch pins (#2263). +/// +/// Vendoring rewrites every dependent's `name: version` snapshot ref to the +/// `file:` tarball. pnpm 12.23 refuses a lock in which a package that is +/// not local depends on a local file, unless it can tie the workspace +/// override to that package (`ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED`). It does +/// so for a package resolved from the default registry by its integrity +/// alone. It does not for one a hosted patch pins (the tarball of its pin, +/// or of the named registry of its route): every install of the vendored +/// project would then fail, frozen or not. Verified against pnpm 12.23.0; +/// the hosted planner refuses the same pair from its side +/// (`formats::pnpm::hosted::plan_hosted`). +/// +/// Only a hosted pin is in the way: a tarball in a Socket patch server's +/// path shape ([`crate::origin::hosted_shape_uuid`], on any origin, since +/// the gate is not handed the run's origins). A dependent that is local +/// itself (a `file:` key, a vendored package among them) is exempt, as +/// pnpm exempts it, and one whose resolution names any other tarball is +/// left as it was before this gate. +/// +/// A hosted → vendored takeover reads this gate on the still-hosted lock +/// ([`super::pnpm_takeover_lock_text_refusals`]), so the dependency of a +/// package the same run takes over waits for the next run; the eject +/// restores every pin first. +pub(super) fn check_hosted_dependents( + lines: &[String], + name: &str, + version: &str, + index: Option<&LockIndex>, +) -> Result<(), String> { + // The snapshot blocks whose body holds a `name: version` ref. + let is_ref = |line: &String| { + parse_key_line(line, 6) + .is_some_and(|(dep, _, rest)| dep == name && unquote_value(rest) == version) + }; + let dependents: Vec = match index { + Some(index) => index + .snapshot_dep_lines + .get(name) + .into_iter() + .flatten() + .filter(|&&(line, _)| is_ref(&lines[line])) + .map(|&(_, block)| index.snapshots.blocks[block].key.clone()) + .collect(), + None => section_bounds(lines, "snapshots") + .into_iter() + .flat_map(|(start, end)| { + std::iter::successors(next_block(lines, start + 1, end), move |b| { + next_block(lines, b.end, end) + }) + }) + .filter(|block| lines[block.header + 1..block.end].iter().any(is_ref)) + .map(|block| block.key) + .collect(), + }; + if dependents.is_empty() { + return Ok(()); + } + // The `packages:` block of a key: `(header, end)`. + let package_block = |key: &str| match index { + Some(index) => { + let block = &index.packages.blocks[*index.packages.by_key.get(key)?.first()?]; + Some((block.header, block.end)) + } + None => { + let (start, end) = section_bounds(lines, "packages")?; + std::iter::successors(next_block(lines, start + 1, end), |b| { + next_block(lines, b.end, end) + }) + .find(|block| block.key == key) + .map(|block| (block.header, block.end)) + } + }; + for dependent in &dependents { + let key = crate::formats::pnpm::strip_pnpm_peer_suffix(dependent); + let crate::formats::pnpm::PnpmKey::Registry { + name: by, + version: by_version, + } = crate::formats::pnpm::classify_pnpm_key(key) + else { + continue; + }; + let Some((header, end)) = package_block(key) else { + continue; + }; + let hosted = crate::formats::pnpm::fragment_resolution(&lines[header..end]) + .and_then(|(_, tarball)| tarball) + .is_some_and(|tarball| crate::origin::hosted_shape_uuid(&tarball).is_some()); + if hosted { + return Err(format!( + "{PNPM_LOCK} installs {by}@{by_version} from a hosted patch (`{key}`) and it \ + depends on {name}@{version}. pnpm 12.23 and newer refuse a lock in which \ + such a package depends on a local file \ + (ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED), so vendoring {name}@{version} would \ + break every install. Patch {name}@{version} in hosted mode as well, or \ + vendor {by}@{by_version} first and run this again (`socket-patch vendor` \ + moves every hosted patch in one run)" + )); + } + } + Ok(()) +} + /// Every snapshot block header and body line, in lock order: the scan's /// [`SnapshotCandidate`]s. fn snapshot_positions(lines: &[String]) -> impl Iterator + '_ { @@ -9928,6 +10035,104 @@ snapshots: assert!(check_rewritable_refs(&lines, name, "1.0.0").is_ok()); } + /// pnpm 12.23 refuses a lock in which a package a hosted patch pins + /// depends on a local file (#2263): vendoring `leaf@1.0.0` under such a + /// dependent (pinned by its tarball, or through the named registry of + /// its route) is refused, by the scan and by the index alike. A + /// dependent on the default registry (with or without its tarball URL + /// in the lock), a local one and one of another `leaf` release are not + /// in the way. + #[test] + fn hosted_dependents_refuse_vendoring_their_dependency() { + const HOSTED: &str = "https://patch.socket.dev/patch/npm/mid/1.0.0/\ + 9ee29ee2-9ee2-49ee-829e-e29ee29ee29e/bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb/mid-1.0.0.tgz"; + const LOCAL: &str = + "file:.socket/vendor/npm/bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb/mid-1.0.0.tgz"; + let lock = |key: &str, resolution: &str, snapshot: &str, leaf: &str| { + format!( + "lockfileVersion: '9.0'\n\npackages:\n\n leaf@1.0.0:\n resolution: \ + {{integrity: sha512-LEAF==}}\n\n {key}:\n resolution: {resolution}\n\n\ + snapshots:\n\n leaf@1.0.0: {{}}\n\n {snapshot}:\n dependencies:\n \ + leaf: {leaf}\n" + ) + }; + let pinned = format!("{{integrity: sha512-MID==, tarball: {HOSTED}}}"); + let check = |text: &str| { + let lines = split_lines(text); + let index = LockIndex::build(&lines); + let scan = check_hosted_dependents(&lines, "leaf", "1.0.0", None); + let indexed = check_hosted_dependents(&lines, "leaf", "1.0.0", Some(&index)); + assert_eq!(scan, indexed, "the index answers as the scan:\n{text}"); + scan + }; + for (what, key, snapshot) in [ + ("a pinned tarball", "mid@1.0.0", "mid@1.0.0"), + ("a peer context", "mid@1.0.0", "mid@1.0.0(host@1.0.0)"), + ( + "a named registry", + "mid@socket-bbbbbbbb:1.0.0", + "mid@socket-bbbbbbbb:1.0.0(host@1.0.0)", + ), + ("a scoped name", "'@sc/mid@1.0.0'", "'@sc/mid@1.0.0'"), + ] { + let err = check(&lock(key, &pinned, snapshot, "1.0.0")) + .expect_err(&format!("{what} must refuse")); + let key = key.trim_matches('\''); + let named = key.replace("socket-bbbbbbbb:", ""); + assert!( + err.contains(&format!("installs {named} from a hosted patch (`{key}`)")) + && err.contains("depends on leaf@1.0.0") + && err.contains("ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED") + && !err.contains(HOSTED), + "{what}: {err}" + ); + } + for (what, text) in [ + ( + "a dependent on the default registry", + lock( + "mid@1.0.0", + "{integrity: sha512-MID==}", + "mid@1.0.0", + "1.0.0", + ), + ), + ( + "a registry dependent whose tarball URL the lock records", + lock( + "mid@1.0.0", + "{integrity: sha512-MID==, tarball: https://registry.npmjs.org/mid/-/mid-1.0.0.tgz}", + "mid@1.0.0", + "1.0.0", + ), + ), + ( + "a vendored dependent", + lock( + &format!("mid@{LOCAL}"), + &format!("{{integrity: sha512-MID==, tarball: {LOCAL}}}"), + &format!("mid@{LOCAL}"), + "1.0.0", + ), + ), + ( + "a dependent of another release", + lock("mid@1.0.0", &pinned, "mid@1.0.0", "2.0.0"), + ), + ( + "a dependent already on the vendored tarball", + lock( + "mid@1.0.0", + &pinned, + "mid@1.0.0", + "file:.socket/vendor/npm/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/leaf-1.0.0.tgz", + ), + ), + ] { + assert_eq!(check(&text), Ok(()), "{what}:\n{text}"); + } + } + /// KNOWN GAP (coverage-audit suspected bug, needs triage): an importer /// dep entry that lost its `specifier:` field (keeping `version:`) is /// neither refused by `check_rewritable_refs` nor rewritten by diff --git a/crates/socket-patch-core/src/vendor/pnpm_lock/rush.rs b/crates/socket-patch-core/src/vendor/pnpm_lock/rush.rs index 371928f9e..abb042c14 100644 --- a/crates/socket-patch-core/src/vendor/pnpm_lock/rush.rs +++ b/crates/socket-patch-core/src/vendor/pnpm_lock/rush.rs @@ -70,11 +70,12 @@ use crate::vendor::state::{PnpmMeta, VendorEntry, WiringAction, WiringRecord}; use crate::vendor::{RevertOpts, RevertOutcome, VendorOutcome, VendorWarning}; use super::{ - check_rewritable_refs_with, dep_entries, drifted, edit_packages, edit_snapshot_refs, - edit_snapshot_rekey, is_mixed_line_endings, lock_has_target_package, matching_blocks, - override_key_name, overrides_record, read_pnpm_text, restore_dep_map_refs, revert_lock_record, - split_v9_lock, EditCtx, PnpmDialect, RefBlocks, KIND_LOCK_IMPORTER_DEP, KIND_LOCK_PACKAGE, - KIND_LOCK_SNAPSHOT, VENDOR_CONFIG_DEPENDENCY_UNPATCHED, VENDOR_PNPM_LOCK_MULTI_DOCUMENT, + check_hosted_dependents, check_rewritable_refs_with, dep_entries, drifted, edit_packages, + edit_snapshot_refs, edit_snapshot_rekey, is_mixed_line_endings, lock_has_target_package, + matching_blocks, override_key_name, overrides_record, read_pnpm_text, restore_dep_map_refs, + revert_lock_record, split_v9_lock, EditCtx, PnpmDialect, RefBlocks, KIND_LOCK_IMPORTER_DEP, + KIND_LOCK_PACKAGE, KIND_LOCK_SNAPSHOT, VENDOR_CONFIG_DEPENDENCY_UNPATCHED, + VENDOR_PNPM_LOCK_MULTI_DOCUMENT, }; /// The ledger flavor of a Rush-wired entry. @@ -934,6 +935,7 @@ async fn plan( ) }; check_rewritable_refs_with(&doc.lines, name, version, None).map_err(unsupported)?; + check_hosted_dependents(&doc.lines, name, version, None).map_err(unsupported)?; override_conflict( lock_rel, lock_overrides(&doc.lines) @@ -2669,6 +2671,28 @@ mod tests { assert_eq!(code, "vendor_lock_entry_not_found"); } + /// A dependent that a hosted patch pins (#2263): pnpm 12.23 refuses a + /// lock in which it depends on a local file, so its dependency is not + /// vendored under it. The refusal names Rush's lock. + #[tokio::test] + async fn a_dependency_of_a_hosted_package_is_refused() { + const MKDIRP: &str = " mkdirp@0.5.1:\n resolution: {integrity: sha512-SknJC52obPfGQPnjIkXbmA6+5H15E+fR+E4iR2oQ3zzCLbd7/ONua69R/Gw7AgkTLsRG+r5fzksYwWe1AgTyWA==}\n"; + let repo = Repo::new("pnpm10"); + let lock = repo.read(RUSH_COMMON_LOCK_REL); + assert!(lock.contains(MKDIRP), "{lock}"); + let hosted = " mkdirp@0.5.1:\n resolution: {integrity: sha512-PATCHED==, tarball: https://patch.socket.dev/patch/npm/mkdirp/0.5.1/9ee29ee2-9ee2-49ee-829e-e29ee29ee29e/bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb/mkdirp-0.5.1.tgz}\n"; + repo.write(RUSH_COMMON_LOCK_REL, &lock.replace(MKDIRP, hosted)); + let (code, detail) = refused(&repo, MINIMIST_008).await; + assert_eq!(code, "vendor_lock_entry_unsupported"); + assert!( + detail.contains(&format!( + "{RUSH_COMMON_LOCK_REL} installs mkdirp@0.5.1 from a hosted patch" + )) && detail.contains("depends on minimist@0.0.8") + && detail.contains("ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED"), + "{detail}" + ); + } + /// The lock and a project's `package.json` disagree: `rush update` has /// not run since the manifest changed. #[tokio::test] diff --git a/crates/socket-patch-core/tests/pnpm_hosted.rs b/crates/socket-patch-core/tests/pnpm_hosted.rs index a021b29e0..8c8b3c78e 100644 --- a/crates/socket-patch-core/tests/pnpm_hosted.rs +++ b/crates/socket-patch-core/tests/pnpm_hosted.rs @@ -121,6 +121,118 @@ fn malformed_resolution_refuses_the_dependency_across_all_locks() { } } +/// A v9 lock in which `left-pad@1.3.0` depends on `leaf`, resolved as +/// `resolution` and reached through the snapshot value `leaf`. +fn lock_with_dependency(resolution: &str, leaf: &str) -> String { + format!( + "lockfileVersion: '9.0'\n\npackages:\n\n left-pad@1.3.0:\n resolution: {resolution}\n\n \ + other@1.0.0:\n resolution: {{integrity: sha512-OTHER==}}\n\nsnapshots:\n\n \ + left-pad@1.3.0(peer@2.0.0):\n dependencies:\n leaf: {leaf}\n peer: 2.0.0\n\n \ + other@1.0.0:\n dependencies:\n leaf: 1.0.0\n" + ) +} + +/// pnpm 12.23 refuses a lock in which a package fetched from a tarball +/// URL depends on a local file (#2263), so the pin that would take such a +/// package off the default registry is refused in every lock. +#[test] +fn a_package_with_a_local_dependency_is_not_taken_off_the_registry() { + const UPSTREAM: &str = "{integrity: sha512-UPSTREAM==}"; + // With `lockfileIncludeTarballUrl`, a registry entry names its tarball. + const UPSTREAM_URL: &str = "{integrity: sha512-UPSTREAM==, tarball: https://registry.npmjs.org/left-pad/-/left-pad-1.3.0.tgz}"; + for (local, upstream) in [ + ( + "file:.socket/vendor/npm/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/leaf-1.0.0.tgz", + UPSTREAM, + ), + ( + "'file:.socket/vendor/npm/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/leaf-1.0.0.tgz'", + UPSTREAM, + ), + ("file:../leaf", UPSTREAM), + ( + "file:.socket/vendor/npm/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/leaf-1.0.0.tgz", + UPSTREAM_URL, + ), + ] { + let files = BTreeMap::from([ + ( + "pnpm-lock.yaml".to_string(), + lock_with_dependency(upstream, local), + ), + ( + "common/config/rush/pnpm-lock.yaml".to_string(), + lock_with_dependency(upstream, "1.0.0"), + ), + ]); + let result = rewrite_registry_redirect(&files, &[dep("left-pad")]); + assert!( + result.files.is_empty() && result.edits.is_empty(), + "{local}: partial rewrite" + ); + assert!(result.refused_pnpm_uuids.contains("patch-id"), "{local}"); + let warnings: Vec<_> = result + .warnings + .iter() + .filter(|w| w.code == "redirect_pnpm_local_dependency") + .collect(); + let [warning] = warnings.as_slice() else { + panic!("{local}: one refusal, for the lock that has the dependency: {warnings:?}"); + }; + let unquoted = local.trim_matches('\''); + assert!( + warning.detail.contains(&format!("`leaf: {unquoted}`")) + && warning.detail.contains("in pnpm-lock.yaml") + && warning.detail.contains("ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED"), + "{}", + warning.detail + ); + } +} + +/// The refusal is for the package the pin moves, and only when the pin +/// makes a hosted package of it: a registry dependency, a peer a workspace +/// project satisfies (`link:`), another package's local dependency and a +/// package an earlier patch already pins are all pinned as before. +#[test] +fn the_local_dependency_refusal_is_scoped_to_the_new_pin() { + const LOCAL: &str = + "file:.socket/vendor/npm/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/leaf-1.0.0.tgz"; + let other_has_it = lock_with_dependency("{integrity: sha512-UPSTREAM==}", "1.0.0").replace( + " other@1.0.0:\n dependencies:\n leaf: 1.0.0\n", + &format!(" other@1.0.0:\n dependencies:\n leaf: {LOCAL}\n"), + ); + assert!(other_has_it.contains(LOCAL)); + for (what, lock) in [ + ( + "a registry dependency", + lock_with_dependency("{integrity: sha512-UPSTREAM==}", "1.0.0"), + ), + ( + "a workspace peer", + lock_with_dependency("{integrity: sha512-UPSTREAM==}", "link:packages/leaf"), + ), + ("another package's local dependency", other_has_it), + ( + "a package an earlier patch pins", + lock_with_dependency( + "{integrity: sha512-STALE==, tarball: https://patch.example/patch/npm/left-pad/1.3.0/9ee29ee2-9ee2-49ee-829e-e29ee29ee29e/cccccccc-cccc-4ccc-8ccc-cccccccccccc/left-pad-1.3.0.tgz}", + LOCAL, + ), + ), + ] { + let files = BTreeMap::from([("pnpm-lock.yaml".to_string(), lock)]); + let result = rewrite_registry_redirect(&files, &[dep("left-pad")]); + assert!(result.warnings.is_empty(), "{what}: {:?}", result.warnings); + assert!(result.refused_pnpm_uuids.is_empty(), "{what}"); + assert_eq!(result.edits.len(), 1, "{what}"); + assert!( + result.files["pnpm-lock.yaml"].contains("https://patch.example/left-pad-1.3.0.tgz"), + "{what}" + ); + } +} + #[test] fn quoted_flow_values_keep_commas_and_extra_fields() { let lock = "packages:\n left-pad@1.3.0:\n resolution: {integrity: sha512-UPSTREAM==, tarball: 'https://registry.example/a,b.tgz', note: 'keep,a,b'}\n"; diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 14dfbf8b6..853dd8751 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -238,6 +238,20 @@ Each Legacy format has an upgrade path and an undo path. Both work in v5: which pnpm applies through `overrides` without a lock; `vex` attests such a vendored pin only while the override map that pnpm reads still routes the package to its artifact, and omits it otherwise (`vex_lock_not_read`). + **One mode for a package and its dependency.** pnpm 12.23 and newer refuse + a lock in which a package fetched from a hosted patch depends on a local + file (`ERR_PNPM_LOCAL_SUBDEP_NOT_ALLOWED`), on every install, frozen or + not. A vendored patch is a local file, so a package patched in hosted mode + cannot depend on a package patched in vendored mode. Whichever run would + create that pair is refused before anything is written, on every pnpm: + hosted mode leaves the package unpinned and warns + `redirect_pnpm_local_dependency`, and vendored mode refuses the dependency + with `vendor_lock_entry_unsupported`. Patch both in one mode: + `socket-patch scan --mode hosted` takes a vendored dependency over, and + `socket-patch vendor` moves every hosted patch to vendored mode in one run + (`scan --mode vendored` moves a package in one run and its dependency in + the next). A package on the default registry can depend on a vendored one + as before. pnpm >=11 checks every lock entry that records a tarball URL against a registry, so a hosted pin needs a setting in the root `pnpm-workspace.yaml`. For 9.0 root or member locks the CLI writes one of two, unless opted out