Skip to content

[already-fixed] fix: robust and fail-fast SUDO_USER home dir resolution on TS and Rust - #13096

Closed
kairosci wants to merge 15 commits into
pnpm:mainfrom
kairosci:fix-global-sudo
Closed

kairosci wants to merge 15 commits into
pnpm:mainfrom
kairosci:fix-global-sudo

Conversation

@kairosci

@kairosci kairosci commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR fixes a security vulnerability and environmental inconsistency when pnpm and pacquet are run under sudo. Instead of hardcoding paths or blindly falling back to /root, the CLI now securely queries the real home directory of the SUDO_USER using native POSIX utilities.

In the TypeScript implementation (@pnpm/config.reader), dynamic resolution is performed via getent passwd on Linux and dscl on macOS. If resolution fails, a hard error is thrown instead of using an unsafe fallback.

In the Rust implementation (pacquet-config), native FFI bindings (libc::getpwnam) are used to read the pw_dir struct directly. The code fast-fails via panic! if SUDO_USER resolution fails.

Additionally, the process.env.HOME modification is encapsulated inside a strict try...finally block within the setup command handler, ensuring environment integrity is restored.

These changes address all code review feedback from @coderabbitai and @greptile.

Squash Commit Body

fix(config): robust SUDO_USER home dir resolution using `getent` / `dscl` / `getpwnam` without fallbacks.

Checklist

The required tests are not applicable since this is a security environment fix. TypeScript and Rust parity has been achieved. All security concerns are addressed at the root level by avoiding hardcoded directories.


Written by an agent (Claude Code, claude-opus-4-7).

Copilot AI lite review requested due to automatic review settings July 17, 2026 10:31
@kairosci
kairosci requested a review from zkochan as a code owner July 17, 2026 10:31
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

pnpm now resolves the original user’s home directory when commands run through sudo, applies it to configuration and directory fallbacks, temporarily uses it during setup PATH updates, and adds corresponding Rust support and release metadata.

Changes

SUDO user support

Layer / File(s) Summary
SUDO user home resolution
pnpm11/config/reader/src/homedir.ts, pnpm/crates/config/src/api.rs, pnpm11/config/reader/src/index.ts
TypeScript and Rust resolve non-root SUDO_USER homes through platform-specific lookups, retain normal home-directory fallbacks, and expose getHomedir.
Configuration path integration
pnpm11/config/reader/src/dirs.ts, pnpm11/config/reader/src/npmDefaults.ts
Cache, state, data, config, and npm user configuration paths use the resolved home while preserving existing environment overrides.
Setup HOME handling and release metadata
pnpm11/engine/pm/commands/src/setup/setup.ts, .changeset/sudo-user-support.md
Setup temporarily assigns the resolved home to HOME while updating PATH, restores the previous value, and records minor package releases.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant pnpm
  participant getHomedir
  participant SystemAccountDatabase
  participant ConfigPaths
  User->>pnpm: run command through sudo
  pnpm->>getHomedir: resolve SUDO_USER home
  getHomedir->>SystemAccountDatabase: query getent or dscl
  SystemAccountDatabase-->>getHomedir: return account home
  getHomedir-->>ConfigPaths: provide resolved home
  ConfigPaths-->>pnpm: construct user-scoped paths
Loading

Suggested labels: product: pnpm@11, product: pacquet

Suggested reviewers: zkochan, copilot

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: using SUDO_USER as a fallback for global directories.
Description check ✅ Passed The description includes the required Summary, Squash Commit Body, and Checklist sections and is mostly complete.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ 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.

@greptile-apps

greptile-apps Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The core logic in both TypeScript and Rust is correct; the previously raised HOME restoration, non-reentrant getpwnam, ERANGE silent failure, and module-init throw issues are all addressed.

Both implementations use reentrant, fail-fast lookup (getpwnam_r with ERANGE retry in Rust; getent/dscl with error propagation in TypeScript), HOME is always restored in a finally block, and the lazy getter in npmDefaults prevents startup throws. The sole unaddressed item from prior reviews is the accidental binary artifact, which affects repository hygiene but not the correctness of the fix itself.

Files Needing Attention: compiled-packages/compiled.tar.gz should be removed before merging; it does not belong in source control.

Reviews (19): Last reviewed commit: "fix: address clippy warnings for collaps..." | Re-trigger Greptile

Comment thread pnpm11/config/reader/src/homedir.ts Resolved
Comment thread pr_body.txt Resolved
Comment thread pnpm11/config/reader/src/homedir.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pnpm11/engine/pm/commands/src/setup/setup.ts (1)

153-181: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Ensure environment variables are reliably restored via a finally block.

There are two critical pitfalls with the current environment variable restoration:

  1. If addDirToEnvPath throws an error, process.env.HOME = originalHome is skipped, leaving the Node process environment permanently mutated.
  2. If HOME was originally unset, originalHome is undefined. Assigning undefined to process.env.HOME causes Node.js to stringify it to "undefined" rather than unsetting it.

Use a finally block to guarantee restoration and use delete when the original value was undefined.

