Skip to content

fix: honor the requested version when updating a transitive dependency - #12752

Closed
m2na7 wants to merge 1 commit into
pnpm:mainfrom
m2na7:fix/update-transitive-dependency-version
Closed

m2na7 wants to merge 1 commit into
pnpm:mainfrom
m2na7:fix/update-transitive-dependency-version

Conversation

@m2na7

@m2na7 m2na7 commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

fixes #12744

pnpm update <dep>@<version> ignores <version> when <dep> exists only as a transitive dependency: it re-resolves the dependency to the highest version in range instead of the requested one.

Reproduction

A project depends on @swc/cli, which depends on piscina (^4.3.1) transitively. With piscina resolved to an older in-range version (e.g. 4.5.0):

pnpm update [email protected]
# expected: piscina 4.9.0
# actual:   piscina 4.9.3 (highest in range)

The requested version is dropped whether it is higher or lower than the currently resolved one.

Root cause

When an update selector matches no direct dependency, installDeps treats it as a transitive-only update and builds an updateMatching predicate:

updateMatching = (pkgName) => updateMatch(pkgName) != null

updateMatching only flags a package for re-resolution — it returns a boolean and cannot carry the version parsed from <dep>@<version>. The version is therefore discarded and the resolver falls back to the highest version in range.

Fix

For a transitive-only update whose selector pins an exact version, pass that version through preferredVersions so the resolver prefers it during re-resolution — the same mechanism getExactSinglePreferredVersions and the audit-fix path already use. Version ranges, dist-tags, glob and negation selectors are left to normal resolution.

Scope

This covers the non-recursive pnpm update <dep>@<version> from the reproduction. Recursive (-r) updates of a transitive dependency by name, and range/tag selectors, are unchanged.

Test

Added a regression test that pins a transitive dependency, then updates it to an explicit in-range version and asserts the requested version is installed rather than the latest.

Summary by CodeRabbit

  • Bug Fixes
    • Updating a transitive dependency with an explicit version now installs that exact version, rather than selecting a different in-range match.
    • Dependency resolution now more reliably preserves explicitly requested version selectors, improving lockfile accuracy.
    • Prevented Object prototype pollution when processing crafted update specifications.
  • Tests
    • Added coverage for exact-version transitive updates and for prototype-safety with malicious package spec inputs.

@m2na7
m2na7 requested a review from zkochan as a code owner July 1, 2026 10:28
@welcome

welcome Bot commented Jul 1, 2026

Copy link
Copy Markdown

💖 Thanks for opening this pull request! 💖
Please be patient and we will get back to you as soon as we can.

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: cd83e9a3-0548-4a9e-acff-b658022ad9eb

📥 Commits

Reviewing files that changed from the base of the PR and between f4c0211 and 662aa70.

📒 Files selected for processing (3)
  • .changeset/update-transitive-dep-to-exact-version.md
  • pnpm11/installing/commands/src/installDeps.ts
  • pnpm11/installing/commands/test/update/update.ts
✅ Files skipped from review due to trivial changes (1)
  • .changeset/update-transitive-dep-to-exact-version.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • pnpm11/installing/commands/src/installDeps.ts

📝 Walkthrough

Walkthrough

This PR updates pnpm update <dep>@<version> so explicit version requests can resolve transitive dependencies to the requested version by deriving preferred versions from the raw update specs and merging them into install resolution.

Changes

Exact Version Preference for Transitive Updates

Layer / File(s) Summary
Preferred versions derivation and wiring
pnpm11/installing/commands/src/installDeps.ts
Adds raw spec preservation, exact-version parsing, selector normalization, and preferred-version merging into install options.
Test and changeset for transitive exact update
pnpm11/installing/commands/test/update/update.ts, .changeset/update-transitive-dep-to-exact-version.md
Adds coverage for transitive explicit-version updates and records the patch in a changeset.

