Repository navigation
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughpnpm now resolves the original user’s home directory when commands run through ChangesSUDO user support
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
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Confidence Score: 5/5The 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 |
There was a problem hiding this comment.
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 winEnsure environment variables are reliably restored via a
finallyblock.There are two critical pitfalls with the current environment variable restoration:
- If
addDirToEnvPaththrows an error,process.env.HOME = originalHomeis skipped, leaving the Node process environment permanently mutated.- If
HOMEwas originally unset,originalHomeisundefined. Assigningundefinedtoprocess.env.HOMEcauses Node.js to stringify it to"undefined"rather than unsetting it.Use a
finallyblock to guarantee restoration and usedeletewhen the original value wasundefined.🛠️ 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
📒 Files selected for processing (6)
.changeset/sudo-user-support.mdpnpm11/config/reader/src/dirs.tspnpm11/config/reader/src/homedir.tspnpm11/config/reader/src/npmDefaults.tspnpm11/engine/pm/commands/src/setup/setup.tspr_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.tspnpm11/config/reader/src/npmDefaults.tspnpm11/engine/pm/commands/src/setup/setup.tspnpm11/config/reader/src/dirs.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
**/*.{ts,tsx}: After changing a TypeScript package, rebuild the bundled CLI withpnpm --filter pnpm run compilebefore 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.
ThrowPnpmErrorfrom@pnpm/errorfor user-reachable errors; use plainErrorfor 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 existingobject/property-pathparser-combinator pattern when structured parsing with backtracking is required.
Pass configurable values through@pnpm/configand command options rather than hardcoding them; command handlers should return data and let the CLI print it.
Prefer asynchronous filesystem APIs andasync/await; run independent work concurrently withPromise.allorPromise.any; hoist invariant work out of loops.
Files:
pnpm11/config/reader/src/homedir.tspnpm11/config/reader/src/npmDefaults.tspnpm11/engine/pm/commands/src/setup/setup.tspnpm11/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.tspr_body.txtpnpm11/config/reader/src/npmDefaults.tspnpm11/engine/pm/commands/src/setup/setup.tspnpm11/config/reader/src/dirs.ts
.changeset/*.md
📄 CodeRabbit inference engine (AGENTS.md)
Create a changeset for changes affecting published packages, explicitly include
pnpmfor 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.tspnpm11/config/reader/src/npmDefaults.tspnpm11/engine/pm/commands/src/setup/setup.tspnpm11/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.tspnpm11/config/reader/src/npmDefaults.tspnpm11/engine/pm/commands/src/setup/setup.tspnpm11/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.tspnpm11/config/reader/src/npmDefaults.tspnpm11/engine/pm/commands/src/setup/setup.tspnpm11/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!
There was a problem hiding this comment.
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
📒 Files selected for processing (5)
pnpm/crates/config/src/api.rspnpm11/config/reader/src/dirs.tspnpm11/config/reader/src/homedir.tspnpm11/config/reader/src/index.tspnpm11/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
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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 winReject 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 winBound 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
📒 Files selected for processing (1)
pnpm11/config/reader/src/homedir.ts
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]>
Code Review by Qodo
Context used✅ Compliance rules (platform):
24 rules 1. PATH-based binary hijack
|
| 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 }) |
There was a problem hiding this comment.
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
PR Code Suggestions ✨Warning
No code suggestions found for the PR. |
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
fd3d07f to
6a0448f
Compare
…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.
|
covered by #13495 |
Summary
This PR fixes a security vulnerability and environmental inconsistency when
pnpmandpacquetare run undersudo. Instead of hardcoding paths or blindly falling back to/root, the CLI now securely queries the real home directory of theSUDO_USERusing native POSIX utilities.In the TypeScript implementation (
@pnpm/config.reader), dynamic resolution is performed viagetent passwdon Linux anddsclon 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 thepw_dirstruct directly. The code fast-fails viapanic!ifSUDO_USERresolution fails.Additionally, the
process.env.HOMEmodification is encapsulated inside a stricttry...finallyblock within thesetupcommand handler, ensuring environment integrity is restored.These changes address all code review feedback from
@coderabbitaiand@greptile.Squash Commit Body
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).