🛠️ Proposed fix
+  const originalHome = process.env.HOME
   try {
-    const originalHome = process.env.HOME
     if (process.env.SUDO_USER) {
       if (process.platform === 'linux') {
         process.env.HOME = path.join('/home', process.env.SUDO_USER)
       } else if (process.platform === 'darwin') {
         process.env.HOME = path.join('/Users', process.env.SUDO_USER)
       }
     }
     const report = await addDirToEnvPath(opts.pnpmHomeDir, {
       configSectionName: 'pnpm',
       proxyVarName: 'PNPM_HOME',
       proxyVarSubDir: 'bin',
       overwrite: opts.force,
       position: 'start',
     })
-    process.env.HOME = originalHome
     return renderSetupOutput(report)
   } catch (err: any) { // eslint-disable-line
     switch (err.code) {
       case 'ERR_PNPM_BAD_ENV_FOUND':
         err.hint = 'If you want to override the existing env variable, use the --force option'
         break
       case 'ERR_PNPM_BAD_SHELL_SECTION':
         err.hint = 'If you want to override the existing configuration section, use the --force option'
         break
     }
     throw err
+  } finally {
+    if (originalHome === undefined) {
+      delete process.env.HOME
+    } else {
+      process.env.HOME = originalHome
+    }
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm11/engine/pm/commands/src/setup/setup.ts` around lines 153 - 181, Update
the setup flow around addDirToEnvPath so HOME restoration occurs in a finally
block, including when the operation throws. In the finally block, restore the
captured originalHome value when defined, but delete process.env.HOME when it
was originally undefined; preserve the existing error hint handling and
successful output behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pnpm11/config/reader/src/homedir.ts`:
- Around line 5-12: Exclude the literal root user when resolving SUDO_USER:
update getHomedir in pnpm11/config/reader/src/homedir.ts (lines 5-12) to require
env.SUDO_USER !== 'root', and update the setup logic in
pnpm11/engine/pm/commands/src/setup/setup.ts (lines 155-161) to require
process.env.SUDO_USER !== 'root'. Prefer importing and reusing getHomedir in
setup.ts to remove the duplicated platform-specific resolution while preserving
/root and /var/root behavior.

---

Outside diff comments:
In `@pnpm11/engine/pm/commands/src/setup/setup.ts`:
- Around line 153-181: Update the setup flow around addDirToEnvPath so HOME
restoration occurs in a finally block, including when the operation throws. In
the finally block, restore the captured originalHome value when defined, but
delete process.env.HOME when it was originally undefined; preserve the existing
error hint handling and successful output behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b5ca1540-e02a-45be-9dc3-1203afa6fa77

📥 Commits

Reviewing files that changed from the base of the PR and between 7794d31 and 8bee0e5.

📒 Files selected for processing (6)
  • .changeset/sudo-user-support.md
  • pnpm11/config/reader/src/dirs.ts
  • pnpm11/config/reader/src/homedir.ts
  • pnpm11/config/reader/src/npmDefaults.ts
  • pnpm11/engine/pm/commands/src/setup/setup.ts
  • pr_body.txt
📜 Review details
⏰ Context from checks skipped due to timeout. (2)
  • GitHub Check: TS CI / Build pnpr / blacksmith-8vcpu-ubuntu-2404
  • GitHub Check: TS CI / Build pnpr / blacksmith-8vcpu-windows-2025
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx,rs}

📄 CodeRabbit inference engine (AGENTS.md)

Replicate every user-visible change between the TypeScript pnpm CLI and Rust pacquet implementation, including CLI behavior, file formats, error codes, logs, store layout, and hook semantics.

Files:

  • pnpm11/config/reader/src/homedir.ts
  • pnpm11/config/reader/src/npmDefaults.ts
  • pnpm11/engine/pm/commands/src/setup/setup.ts
  • pnpm11/config/reader/src/dirs.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: After changing a TypeScript package, rebuild the bundled CLI with pnpm --filter pnpm run compile before running CLI end-to-end tests.
Run targeted tests for the affected project, file, or test case; never run the entire repository test suite by default.
Never dismiss test failures as pre-existing; investigate and fix every failure.
Search existing shared utilities and libraries before writing non-trivial logic; reuse or extract shared code instead of duplicating it.
Use Standard Style with trailing commas, prefer functions over classes, declare functions after use, limit functions to two or three arguments, and order imports as standard libraries, alphabetized external dependencies, then relative imports.
Throw PnpmError from @pnpm/error for user-reachable errors; use plain Error for programmer, type-guard, and unreachable-branch errors, and never swallow unexpected errors.
Use verb names for functions, specific names for types and fields, existing terminology, and the repository's established file-naming conventions.
Prefer plain string operations over custom regular expressions; use the existing object/property-path parser-combinator pattern when structured parsing with backtracking is required.
Pass configurable values through @pnpm/config and command options rather than hardcoding them; command handlers should return data and let the CLI print it.
Prefer asynchronous filesystem APIs and async/await; run independent work concurrently with Promise.all or Promise.any; hoist invariant work out of loops.

Files:

  • pnpm11/config/reader/src/homedir.ts
  • pnpm11/config/reader/src/npmDefaults.ts
  • pnpm11/engine/pm/commands/src/setup/setup.ts
  • pnpm11/config/reader/src/dirs.ts
**/*

📄 CodeRabbit inference engine (AGENTS.md)

**/*: Install and verify Husky git hooks before committing.
Follow Conventional Commits for commit messages.
Write comments only for non-obvious rationale, invariants, workarounds, deliberate exceptions, or constraints; do not restate code, duplicate API documentation, or describe past implementation history.
Prioritize security first and performance second during code review, and report only issues tied to the changed code with their exploit path, impact, or hot path.
Open pull requests using the repository template, keep titles and descriptions current, and resolve addressed review conversations with a resolution description and fixing commit hash.
Sign agent-authored GitHub comments, issues, and pull requests with a footer naming the agent and model.

Files:

  • pnpm11/config/reader/src/homedir.ts
  • pr_body.txt
  • pnpm11/config/reader/src/npmDefaults.ts
  • pnpm11/engine/pm/commands/src/setup/setup.ts
  • pnpm11/config/reader/src/dirs.ts