Estimated code review effort: 2 (Simple) | ~15 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI as update.handler
  participant installDeps as installDeps
  participant Parser as parseUpdateParam
  participant Resolver as install resolver

  CLI->>installDeps: run update with params
  installDeps->>installDeps: save updateSpecs before reassignment
  installDeps->>Parser: parseUpdateParam(updateSpecs)
  Parser-->>installDeps: pattern, versionSpec
  installDeps->>installDeps: build preferredVersions
  installDeps->>Resolver: merge preferredVersions into installOpts
  Resolver-->>installDeps: resolve requested exact version
Loading

Assessment against linked issues

Objective Addressed Explanation
pnpm up dep@version should update transitive dependencies to the specified version, not the highest in-range version [#12744] ✅

Suggested labels: product: pnpm@11

Suggested reviewers: zkochan

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Fix pnpm update to respect exact versions for transitive-only dependencies

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Preserve exact @ when updating a transitive-only dependency.
• Pass requested exact versions via preferredVersions during re-resolution.
• Add regression test ensuring requested version wins over latest dist-tag.
Diagram

graph TD
  U["pnpm update args"] --> I["installDeps()"] --> M{"Direct deps matched?"}
  M -- "yes" --> S["Resolver re-resolve"] --> L[("pnpm-lock.yaml")]
  M -- "no (transitive only)" --> T["updateMatching: flag packages"] --> P["preferredVersions from specs"] --> S

  subgraph Legend
    direction LR
    _p["Process"] ~~~ _d{"Decision"} ~~~ _ds[("Data")]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Extend updateMatching to carry version specs
  • ➕ Would encode “dep -> requested version” directly in the updateMatching mechanism.
  • ➕ Avoids mixing update intent into preferredVersions.
  • ➖ Requires API changes across @pnpm/installing.deps-installer and call sites.
  • ➖ Higher regression risk; more complex semantics (boolean vs spec).
2. Treat transitive-only exact update as a temporary direct dependency
  • ➕ Leverages existing direct-dependency update code paths.
  • ➕ Could reuse existing exact-spec handling without resolver preferences.
  • ➖ Blurs meaning of manifests (would need special-casing to avoid writing package.json).
  • ➖ More intrusive behavior changes and edge cases around save/no-save.

Recommendation: Current approach (injecting preferredVersions only for exact, non-glob, non-negated transitive-only specs) is the best tradeoff: minimal surface-area change, reuses an existing resolver mechanism already used by other flows (e.g., exact preferred versions / audit fix), and avoids altering public matcher/updateMatching contracts.

Files changed (3) +64 / -0

Bug fix (1) +26 / -0
installDeps.tsPrefer exact requested version for transitive-only updates +26/-0

Prefer exact requested version for transitive-only updates

• When no direct dependencies match update selectors, captures the original update specs and derives preferredVersions from exact dep@version selectors. Merges these into install options so the resolver prefers the requested exact version during re-resolution, while leaving ranges/tags/globs/negations unchanged.

pnpm11/installing/commands/src/installDeps.ts

Tests (1) +32 / -0
update.tsRegression test: transitive update honors explicit version +32/-0

Regression test: transitive update honors explicit version

• Adds a test that installs a project where a dependency is only transitive, then updates it using an explicit in-range version. Asserts the lockfile contains the requested version and not the latest dist-tag or prior version.

pnpm11/installing/commands/test/update/update.ts

Documentation (1) +6 / -0
update-transitive-dep-to-exact-version.mdAdd changeset for transitive-only exact update fix +6/-0

Add changeset for transitive-only exact update fix

• Introduces a patch changeset for @pnpm/installing.commands and pnpm. Documents that pnpm update <dep>@<version> now prefers the requested exact version when the dependency is transitive-only.

.changeset/update-transitive-dep-to-exact-version.md

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Update spec prototype pollution 🐞 Bug ⛨ Security
Description
getPreferredVersionsForUpdateSpecs writes the user-controlled update selector pattern into a plain
object without filtering __proto__/constructor/prototype, so pnpm update [email protected] can
end up mutating Object.prototype. This can corrupt runtime state or crash pnpm during/after
dependency resolution.
Code

pnpm11/installing/commands/src/installDeps.ts[R601-611]

+function getPreferredVersionsForUpdateSpecs (updateSpecs: string[]): PreferredVersions {
+  const preferredVersions: PreferredVersions = {}
+  for (const spec of updateSpecs) {
+    const { pattern, versionSpec } = parseUpdateParam(spec)
+    if (versionSpec == null || pattern.includes('*') || pattern.startsWith('!')) continue
+    // Only an exact version of a single named package can be preferred.
+    const selector = getVersionSelectorType(versionSpec)
+    if (selector?.type !== 'version') continue
+    preferredVersions[pattern] = preferredVersions[pattern] ?? {}
+    preferredVersions[pattern][selector.normalized] = 'version'
+  }
Evidence
The new helper uses a plain object and assigns user-derived keys (pattern) into it, enabling
special-key prototype mutation; pattern comes from parseUpdateParam() which performs only string
slicing and no validation. The same file already includes an explicit prototype-pollution guard for
vulnerability ranges, showing this threat model is relevant here too.

pnpm11/installing/commands/src/installDeps.ts[601-611]
pnpm11/installing/commands/src/recursive.ts[606-618]
pnpm11/installing/commands/src/installDeps.ts[632-635]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`getPreferredVersionsForUpdateSpecs()` builds `preferredVersions` as a plain object and indexes it with `pattern` coming from CLI args. Special keys like `__proto__`, `constructor`, or `prototype` can trigger prototype pollution (including writing onto `Object.prototype`) via the nested assignment.
### Issue Context
`parseUpdateParam()` does not validate/sanitize `pattern`, so this path must defensively guard keys or avoid prototype-bearing objects.
### Fix Focus Areas
- pnpm11/installing/commands/src/installDeps.ts[601-613]
### Suggested fix
1) Build maps with null prototypes:
- `const preferredVersions = Object.create(null) as PreferredVersions`
- for nested maps: `preferredVersions[pattern] ??= Object.create(null) as any`
2) Add explicit key guards before writing:
- Skip/throw if `pattern` is `__proto__`, `constructor`, or `prototype`.
3) (Recommended) Add a regression test that calls update with a selector like `[email protected]` and asserts `({} as any).someInjectedProp` is still `undefined` (i.e., Object.prototype wasn’t polluted).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Test dist-tag state leak 🐞 Bug ☼ Reliability
Description
The new regression test updates the mock registry's global latest dist-tag for
@pnpm.e2e/dep-of-pkg-with-1-dep and never restores it, so later tests can resolve a different
version depending on execution order. Because the resolver prefers meta['dist-tags'].latest for
* ranges, this can affect many other tests that depend on that fixture package.
Code

pnpm11/installing/commands/test/update/update.ts[R159-165]

+  // 101.0.0 is now the latest, but the update requests 100.1.0, which must win.
+  await addDistTag({ package: '@pnpm.e2e/dep-of-pkg-with-1-dep', version: '101.0.0', distTag: 'latest' })
+
+  await update.handler({
+    ...DEFAULT_OPTS,
+    dir: process.cwd(),
+  }, ['@pnpm.e2e/[email protected]'])
Evidence
The test sets latest to 101.0.0 and does not revert it. addDistTag updates the shared registry
mock via setDistTag, and the resolver explicitly prefers meta['dist-tags'].latest when the range
is '*', so this dist-tag mutation can change resolutions outside this test.

pnpm11/installing/commands/test/update/update.ts[142-172]
pnpm11/testing/registry-mock/src/index.ts[35-57]
pnpm11/resolving/npm-resolver/src/pickPackageFromMeta.ts[172-193]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The added test mutates shared registry mock state by changing the `latest` dist-tag, but doesn't restore it. This can make other tests order-dependent/flaky.
### Issue Context
- `addDistTag()` performs a real authenticated `setDistTag` call against the shared registry mock.
- The npm resolver prefers `dist-tags.latest` for `versionRange === '*'`, so changing `latest` affects unrelated dependency resolutions.
### Fix Focus Areas
- pnpm11/installing/commands/test/update/update.ts[142-172]
### Suggested fix
- Wrap the dist-tag change in a `try/finally` and restore `latest` to the value set earlier in the test (e.g. back to `100.0.0`), or to whatever the suite-wide expected default is.
- Alternatively, avoid touching `latest` by using a dedicated test package/fixture name (if available) so the test doesn't mutate a commonly-used package's dist-tags.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Previous review results

Review updated until commit 662aa70

Results up to commit 662aa70


🐞 Bugs (2) 📘 Rule violations (0) 📜 Skill insights (0)


Action required
1. Update spec prototype pollution 🐞 Bug ⛨ Security
Description
getPreferredVersionsForUpdateSpecs writes the user-controlled update selector pattern into a plain
object without filtering __proto__/constructor/prototype, so pnpm update [email protected] can
end up mutating Object.prototype. This can corrupt runtime state or crash pnpm during/after
dependency resolution.
Code

pnpm11/installing/commands/src/installDeps.ts[R601-611]

+function getPreferredVersionsForUpdateSpecs (updateSpecs: string[]): PreferredVersions {
+  const preferredVersions: PreferredVersions = {}
+  for (const spec of updateSpecs) {
+    const { pattern, versionSpec } = parseUpdateParam(spec)
+    if (versionSpec == null || pattern.includes('*') || pattern.startsWith('!')) continue
+    // Only an exact version of a single named package can be preferred.
+    const selector = getVersionSelectorType(versionSpec)
+    if (selector?.type !== 'version') continue
+    preferredVersions[pattern] = preferredVersions[pattern] ?? {}
+    preferredVersions[pattern][selector.normalized] = 'version'
+  }
Evidence
The new helper uses a plain object and assigns user-derived keys (pattern) into it, enabling
special-key prototype mutation; pattern comes from parseUpdateParam() which performs only string
slicing and no validation. The same file already includes an explicit prototype-pollution guard for
vulnerability ranges, showing this threat model is relevant here too.

pnpm11/installing/commands/src/installDeps.ts[601-611]
pnpm11/installing/commands/src/recursive.ts[606-618]
pnpm11/installing/commands/src/installDeps.ts[632-635]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`getPreferredVersionsForUpdateSpecs()` builds `preferredVersions` as a plain object and indexes it with `pattern` coming from CLI args. Special keys like `__proto__`, `constructor`, or `prototype` can trigger prototype pollution (including writing onto `Object.prototype`) via the nested assignment.
### Issue Context
`parseUpdateParam()` does not validate/sanitize `pattern`, so this path must defensively guard keys or avoid prototype-bearing objects.
### Fix Focus Areas
- pnpm11/installing/commands/src/installDeps.ts[601-613]
### Suggested fix
1) Build maps with null prototypes:
- `const preferredVersions = Object.create(null) as PreferredVersions`
- for nested maps: `preferredVersions[pattern] ??= Object.create(null) as any`
2) Add explicit key guards before writing:
- Skip/throw if `pattern` is `__proto__`, `constructor`, or `prototype`.
3) (Recommended) Add a regression test that calls update with a selector like `[email protected]` and asserts `({} as any).someInjectedProp` is still `undefined` (i.e., Object.prototype wasn’t polluted).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended
2. Test dist-tag state leak 🐞 Bug ☼ Reliability
Description
The new regression test updates the mock registry's global latest dist-tag for
@pnpm.e2e/dep-of-pkg-with-1-dep and never restores it, so later tests can resolve a different
version depending on execution order. Because the resolver prefers meta['dist-tags'].latest for
* ranges, this can affect many other tests that depend on that fixture package.
Code

pnpm11/installing/commands/test/update/update.ts[R159-165]

+  // 101.0.0 is now the latest, but the update requests 100.1.0, which must win.
+  await addDistTag({ package: '@pnpm.e2e/dep-of-pkg-with-1-dep', version: '101.0.0', distTag: 'latest' })
+
+  await update.handler({
+    ...DEFAULT_OPTS,
+    dir: process.cwd(),
+  }, ['@pnpm.e2e/[email protected]'])
Evidence
The test sets latest to 101.0.0 and does not revert it. addDistTag updates the shared registry
mock via setDistTag, and the resolver explicitly prefers meta['dist-tags'].latest when the range
is '*', so this dist-tag mutation can change resolutions outside this test.

pnpm11/installing/commands/test/update/update.ts[142-172]
pnpm11/testing/registry-mock/src/index.ts[35-57]
pnpm11/resolving/npm-resolver/src/pickPackageFromMeta.ts[172-193]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The added test mutates shared registry mock state by changing the `latest` dist-tag, but doesn't restore it. This can make other tests order-dependent/flaky.
### Issue Context
- `addDistTag()` performs a real authenticated `setDistTag` call against the shared registry mock.
- The npm resolver prefers `dist-tags.latest` for `versionRange === '*'`, so changing `latest` affects unrelated dependency resolutions.
### Fix Focus Areas
- pnpm11/installing/commands/test/update/update.ts[142-172]
### Suggested fix
- Wrap the dist-tag change in a `try/finally` and restore `latest` to the value set earlier in the test (e.g. back to `100.0.0`), or to whatever the suite-wide expected default is.
- Alternatively, avoid touching `latest` by using a dedicated test package/fixture name (if available) so the test doesn't mutate a commonly-used package's dist-tags.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit f4c0211


🐞 Bugs (2) 📘 Rule violations (0) 📜 Skill insights (0)


Action required
1. Update spec prototype pollution 🐞 Bug ⛨ Security
Description
getPreferredVersionsForUpdateSpecs writes the user-controlled update selector pattern into a plain
object without filtering __proto__/constructor/prototype, so pnpm update [email protected] can
end up mutating Object.prototype. This can corrupt runtime state or crash pnpm during/after
dependency resolution.
Code

pnpm11/installing/commands/src/installDeps.ts[R601-611]

+function getPreferredVersionsForUpdateSpecs (updateSpecs: string[]): PreferredVersions {
+  const preferredVersions: PreferredVersions = {}
+  for (const spec of updateSpecs) {
+    const { pattern, versionSpec } = parseUpdateParam(spec)
+    if (versionSpec == null || pattern.includes('*') || pattern.startsWith('!')) continue
+    // Only an exact version of a single named package can be preferred.
+    const selector = getVersionSelectorType(versionSpec)
+    if (selector?.type !== 'version') continue
+    preferredVersions[pattern] = preferredVersions[pattern] ?? {}
+    preferredVersions[pattern][selector.normalized] = 'version'
+  }
Evidence
The new helper uses a plain object and assigns user-derived keys (pattern) into it, enabling
special-key prototype mutation; pattern comes from parseUpdateParam() which performs only string
slicing and no validation. The same file already includes an explicit prototype-pollution guard for
vulnerability ranges, showing this threat model is relevant here too.

pnpm11/installing/commands/src/installDeps.ts[601-611]
pnpm11/installing/commands/src/recursive.ts[606-618]
pnpm11/installing/commands/src/installDeps.ts[632-635]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`getPreferredVersionsForUpdateSpecs()` builds `preferredVersions` as a plain object and indexes it with `pattern` coming from CLI args. Special keys like `__proto__`, `constructor`, or `prototype` can trigger prototype pollution (including writing onto `Object.prototype`) via the nested assignment.
### Issue Context
`parseUpdateParam()` does not validate/sanitize `pattern`, so this path must defensively guard keys or avoid prototype-bearing objects.
### Fix Focus Areas
- pnpm11/installing/commands/src/installDeps.ts[601-613]
### Suggested fix
1) Build maps with null prototypes:
- `const preferredVersions = Object.create(null) as PreferredVersions`
- for nested maps: `preferredVersions[pattern] ??= Object.create(null) as any`
2) Add explicit key guards before writing:
- Skip/throw if `pattern` is `__proto__`, `constructor`, or `prototype`.
3) (Recommended) Add a regression test that calls update with a selector like `[email protected]` and asserts `({} as any).someInjectedProp` is still `undefined` (i.e., Object.prototype wasn’t polluted).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended
2. Test dist-tag state leak 🐞 Bug ☼ Reliability ⭐ New
Description
The new regression test updates the mock registry's global latest dist-tag for
@pnpm.e2e/dep-of-pkg-with-1-dep and never restores it, so later tests can resolve a different
version depending on execution order. Because the resolver prefers meta['dist-tags'].latest for
* ranges, this can affect many other tests that depend on that fixture package.
Code

pnpm11/installing/commands/test/update/update.ts[R159-165]

+  // 101.0.0 is now the latest, but the update requests 100.1.0, which must win.
+  await addDistTag({ package: '@pnpm.e2e/dep-of-pkg-with-1-dep', version: '101.0.0', distTag: 'latest' })
+
+  await update.handler({
+    ...DEFAULT_OPTS,
+    dir: process.cwd(),
+  }, ['@pnpm.e2e/[email protected]'])
Evidence
The test sets latest to 101.0.0 and does not revert it. addDistTag updates the shared registry
mock via setDistTag, and the resolver explicitly prefers meta['dist-tags'].latest when the range
is '*', so this dist-tag mutation can change resolutions outside this test.

pnpm11/installing/commands/test/update/update.ts[142-172]
pnpm11/testing/registry-mock/src/index.ts[35-57]
pnpm11/resolving/npm-resolver/src/pickPackageFromMeta.ts[172-193]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The added test mutates shared registry mock state by changing the `latest` dist-tag, but doesn't restore it. This can make other tests order-dependent/flaky.

### Issue Context
- `addDistTag()` performs a real authenticated `setDistTag` call against the shared registry mock.
- The npm resolver prefers `dist-tags.latest` for `versionRange === '*'`, so changing `latest` affects unrelated dependency resolutions.

### Fix Focus Areas
- pnpm11/installing/commands/test/update/update.ts[142-172]

### Suggested fix
- Wrap the dist-tag change in a `try/finally` and restore `latest` to the value set earlier in the test (e.g. back to `100.0.0`), or to whatever the suite-wide expected default is.
- Alternatively, avoid touching `latest` by using a dedicated test package/fixture name (if available) so the test doesn't mutate a commonly-used package's dist-tags.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit f4c0211


🐞 Bugs (1) 📘 Rule violations (0) 📜 Skill insights (0)


Action required
1. Update spec prototype pollution 🐞 Bug ⛨ Security
Description
getPreferredVersionsForUpdateSpecs writes the user-controlled update selector pattern into a plain
object without filtering __proto__/constructor/prototype, so pnpm update [email protected] can
end up mutating Object.prototype. This can corrupt runtime state or crash pnpm during/after
dependency resolution.
Code

pnpm11/installing/commands/src/installDeps.ts[R601-611]

+function getPreferredVersionsForUpdateSpecs (updateSpecs: string[]): PreferredVersions {
+  const preferredVersions: PreferredVersions = {}
+  for (const spec of updateSpecs) {
+    const { pattern, versionSpec } = parseUpdateParam(spec)
+    if (versionSpec == null || pattern.includes('*') || pattern.startsWith('!')) continue
+    // Only an exact version of a single named package can be preferred.
+    const selector = getVersionSelectorType(versionSpec)
+    if (selector?.type !== 'version') continue
+    preferredVersions[pattern] = preferredVersions[pattern] ?? {}
+    preferredVersions[pattern][selector.normalized] = 'version'
+  }
Evidence
The new helper uses a plain object and assigns user-derived keys (pattern) into it, enabling
special-key prototype mutation; pattern comes from parseUpdateParam() which performs only string
slicing and no validation. The same file already includes an explicit prototype-pollution guard for
vulnerability ranges, showing this threat model is relevant here too.

pnpm11/installing/commands/src/installDeps.ts[601-611]
pnpm11/installing/commands/src/recursive.ts[606-618]
pnpm11/installing/commands/src/installDeps.ts[632-635]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`getPreferredVersionsForUpdateSpecs()` builds `preferredVersions` as a plain object and indexes it with `pattern` coming from CLI args. Special keys like `__proto__`, `constructor`, or `prototype` can trigger prototype pollution (including writing onto `Object.prototype`) via the nested assignment.

### Issue Context
`parseUpdateParam()` does not validate/sanitize `pattern`, so this path must defensively guard keys or avoid prototype-bearing objects.

### Fix Focus Areas
- pnpm11/installing/commands/src/installDeps.ts[601-613]

### Suggested fix
1) Build maps with null prototypes:
- `const preferredVersions = Object.create(null) as PreferredVersions`
- for nested maps: `preferredVersions[pattern] ??= Object.create(null) as any`

2) Add explicit key guards before writing:
- Skip/throw if `pattern` is `__proto__`, `constructor`, or `prototype`.

3) (Recommended) Add a regression test that calls update with a selector like `[email protected]` and asserts `({} as any).someInjectedProp` is still `undefined` (i.e., Object.prototype wasn’t polluted).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Qodo Logo

Comment on lines +601 to +611
function getPreferredVersionsForUpdateSpecs (updateSpecs: string[]): PreferredVersions {
const preferredVersions: PreferredVersions = {}
for (const spec of updateSpecs) {
const { pattern, versionSpec } = parseUpdateParam(spec)
if (versionSpec == null || pattern.includes('*') || pattern.startsWith('!')) continue
// Only an exact version of a single named package can be preferred.
const selector = getVersionSelectorType(versionSpec)
if (selector?.type !== 'version') continue
preferredVersions[pattern] = preferredVersions[pattern] ?? {}
preferredVersions[pattern][selector.normalized] = 'version'
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. Update spec prototype pollution 🐞 Bug ⛨ Security

getPreferredVersionsForUpdateSpecs writes the user-controlled update selector pattern into a plain
object without filtering __proto__/constructor/prototype, so pnpm update [email protected] can
end up mutating Object.prototype. This can corrupt runtime state or crash pnpm during/after
dependency resolution.
Agent Prompt
### Issue description
`getPreferredVersionsForUpdateSpecs()` builds `preferredVersions` as a plain object and indexes it with `pattern` coming from CLI args. Special keys like `__proto__`, `constructor`, or `prototype` can trigger prototype pollution (including writing onto `Object.prototype`) via the nested assignment.

### Issue Context
`parseUpdateParam()` does not validate/sanitize `pattern`, so this path must defensively guard keys or avoid prototype-bearing objects.

### Fix Focus Areas
- pnpm11/installing/commands/src/installDeps.ts[601-613]

### Suggested fix
1) Build maps with null prototypes:
- `const preferredVersions = Object.create(null) as PreferredVersions`
- for nested maps: `preferredVersions[pattern] ??= Object.create(null) as any`

2) Add explicit key guards before writing:
- Skip/throw if `pattern` is `__proto__`, `constructor`, or `prototype`.

3) (Recommended) Add a regression test that calls update with a selector like `[email protected]` and asserts `({} as any).someInjectedProp` is still `undefined` (i.e., Object.prototype wasn’t polluted).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. Switched getPreferredVersionsForUpdateSpecs to a null-prototype map (Object.create(null)), so a crafted selector like [email protected] becomes a plain key instead of mutating Object.prototype. Added a regression test that runs update with a __proto__@… selector and asserts the prototype is untouched. Done in 662aa70.

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 1, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit f4c0211

@m2na7
m2na7 force-pushed the fix/update-transitive-dependency-version branch from f4c0211 to 662aa70 Compare July 2, 2026 01:59
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 662aa70

1 similar comment
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 662aa70

zkochan added a commit to aqeelat/pnpm that referenced this pull request Jul 4, 2026
pnpm update <dep>@<version> ignored <version> when <dep> exists only as
a transitive dependency: updateMatching only flags a package for
re-resolution and cannot carry a version, so the resolver fell back to
highest-in-range. Adopts the fix from pnpm#12752, reconciled with
the updateRequested preferred-version bypass in this PR:

- The requested version joins preferredVersions as a range selector
  (an exact version is a valid range matching only itself) at a new
  maximum REQUESTED_VERSION_SELECTOR_WEIGHT, instead of a version-type
  pin. version-type selectors are exactly what the updateRequested
  bypass strips for update targets, so a plain pin would be discarded
  and the fix would never fire; range selectors survive by design.
- The install layer now merges caller-supplied preferredVersions over
  the lockfile-derived seed per package name instead of replacing it.
  Replacement would have disabled the unrelated-packages-stay-pinned
  fix (pnpm#10662) whenever a caller passes preferred versions —
  including pnpm audit --fix's vulnerability penalties. The merge
  target is null-prototype so a crafted package name such as
  __proto__ lands as a plain own key.

pacquet (same fix, same encoding):
- UpdateSeedPolicy::DropOnly gains a requested_versions map; the
  versioned-selector/no-direct-match branch of update fills it from
  selectors whose version parses as an exact semver (glob and negated
  patterns excluded).
- install_with_fresh_lockfile folds each requested version into the
  preferred-versions seed as a range selector at
  REQUESTED_VERSION_SELECTOR_WEIGHT.

Tests: the TS e2e regression from pnpm#12752 (explicit in-range
version wins over latest; prototype-pollution guard) plus a pacquet
integration test (update_transitive_to_explicitly_requested_version),
verified to fail with the seed fold disabled.

Closes pnpm#12744.

Co-authored-by: Minha Kang <[email protected]>
@zkochan

zkochan commented Jul 4, 2026

Copy link
Copy Markdown
Member

Thanks for this fix and the clear root-cause analysis! We've folded it into #12558 (with your commits credited via Co-authored-by), because the two changes interact and need to land together:

  1. The updateRequested bypass introduced in fix(resolver): targeted updates resolve exactly like a fresh install #12558 strips version-type preferred selectors for update targets — exactly the selector type this PR used to carry the requested version, so the injected pin would have been discarded and the fix would never fire. In the combined version, the requested version rides a range selector (an exact version is a valid range matching only itself) at a new maximum REQUESTED_VERSION_SELECTOR_WEIGHT, which the bypass preserves by design.
  2. Passing installOpts.preferredVersions made the install layer skip the lockfile-derived seed entirely, which would have re-broken pnpm up -r <package> unexpectedly updates unrelated packages with compatible new versions #10662 (unrelated packages losing their pins) for pnpm update <dep>@<version>. The install layer now merges caller-supplied preferred versions over the lockfile seed per package name.

Your regression tests (including the prototype-pollution guard) are carried over unchanged, and the same fix is also implemented in the Rust pacquet/ stack. Closing this PR in favor of #12558 — #12744 will be closed by that PR.


Written by an agent (Claude Code, claude-fable-5) on behalf of zkochan.

@zkochan zkochan closed this Jul 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pnpm@11 reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pnpm up dep@version does not work on transitive dependencies

2 participants