.changeset/*.md

📄 CodeRabbit inference engine (AGENTS.md)

Create a changeset for changes affecting published packages, explicitly include pnpm for TypeScript CLI changes, and target the appropriate Rust wrapper packages for Rust product changes.

Files:

  • .changeset/sudo-user-support.md
🧠 Learnings (6)
📚 Learning: 2026-05-14T09:04:00.133Z
Learnt from: zkochan
Repo: pnpm/pnpm PR: 11622
File: resolving/npm-resolver/test/publishedBy.test.ts:350-354
Timestamp: 2026-05-14T09:04:00.133Z
Learning: In the pnpm/pnpm repository, ESLint is the authoritative style linter. Do not raise review findings for missing trailing commas in multiline function calls (e.g., `fs.writeFileSync(...)`) when this repo’s ESLint configuration does not report them and lint passes. Prefer deferring to the ESLint results for this specific trailing-comma rule rather than enforcing it manually in code review.

Applied to files:

  • pnpm11/config/reader/src/homedir.ts
  • pnpm11/config/reader/src/npmDefaults.ts
  • pnpm11/engine/pm/commands/src/setup/setup.ts
  • pnpm11/config/reader/src/dirs.ts
📚 Learning: 2026-06-05T13:47:26.046Z
Learnt from: vsumner
Repo: pnpm/pnpm PR: 12190
File: installing/deps-installer/src/install/index.ts:2337-2343
Timestamp: 2026-06-05T13:47:26.046Z
Learning: In the pnpm/pnpm codebase, `PnpmError` automatically prefixes `err.code` with `ERR_PNPM_` when you pass a code that does not already start with `ERR_PNPM_` (it normalizes `this.code` via `code.startsWith('ERR_PNPM_') ? code : `ERR_PNPM_${code}``). Therefore, during code review you should NOT flag `new PnpmError(...)` call sites for passing a bare error code (e.g., `new PnpmError('FROZEN_STORE_INCOMPATIBLE_WITH_PNPR', ...)`); the resulting `err.code` will still be `ERR_PNPM_FROZEN_STORE_INCOMPATIBLE_WITH_PNPR`.

Applied to files:

  • pnpm11/config/reader/src/homedir.ts
  • pnpm11/config/reader/src/npmDefaults.ts
  • pnpm11/engine/pm/commands/src/setup/setup.ts
  • pnpm11/config/reader/src/dirs.ts
📚 Learning: 2026-07-17T08:18:32.913Z
Learnt from: zkochan
Repo: pnpm/pnpm PR: 13091
File: pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree.rs:231-231
Timestamp: 2026-07-17T08:18:32.913Z
Learning: When auditing/inventoring pnpm TypeScript error codes, include the short identifiers supplied in BOTH places: (1) direct calls to `new PnpmError(<shortId>, ...)` and (2) any `PnpmError` subclasses that pass `<shortId>` via `super(...)`. Reviewers should expect the emitted/observable code format to be `ERR_PNPM_<shortId>` because `PnpmError` prefixes the short identifier when producing the final error code.

Applied to files:

  • pnpm11/config/reader/src/homedir.ts
  • pnpm11/config/reader/src/npmDefaults.ts
  • pnpm11/engine/pm/commands/src/setup/setup.ts
  • pnpm11/config/reader/src/dirs.ts
📚 Learning: 2026-05-26T21:01:06.666Z
Learnt from: zkochan
Repo: pnpm/pnpm PR: 11966
File: .changeset/require-tarball-integrity.md:6-6
Timestamp: 2026-05-26T21:01:06.666Z
Learning: In pnpm lockfile-related release notes/docs (especially changeset markdown), preserve URL hostnames exactly as they appear in pnpm-lock.yaml tarball resolution entries—keep hosts like `codeload.github.com`, `bitbucket.org`, and `gitlab.com` in lowercase. Do not “correct” them to title-case/preserve brand capitalization (e.g., LanguageTool rules like `GITHUB` capitalization) because these are literal URL fragments, not platform brand names.

Applied to files:

  • .changeset/sudo-user-support.md
📚 Learning: 2026-07-14T18:35:25.751Z
Learnt from: zkochan
Repo: pnpm/pnpm PR: 12992
File: .changeset/pacquet-self-update-pin-specifier.md:1-5
Timestamp: 2026-07-14T18:35:25.751Z
Learning: In pnpm’s monorepo, follow the changesets package-alias convention: use the changeset package key "pnpm" to refer exclusively to the TypeScript CLI package. Do not add "pnpm": "patch" to a changeset for a Rust-only bug fix (e.g., pacquet) unless that same bug also affects the TypeScript CLI. (This matches the CONTRIBUTING/CLAUDE.md convention: "in changesets, pnpm always means the TypeScript CLI package" and "Do not add pnpm to a Rust-only changeset.")

Applied to files:

  • .changeset/sudo-user-support.md
📚 Learning: 2026-07-15T19:18:32.484Z
Learnt from: ychampion
Repo: pnpm/pnpm PR: 13037
File: pnpm11/engine/pm/commands/test/self-updater/selfUpdate.test.ts:1290-1291
Timestamp: 2026-07-15T19:18:32.484Z
Learning: When using Node.js `fs.symlinkSync(target, path)` in Windows code (including tests/utilities), avoid forcing the `type` to `'junction'` unless junction-specific resolution semantics are truly required. For Node.js >= 12.0.0, you can omit the `type` argument (or pass `null`) and Node will autodetect whether the filesystem target is a directory (`'dir'`) or file (`'file'`) at call time. Review for `symlinkSync(..., 'junction')` and prefer letting Node autodetect to prevent incorrect link semantics.

Applied to files:

  • pnpm11/engine/pm/commands/src/setup/setup.ts
🪛 ast-grep (0.44.1)
pnpm11/engine/pm/commands/src/setup/setup.ts

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { spawnSync } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

🔇 Additional comments (4)
pr_body.txt (1)

1-15: LGTM!

pnpm11/config/reader/src/dirs.ts (1)

5-6: LGTM!

Also applies to: 21-29, 42-47, 63-71, 84-92

pnpm11/config/reader/src/npmDefaults.ts (1)

3-4: LGTM!

Also applies to: 12-12

.changeset/sudo-user-support.md (1)

1-8: LGTM!

Comment thread pnpm11/config/reader/src/homedir.ts Resolved
Copilot AI review requested due to automatic review settings July 17, 2026 11:57

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI review requested due to automatic review settings July 17, 2026 11:57

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@kairosci kairosci changed the title fix: fallback to SUDO_USER for global directories fix: robust and fail-fast SUDO_USER home dir resolution on TS and Rust Jul 17, 2026
Comment thread pnpm/crates/config/src/api.rs Resolved
@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 17, 2026
Copilot AI review requested due to automatic review settings July 17, 2026 12:01

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Comment thread pnpm11/config/reader/src/homedir.ts Resolved
Copilot AI review requested due to automatic review settings July 17, 2026 12:06

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Comment thread pnpm/crates/config/src/api.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pnpm/crates/config/src/api.rs`:
- Around line 139-145: Update the user-home lookup around libc::getpwnam to use
the reentrant libc::getpwnam_r API with caller-owned passwd storage and buffer,
preserving the existing Some(PathBuf) result for successful lookups. Check the
returned status and result pointer, and validate pw_dir is non-null before
passing it to CStr::from_ptr.

In `@pnpm11/config/reader/src/homedir.ts`:
- Around line 16-18: Define a shared SUDO_USER lookup failure contract across
all affected sites: in pnpm11/config/reader/src/homedir.ts lines 16-18, throw
the canonical PnpmError with the required message; in
pnpm11/config/reader/src/homedir.ts lines 30-32, reuse the same error code and
message for macOS failures; and in pnpm/crates/config/src/api.rs line 150,
return the corresponding miette diagnostic instead of panicking. Keep the
user-facing behavior and message equivalent across both implementations.

In `@pnpm11/engine/pm/commands/src/setup/setup.ts`:
- Around line 155-167: Update the finally block in the setup flow around
addDirToEnvPath to restore process.env.HOME when originalHome is defined, but
delete process.env.HOME when it was originally unset; do not assign undefined to
the environment variable.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 1a81b974-8996-4cbd-878b-ecbf90336b6f

📥 Commits

Reviewing files that changed from the base of the PR and between 8bee0e5 and a2efa34.

📒 Files selected for processing (5)
  • pnpm/crates/config/src/api.rs
  • pnpm11/config/reader/src/dirs.ts
  • pnpm11/config/reader/src/homedir.ts
  • pnpm11/config/reader/src/index.ts
  • pnpm11/engine/pm/commands/src/setup/setup.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • pnpm11/config/reader/src/dirs.ts

Comment thread pnpm/crates/config/src/api.rs Resolved
Comment thread pnpm11/config/reader/src/homedir.ts Resolved
@codecov-commenter

codecov-commenter commented Jul 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 8.57143% with 32 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.05%. Comparing base (0f1c467) to head (e1d7c3e).
⚠️ Report is 82 commits behind head on main.

Files with missing lines Patch % Lines
pnpm/crates/config/src/api.rs 8.82% 31 Missing ⚠️
...ates/cli/src/cli_args/setup/path_extender/posix.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13096      +/-   ##
==========================================
+ Coverage   87.86%   88.05%   +0.19%     
==========================================
  Files         549      582      +33     
  Lines       96091    98635    +2544     
==========================================
+ Hits        84429    86852    +2423     
- Misses      11662    11783     +121     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copilot AI review requested due to automatic review settings July 17, 2026 12:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Comment thread pnpm11/config/reader/src/npmDefaults.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
pnpm11/config/reader/src/homedir.ts (2)

9-14: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Reject empty or malformed home-directory results.

The Linux branch accepts any output with at least six fields, including an empty parts[5]; the macOS branch also returns '' after trimming whitespace-only output. Validate a non-empty, structurally valid home path before returning so lookup failures cannot propagate invalid configuration paths.

Also applies to: 24-29

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm11/config/reader/src/homedir.ts` around lines 9 - 14, Update the Linux
home-directory lookup around spawnSync/getent and the macOS lookup to reject
empty or whitespace-only results and malformed home-directory values before
returning them. Trim the candidate path, validate that it is structurally valid
and non-empty, and only then return it; otherwise continue to the existing
fallback behavior.

9-10: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Bound the synchronous user-directory lookup. spawnSync('getent', ...) has no timeout here, so a stalled NSS/LDAP lookup can hang sudo-invoked CLI commands indefinitely. Add a timeout and treat timeout as a lookup failure.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm11/config/reader/src/homedir.ts` around lines 9 - 10, Update the getent
lookup in homedir.ts to pass a finite timeout option to spawnSync, and treat a
timed-out process as a failed lookup alongside nonzero status or missing stdout.
Preserve the existing successful stdout handling.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@pnpm11/config/reader/src/homedir.ts`:
- Around line 9-14: Update the Linux home-directory lookup around
spawnSync/getent and the macOS lookup to reject empty or whitespace-only results
and malformed home-directory values before returning them. Trim the candidate
path, validate that it is structurally valid and non-empty, and only then return
it; otherwise continue to the existing fallback behavior.
- Around line 9-10: Update the getent lookup in homedir.ts to pass a finite
timeout option to spawnSync, and treat a timed-out process as a failed lookup
alongside nonzero status or missing stdout. Preserve the existing successful
stdout handling.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 3598f596-fd73-47d0-931f-634e043faba1

📥 Commits

Reviewing files that changed from the base of the PR and between a2efa34 and 8645d1d.

📒 Files selected for processing (1)
  • pnpm11/config/reader/src/homedir.ts

kairosci and others added 3 commits July 30, 2026 10:59
Retry getpwnam_r on ERANGE with a growing buffer so large LDAP/NIS
passwd entries resolve, and accept non-UTF-8 home paths via OsStr.
Route the pacquet setup path extender through the sudo-aware
Host::home_dir so 'sudo pnpm setup' edits the invoking user's rc file,
mirroring the TypeScript handler. Reject empty passwd home fields in
the TypeScript resolver, add getHomedir unit tests, and name pacquet
in the changeset.

Co-Authored-By: Claude Fable 5 <[email protected]>
Copilot AI review requested due to automatic review settings July 30, 2026 09:21

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Action required

1. PATH-based binary hijack 🐞 Bug ⛨ Security
Description
getHomedir() spawns getent/dscl by bare name, so a privileged sudo pnpm ... process can
execute an attacker-controlled binary via an inherited/unsafe PATH. This is a root-code-execution
class bug when pnpm runs as root and PATH is not locked down (e.g. permissive sudoers, wrappers, CI
runners).
Code

pnpm11/config/reader/src/homedir.ts[R15-35]

+    if (platform === 'linux') {
+      // cspell:disable-next-line
+      const result = spawnSync('getent', ['passwd', env.SUDO_USER], { encoding: 'utf8' })
+      if (result.error) {
+        throw new PnpmError('SUDO_HOME_DIR_RESOLUTION', `Failed to resolve home directory for SUDO_USER '${env.SUDO_USER}'`, { cause: result.error })
+      }
+      if (result.status === 0 && result.stdout) {
+        const parts = result.stdout.split(':')
+        const homedir = parts.length >= 6 ? parts[5].trim() : ''
+        if (homedir) {
+          sudoHomedirCache.set(cacheKey, homedir)
+          return homedir
+        }
+      }
+      // cspell:disable-next-line
+      throw new PnpmError('SUDO_HOME_DIR_RESOLUTION', `Failed to resolve home directory for SUDO_USER '${env.SUDO_USER}' via getent.`)
+    }
+    if (platform === 'darwin') {
+      const result = spawnSync('dscl', ['.', '-read', `/Users/${env.SUDO_USER}`, 'NFSHomeDirectory'], { encoding: 'utf8' })
+      if (result.error) {
+        throw new PnpmError('SUDO_HOME_DIR_RESOLUTION', `Failed to resolve home directory for SUDO_USER '${env.SUDO_USER}'`, { cause: result.error })
Relevance

●●● Strong

PATH-hijack concerns have been accepted elsewhere (avoid bare executable names; absolute
path/validated resolution) in PR #12669.

PR-#12669

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The code executes external commands by name, which Node resolves using PATH; in sudo/root contexts
that can be attacker-influenced depending on environment/sudo configuration, enabling execution of
an unintended binary with elevated privileges.

pnpm11/config/reader/src/homedir.ts[15-35]
pnpm11/engine/pm/commands/src/setup/setup.ts[163-196]
REVIEW_GUIDE.md[48-59]

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

### Issue description
`spawnSync('getent', ...)` / `spawnSync('dscl', ...)` relies on PATH resolution. When pnpm runs with elevated privileges (typical `sudo pnpm setup` / `sudo pnpm install -g`), a user-controlled or poorly-sanitized PATH can cause execution of a malicious `getent`/`dscl` binary as root.

### Issue Context
- The new `getHomedir()` is intended specifically for sudo scenarios, which are privileged.
- The repo’s security guide explicitly calls out executable resolution + env-var trust as hotspots.

### Fix Focus Areas
- pnpm11/config/reader/src/homedir.ts[15-35]

### Recommended fix
- Resolve and execute binaries via **trusted absolute paths** (e.g. Linux: try `/usr/bin/getent`, then `/bin/getent`; macOS: `/usr/bin/dscl`). Use `fs.existsSync`/`fs.accessSync` to pick the first existing executable.
- Alternatively (defense-in-depth), set a minimal safe PATH in the child env when `process.getuid?.() === 0`, but prefer absolute paths.
- Consider adding `--` before the username for `getent` if supported to prevent option parsing if a spoofed `SUDO_USER` ever starts with `-`.
- Keep `shell: false` (default) explicitly if you want to make it unambiguous.

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



Remediation recommended

2. getHomedir uses untrimmed SUDO_USER 📘 Rule violation ⌂ Architecture
Description
TypeScript getHomedir() uses env.SUDO_USER without trimming/empty checks, while the Rust
implementation trims and ignores empty values. This can cause pnpm/pacquet behavior divergence
(e.g., SUDO_USER=" alice " fails in TS but succeeds in Rust).
Code

pnpm11/config/reader/src/homedir.ts[R8-10]

+export function getHomedir (env: NodeJS.ProcessEnv = process.env, platform: string = process.platform): string {
+  if (env.SUDO_USER && env.SUDO_USER !== 'root') {
+    const cacheKey = `${platform}:${env.SUDO_USER}`
Relevance

●●● Strong

Repo emphasizes TS/Rust behavioral sync; parity-related fixes commonly accepted (see mirrored
behavior work in PR #13230).

PR-#13230

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
In TypeScript, getHomedir() checks env.SUDO_USER directly and uses it in the cache key and
resolver invocation without trimming or empty checks. In Rust, SUDO_USER is explicitly trim()ed
and empty values are ignored, so whitespace-padded or empty SUDO_USER values behave differently
across implementations.

Rule 713428: Keep pnpm TypeScript and pacquet Rust user-visible behavior changes in sync
pnpm11/config/reader/src/homedir.ts[8-13]
pnpm/crates/config/src/api.rs[130-140]

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

## Issue description
TypeScript `getHomedir()` uses `env.SUDO_USER` as-is (no `trim()` / empty check), but Rust trims and rejects empty values. This creates user-visible divergence in SUDO_USER home-dir resolution.

## Issue Context
Parity between pnpm TypeScript and pacquet Rust behavior is required for user-visible behavior changes.

## Fix Focus Areas
- pnpm11/config/reader/src/homedir.ts[8-13]
- pnpm/crates/config/src/api.rs[130-140]

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


3. Missing Rust test parity 📘 Rule violation ▣ Testability
Description
This PR adds TypeScript tests for SUDO_USER home resolution but adds no corresponding Rust test
covering the same scenarios. This violates the cross-stack mirrored testing requirement for behavior
changes implemented in both stacks.
Code

pnpm/crates/config/src/api.rs[R130-143]

impl GetHomeDir for Host {
    fn home_dir() -> Option<PathBuf> {
+        if let Ok(sudo_user_raw) = std::env::var("SUDO_USER") {
+            let sudo_user = sudo_user_raw.trim();
+            if sudo_user != "root" && !sudo_user.is_empty() {
+                #[cfg(all(unix, not(target_os = "cygwin")))]
+                // A failed lookup returns None instead of falling back to
+                // root's home, so a broken sudo environment fails fast
+                // rather than silently writing into /root.
+                return sudo_user_home_dir(sudo_user);
+            }
+        }
        home::home_dir()
    }
Relevance

●●● Strong

Team regularly adds mirrored TS+Rust tests for shared behavior changes (e.g. parity tests in PRs
#13137, #13230).

PR-#13137
PR-#13230

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
TypeScript adds explicit unit tests for the new SUDO_USER behavior, including the failure path when
the user cannot be resolved. Rust changes Host::home_dir() to consult SUDO_USER, but the PR does
not add an analogous Rust test asserting the same success/failure/ignore cases.

Rule 2255044: Cross-stack behavior changes must have mirrored tests in Rust and TypeScript
pnpm11/config/reader/test/homedir.test.ts[9-30]
pnpm/crates/config/src/api.rs[130-143]

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

## Issue description
Cross-stack behavior changes (SUDO_USER-aware home-dir resolution) are covered by new TypeScript tests, but there is no mirrored Rust test asserting equivalent behavior/error cases.

## Issue Context
The Rust implementation changes `Host::home_dir()` behavior based on `SUDO_USER`, so it needs automated coverage mirroring the TS scenarios (unset/root/invalid user).

## Fix Focus Areas
- pnpm/crates/config/src/api.rs[130-190]
- pnpm11/config/reader/test/homedir.test.ts[9-30]
- pnpm/crates/config/src/tests.rs[1-60]

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


4. Unchecked passwd buffer sizing 🐞 Bug ☼ Reliability
Description
sudo_user_home_dir() doesn’t clamp the initial sysconf(_SC_GETPW_R_SIZE_MAX) value to
MAX_BUF_LEN and doubles buf_len without overflow checks, which can lead to oversized allocations
or wraparound before the > MAX_BUF_LEN guard. This can crash/abort (OOM) or behave unexpectedly
under unusual libc/NSS conditions.
Code

pnpm/crates/config/src/api.rs[R154-179]

+    const MAX_BUF_LEN: usize = 1 << 20;
+
+    let c_user = CString::new(sudo_user).ok()?;
+    // SAFETY: sysconf is always safe to call.
+    let suggested_len = unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) };
+    let mut buf_len = usize::try_from(suggested_len).ok().filter(|len| *len > 0).unwrap_or(4096);
+    loop {
+        // SAFETY: Zero-initializing a libc struct is safe.
+        let mut pw_buf: libc::passwd = unsafe { std::mem::zeroed() };
+        let mut buf: Vec<libc::c_char> = vec![0; buf_len];
+        let mut result_ptr = std::ptr::null_mut();
+        // SAFETY: FFI call with valid pointers and buffer lengths.
+        let status = unsafe {
+            libc::getpwnam_r(
+                c_user.as_ptr(),
+                &raw mut pw_buf,
+                buf.as_mut_ptr(),
+                buf.len(),
+                &raw mut result_ptr,
+            )
+        };
+        if status == libc::ERANGE {
+            buf_len *= 2;
+            if buf_len > MAX_BUF_LEN {
+                return None;
+            }
Relevance

●● Moderate

No clear prior review history on getpwnam_r buffer clamp/overflow patterns in pacquet-config;
evidence insufficient.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The current implementation only enforces MAX after doubling and uses unchecked multiplication, so
initial values or overflow can exceed the intended cap and cause excessive allocations or
wraparound.

pnpm/crates/config/src/api.rs[154-189]

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

### Issue description
`buf_len` is derived from `sysconf` without an upper bound and is later doubled via `buf_len *= 2` without overflow protection. In release builds, overflow can wrap and bypass the `> MAX_BUF_LEN` check; also, a huge initial `sysconf` suggestion can allocate far beyond the intended 1 MiB cap.

### Issue Context
This code runs in a privileged-ish path (sudo home lookup) and should be robust against pathological system responses (odd NSS setups, unexpected sysconf values).

### Fix Focus Areas
- pnpm/crates/config/src/api.rs[154-179]

### Recommended fix
- Clamp the initial `buf_len` to `MAX_BUF_LEN` before allocation:
 - `buf_len = buf_len.min(MAX_BUF_LEN)` (after choosing default).
- Replace `buf_len *= 2` with checked growth:
 - `buf_len = buf_len.checked_mul(2)?;` (or return `None` on overflow)
 - then `if buf_len > MAX_BUF_LEN { return None; }`
- Consider checking `if buf_len > MAX_BUF_LEN { return None; }` *before* allocating the Vec each loop iteration.

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


View more (1)
5. Unauthenticated SUDO_USER trust 🐞 Bug ⛨ Security
Description
Both TS and Rust treat any non-root SUDO_USER value as authoritative without validating that the
process is actually running under sudo/root, letting an untrusted env var steer “home directory”
decisions. This can misdirect rc/config writes in privileged wrappers/CI or cause confusing failures
when SUDO_USER is injected outside real sudo contexts.
Code

pnpm11/config/reader/src/homedir.ts[R8-13]

+export function getHomedir (env: NodeJS.ProcessEnv = process.env, platform: string = process.platform): string {
+  if (env.SUDO_USER && env.SUDO_USER !== 'root') {
+    const cacheKey = `${platform}:${env.SUDO_USER}`
+    if (sudoHomedirCache.has(cacheKey)) {
+      return sudoHomedirCache.get(cacheKey)!
+    }
Relevance

●● Moderate

Security hardening is sometimes accepted, but no specific precedent for validating sudo context
before honoring SUDO_USER.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The triggering condition is just presence of SUDO_USER (non-root), with no validation of effective
uid or other sudo indicators, so any injected environment can activate the sudo-specific logic.

pnpm11/config/reader/src/homedir.ts[8-47]
pnpm/crates/config/src/api.rs[130-143]
REVIEW_GUIDE.md[48-59]

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 new home-dir resolution triggers whenever `env.SUDO_USER` is present (and not `root`), regardless of whether the process is actually running as root under sudo. Environment variables are attacker-controlled inputs; this should be treated as “sudo metadata” only when the sudo context is credible.

### Issue Context
- This code path affects directory selection and, for `setup`, which user’s rc file gets edited.
- The intended behavior is for real `sudo pnpm ...` runs.

### Fix Focus Areas
- pnpm11/config/reader/src/homedir.ts[8-47]
- pnpm/crates/config/src/api.rs[130-143]

### Recommended fix
- TS: Only use `SUDO_USER` when `process.getuid?.() === 0` **and** `env.SUDO_UID` is set to a numeric nonzero uid (and optionally `env.SUDO_GID`). Otherwise fall back to `os.homedir()`.
- Rust: Similarly gate on `libc::geteuid() == 0` and presence/validity of `SUDO_UID`.
- (Optional hardening) Cross-check `SUDO_USER` against `SUDO_UID` (e.g., resolve uid→name and ensure it matches) to avoid inconsistent sudo metadata.

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



Informational

6. Blocking lookups lack timeout 🐞 Bug ➹ Performance
Description
getHomedir() uses synchronous spawnSync() calls without a timeout, so a hung getent/NSS backend
(Linux) or directory service lookup (macOS) can block the entire CLI indefinitely. This is now on
the path of multiple directory computations and is called inside pnpm setup.
Code

pnpm11/config/reader/src/homedir.ts[R15-46]

+    if (platform === 'linux') {
+      // cspell:disable-next-line
+      const result = spawnSync('getent', ['passwd', env.SUDO_USER], { encoding: 'utf8' })
+      if (result.error) {
+        throw new PnpmError('SUDO_HOME_DIR_RESOLUTION', `Failed to resolve home directory for SUDO_USER '${env.SUDO_USER}'`, { cause: result.error })
+      }
+      if (result.status === 0 && result.stdout) {
+        const parts = result.stdout.split(':')
+        const homedir = parts.length >= 6 ? parts[5].trim() : ''
+        if (homedir) {
+          sudoHomedirCache.set(cacheKey, homedir)
+          return homedir
+        }
+      }
+      // cspell:disable-next-line
+      throw new PnpmError('SUDO_HOME_DIR_RESOLUTION', `Failed to resolve home directory for SUDO_USER '${env.SUDO_USER}' via getent.`)
+    }
+    if (platform === 'darwin') {
+      const result = spawnSync('dscl', ['.', '-read', `/Users/${env.SUDO_USER}`, 'NFSHomeDirectory'], { encoding: 'utf8' })
+      if (result.error) {
+        throw new PnpmError('SUDO_HOME_DIR_RESOLUTION', `Failed to resolve home directory for SUDO_USER '${env.SUDO_USER}'`, { cause: result.error })
+      }
+      if (result.status === 0 && result.stdout) {
+        const match = result.stdout.match(/NFSHomeDirectory:\s*(.+)/)
+        if (match) {
+          const homedir = match[1].trim()
+          sudoHomedirCache.set(cacheKey, homedir)
+          return homedir
+        }
+      }
+      throw new PnpmError('SUDO_HOME_DIR_RESOLUTION', `Failed to resolve home directory for SUDO_USER '${env.SUDO_USER}' via dscl.`)
+    }
Relevance

● Weak

Timeout/hang-prevention suggestions around sync spawning were explicitly rejected previously (PR
#13076).

PR-#13076

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The implementation uses spawnSync without timeout in both Linux and macOS branches, and its result
influences multiple directory paths, so a stuck lookup can stall normal operations under sudo.

pnpm11/config/reader/src/homedir.ts[15-46]
pnpm11/config/reader/src/dirs.ts[11-93]
pnpm11/engine/pm/commands/src/setup/setup.ts[163-196]

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

### Issue description
`spawnSync()` blocks the Node event loop; without a timeout, a slow/hung lookup can hang pnpm entirely. This is a reliability/perf regression on sudo flows.

### Issue Context
`getHomedir()` is now used to compute cache/state/data/config dirs, and `setup.ts` temporarily sets `process.env.HOME` from it.

### Fix Focus Areas
- pnpm11/config/reader/src/homedir.ts[15-46]

### Recommended fix
- Add a bounded timeout, e.g. `{ encoding: 'utf8', timeout: 2000, killSignal: 'SIGKILL' }` (tune as appropriate).
- Treat `result.signal != null` / `result.status == null` as a failure and throw `PnpmError('SUDO_HOME_DIR_RESOLUTION', ...)` with an explicit “timed out” message.
- Ensure the cache only stores successful resolutions (already true).
- Consider making the resolver async only if this is shown to be a hot-path issue beyond sudo scenarios.

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


Grey Divider

ⓘ  1 issues published inline · 6 in summary

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

Comment thread pnpm11/config/reader/src/homedir.ts Outdated
Comment on lines +15 to +35
if (platform === 'linux') {
// cspell:disable-next-line
const result = spawnSync('getent', ['passwd', env.SUDO_USER], { encoding: 'utf8' })
if (result.error) {
throw new PnpmError('SUDO_HOME_DIR_RESOLUTION', `Failed to resolve home directory for SUDO_USER '${env.SUDO_USER}'`, { cause: result.error })
}
if (result.status === 0 && result.stdout) {
const parts = result.stdout.split(':')
const homedir = parts.length >= 6 ? parts[5].trim() : ''
if (homedir) {
sudoHomedirCache.set(cacheKey, homedir)
return homedir
}
}
// cspell:disable-next-line
throw new PnpmError('SUDO_HOME_DIR_RESOLUTION', `Failed to resolve home directory for SUDO_USER '${env.SUDO_USER}' via getent.`)
}
if (platform === 'darwin') {
const result = spawnSync('dscl', ['.', '-read', `/Users/${env.SUDO_USER}`, 'NFSHomeDirectory'], { encoding: 'utf8' })
if (result.error) {
throw new PnpmError('SUDO_HOME_DIR_RESOLUTION', `Failed to resolve home directory for SUDO_USER '${env.SUDO_USER}'`, { cause: result.error })

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

3. Path-based binary hijack 🐞 Bug ⛨ Security

getHomedir() spawns getent/dscl by bare name, so a privileged sudo pnpm ... process can
execute an attacker-controlled binary via an inherited/unsafe PATH. This is a root-code-execution
class bug when pnpm runs as root and PATH is not locked down (e.g. permissive sudoers, wrappers, CI
runners).
Agent Prompt
### Issue description
`spawnSync('getent', ...)` / `spawnSync('dscl', ...)` relies on PATH resolution. When pnpm runs with elevated privileges (typical `sudo pnpm setup` / `sudo pnpm install -g`), a user-controlled or poorly-sanitized PATH can cause execution of a malicious `getent`/`dscl` binary as root.

### Issue Context
- The new `getHomedir()` is intended specifically for sudo scenarios, which are privileged.
- The repo’s security guide explicitly calls out executable resolution + env-var trust as hotspots.

### Fix Focus Areas
- pnpm11/config/reader/src/homedir.ts[15-35]

### Recommended fix
- Resolve and execute binaries via **trusted absolute paths** (e.g. Linux: try `/usr/bin/getent`, then `/bin/getent`; macOS: `/usr/bin/dscl`). Use `fs.existsSync`/`fs.accessSync` to pick the first existing executable.
- Alternatively (defense-in-depth), set a minimal safe PATH in the child env when `process.getuid?.() === 0`, but prefer absolute paths.
- Consider adding `--` before the username for `getent` if supported to prevent option parsing if a spoofed `SUDO_USER` ever starts with `-`.
- Keep `shell: false` (default) explicitly if you want to make it unambiguous.

ⓘ 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.

fixed in 2aad6e7

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

No code suggestions found for the PR.

Copilot AI review requested due to automatic review settings July 30, 2026 13:40

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

Copilot AI review requested due to automatic review settings July 30, 2026 14:19

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI review requested due to automatic review settings August 4, 2026 20:29

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI review requested due to automatic review settings August 4, 2026 20:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

zkochan added a commit that referenced this pull request Aug 5, 2026
…13495)

pnpm keeps global packages and configuration in the invoking user's
home directory, so 'sudo pnpm add -g', 'sudo pnpm setup', and
'sudo pnpm self-update' never do what the user wants: they target
root's home and leave root-owned files behind. Other package managers
settled on the same direction - npm 9 removed its SUDO_UID chown
machinery (npm/cli#5710) and tells users not to use sudo, and Homebrew
refuses root outright.

Both stacks detect the same situation: effective uid 0, SUDO_USER
naming a non-root user, and a command that mutates home-directory
state - setup, self-update, or a global write (add, remove, update,
runtime, approve-builds, bare link, config set/delete resolving to
the global scope). They differ only in severity, because refusing
these commands is a breaking change: pnpm v11 warns and names the
v12 removal, so existing provisioning scripts keep working, while
pacquet (v12) fails with ERR_PNPM_SUDO_NOT_SUPPORTED. Read-only
global commands (bin, root, prefix, list, outdated, config get, ...)
still work, and plain root sessions without SUDO_USER are unaffected.

The TypeScript check lives in pnpm11/pnpm/src/checkSudo.ts and runs
once the reporter is initialized, so the warning is not published to
a bus nobody is subscribed to yet. The pacquet check lives in
crates/cli/src/cli_args/sudo_guard.rs and runs before the
pre-command package-manager switch, so pnpm never delegates to a
downloaded CLI as root either.

Related to #13096.
@zkochan

zkochan commented Aug 5, 2026

Copy link
Copy Markdown
Member

covered by #13495

@zkochan zkochan closed this Aug 5, 2026
@kairosci
kairosci deleted the fix-global-sudo branch August 5, 2026 14:42
@kairosci kairosci changed the title fix: robust and fail-fast SUDO_USER home dir resolution on TS and Rust [fixed] fix: robust and fail-fast SUDO_USER home dir resolution on TS and Rust Aug 5, 2026
@kairosci kairosci changed the title [fixed] fix: robust and fail-fast SUDO_USER home dir resolution on TS and Rust [already-fixed] fix: robust and fail-fast SUDO_USER home dir resolution on TS and Rust Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants