Skip to content

fix(config): allow tokenHelper to be set in the global auth.ini - #12833

Merged
zkochan merged 8 commits into
pnpm:mainfrom
kyungseopk1m:fix/tokenhelper-allow-global-auth-ini
Jul 13, 2026
Merged

zkochan merged 8 commits into
pnpm:mainfrom
kyungseopk1m:fix/tokenhelper-allow-global-auth-ini

Conversation

@kyungseopk1m

@kyungseopk1m kyungseopk1m commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

What

Allow a tokenHelper configured in the global pnpm auth.ini to be used, instead of rejecting it as project-level configuration.

Closes #12759.

Why

The guard that blocks tokenHelper from a project .npmrc (so a checked-in .npmrc can't run an arbitrary command) validated the helper against userConfig, which only contains ~/.npmrc. But pnpm config set writes a tokenHelper to the global auth.ini, which flows into trustedConfig, not userConfig. As a result a legitimately configured tokenHelper was rejected on every command with ERR_PNPM_TOKEN_HELPER_IN_PROJECT_CONFIG, and pnpm config delete failed as well. The guard's own comment already says the helper may come from "~/.npmrc or global auth.ini".

How

Validate against trustedConfig instead of userConfig. trustedConfig merges the trusted sources (including ~/.npmrc and the global auth.ini) but excludes workspace and project .npmrc files, so the global helper is accepted while a project-level one is still rejected.

Tests in config/reader cover both paths: a tokenHelper in the global auth.ini is honored, and a tokenHelper in a project .npmrc still throws ERR_PNPM_TOKEN_HELPER_IN_PROJECT_CONFIG.

Pacquet parity

Pacquet had no tokenHelper support at all, so this PR also ports the whole feature to the Rust stack (matching the cardinal rule that user-visible changes land in both stacks):

  • Config layer (pnpm/crates/config): parse //host/:tokenHelper (scoped and default forms too) from trusted .npmrc / auth.ini sources only; reject a project/workspace helper via the same full-vs-trusted comparison used on the TypeScript side; and reject reserved characters — surfacing the same ERR_PNPM_TOKEN_HELPER_IN_PROJECT_CONFIG / ERR_PNPM_TOKEN_HELPER_UNSUPPORTED_CHARACTER codes.
  • Network layer (pnpm/crates/network): AuthHeaders carries the un-executed command per registry and runs it lazily on lookup, memoized (runs at most once, and never for a command that makes no matching request). Baked headers keep their eager, lock-free hot path; a header is emitted only on success, so a failing helper sends no credential.
  • Known divergence: because AuthHeaders::for_url is infallible and there is no single network seam, a helper failure surfaces as a loud error plus an unauthenticated request rather than pnpm's hard whole-command abort.
  • Known divergence — execution timing: pnpm runs every configured registry's tokenHelper when it builds the auth-header lookup (so a helper for a registry never contacted still runs); pacquet runs each helper lazily on the first request to that registry (per-registry, memoized, and never on a command that makes no matching request). Both bound execution at 60s.

Covered by new Rust unit + integration tests (parse, trust guard, reserved-char, env-drop, lazy execution / memoization, and an end-to-end /bin/echo run).


Pacquet port added by an agent (Claude Code, claude-opus-4-8).

Summary by CodeRabbit

  • Bug Fixes
    • tokenHelper from the user’s global pnpm auth.ini is now trusted, while project/workspace .npmrc tokenHelper values remain blocked.
    • tokenHelper execution is lazy and registry-scoped, rejects unsupported inputs, and now has a 60-second timeout.
  • New Features
    • Pacquet gained “minor” tokenHelper support for retrieving registry tokens on demand.
  • Tests
    • Added/expanded coverage for global accept vs project reject, lazy execution + memoization, reserved-character rejection, URL-scoped env ignoring, and helper timeout/error handling.

Copilot AI review requested due to automatic review settings July 7, 2026 05:24
@kyungseopk1m
kyungseopk1m requested a review from zkochan as a code owner July 7, 2026 05:24
@coderabbitai

coderabbitai Bot commented Jul 7, 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

Adds trusted tokenHelper parsing and validation across pnpm and pacquet. Global auth.ini entries are accepted, project and workspace entries remain rejected, and registry tokens are executed lazily through shared network authentication with timeout handling.

Changes

TokenHelper authentication flow

Layer / File(s) Summary
Lazy tokenHelper execution and auth lookup
pnpm/crates/network/src/auth.rs, pnpm/crates/network/src/token_helper.rs, pnpm/crates/network/src/*/tests.rs
Executes token helpers lazily on matching URL lookup, memoizes results, formats authorization headers, enforces timeouts, and prevents fallback after a matched helper fails.
Configuration parsing and trust enforcement
pnpm/crates/config/src/npmrc_auth.rs, pnpm/crates/config/src/lib.rs, pnpm/crates/config/src/workspace_yaml.rs
Parses trusted file-based values, rejects unsupported commands and untrusted project values, and propagates configuration errors.
pnpm configuration source validation
pnpm11/config/reader/src/index.ts, pnpm11/config/reader/src/loadNpmrcFiles.ts, pnpm11/config/reader/test/index.ts
Compares tokenHelper entries with trusted configuration, accepts global auth.ini, and rejects project .npmrc entries.
Integration coverage and release documentation
pnpm/crates/config/src/tests.rs, pnpm/crates/config/README.md, .changeset/*, pnpm/crates/publish/src/execute_token_helper.rs, pnpm/plans/TEST_PORTING.md, pnpm11/network/auth-header/*
Covers trusted, rejected, unsupported, environment-sourced, and timed-out helpers while updating documentation and release metadata.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Config as NpmrcAuth
  participant Headers as AuthHeaders
  participant Registry as Registry request
  participant Helper as TokenHelperRunner
  Config->>Headers: build headers with trusted tokenHelper
  Registry->>Headers: request credentials for registry URL
  Headers->>Helper: execute helper lazily
  Helper-->>Headers: token output or failure
  Headers-->>Registry: Authorization header or no credential
Loading

Possibly related PRs

  • pnpm/pnpm#11953: Related tokenHelper provenance and registry-scoping behavior.
  • pnpm/pnpm#12338: Related URL-scoped environment handling for tokenHelper.

Suggested reviewers: zkochan, copilot

Poem

I’m a rabbit with tokens tucked neat,
Global auth makes the flow complete.
Helpers wake when registries call,
Timeouts keep them from hopping all.
Trusted paths pass; project ones fall!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately highlights the main change: allowing tokenHelper from the global auth.ini.
Description check ✅ Passed It covers the change, rationale, Rust porting, and tests, though it does not mirror the template headings exactly.
Linked Issues check ✅ Passed The PR satisfies #12759 by accepting global trusted tokenHelper config while still rejecting project-level .npmrc entries.
Out of Scope Changes check ✅ Passed The Rust port, timeout, tests, and docs all support the stated tokenHelper work and do not appear unrelated.
✨ 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-code-review

qodo-code-review Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Fix tokenHelper validation to trust global pnpm auth.ini

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Accept tokenHelper when sourced from trusted config (global auth.ini or ~/.npmrc).
• Keep rejecting tokenHelper configured in project/workspace .npmrc for security.
• Add reader tests covering accepted global auth.ini and rejected project .npmrc.
Diagram

graph TD
  A["pnpm CLI"] --> B["getConfig()"] --> C["npmrc reader"] --> D["trustedConfig"] --> E["tokenHelper guard"] --> F["authConfig output"]
  C --> G["project .npmrc"]
  D --> H["global auth.ini + ~/.npmrc"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Track per-key config origin (source metadata)
  • ➕ Avoids value-based comparison (more robust when same key appears in multiple sources).
  • ➕ Enables clearer error messages (which exact file introduced tokenHelper).
  • ➖ Requires broader changes to config parsing/merging APIs.
  • ➖ Higher complexity and risk for a narrowly scoped bug.
2. Explicit allowlist of trusted tokenHelper locations
  • ➕ Makes the security policy very explicit and auditable.
  • ➕ Could support future trusted locations without changing merge semantics.
  • ➖ May duplicate logic already represented by trustedConfig.
  • ➖ Still needs careful handling for URL-scoped keys.

Recommendation: Keep the PR’s approach: validating against trustedConfig is the smallest change that matches the documented intent (trust ~/.npmrc and global auth.ini, reject project/workspace). More elaborate origin-tracking would be cleaner long-term but is disproportionate for this regression and would widen the change surface.

Files changed (3) +57 / -2

Bug fix (1) +2 / -2
index.tsValidate tokenHelper against trustedConfig (includes global auth.ini) +2/-2

Validate tokenHelper against trustedConfig (includes global auth.ini)

• Fixes the tokenHelper guard to compare pnpm authConfig entries against 'trustedConfig' instead of 'userConfig'. This allows tokenHelper values coming from global pnpm auth.ini while continuing to reject project/workspace '.npmrc' sources.

pnpm11/config/reader/src/index.ts

Tests (1) +49 / -0
index.tsAdd tests for global auth.ini acceptance and project .npmrc rejection +49/-0

Add tests for global auth.ini acceptance and project .npmrc rejection

• Adds coverage ensuring a tokenHelper in XDG-scoped global 'pnpm/auth.ini' is honored. Also asserts that a tokenHelper set in a project '.npmrc' still throws 'ERR_PNPM_TOKEN_HELPER_IN_PROJECT_CONFIG'.

pnpm11/config/reader/test/index.ts

Documentation (1) +6 / -0
allow-tokenhelper-in-global-auth-ini.mdAdd changeset for tokenHelper global auth.ini fix +6/-0

Add changeset for tokenHelper global auth.ini fix

• Adds a changeset describing that tokenHelper configured in global pnpm auth.ini is now accepted while project/workspace tokenHelper remains blocked. Marks patch bumps for @pnpm/config.reader and pnpm.

.changeset/allow-tokenhelper-in-global-auth-ini.md

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.

Pull request overview

This PR fixes an auth configuration regression in @pnpm/config.reader where a tokenHelper written by pnpm config set into the global pnpm auth.ini was incorrectly rejected as “project-level” configuration. It does so by validating tokenHelper against the merged trusted config sources rather than only ~/.npmrc, while keeping the project/workspace .npmrc guard in place.

Changes:

  • Validate tokenHelper presence/value against npmrcResult.trustedConfig (includes global auth.ini) instead of npmrcResult.userConfig.
  • Add tests covering: (1) tokenHelper in global auth.ini is accepted, and (2) tokenHelper in project .npmrc is still rejected.
  • Add a changeset for patch releases of @pnpm/config.reader and pnpm.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
pnpm11/config/reader/src/index.ts Switch tokenHelper trust validation to use trustedConfig so global auth.ini is accepted while project config remains blocked.
pnpm11/config/reader/test/index.ts Add coverage for the global auth.ini acceptance path and the project .npmrc rejection path.
.changeset/allow-tokenhelper-in-global-auth-ini.md Document the fix and ship patch bumps for the affected packages.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread pnpm11/config/reader/src/index.ts Resolved
@qodo-code-review

qodo-code-review Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 18 rules

Grey Divider


Action required

1. Pacquet tokenHelper laziness diverges 📘 Rule violation ⌂ Architecture
Description
Pacquet documents and implements tokenHelper execution as lazy (only when a matching registry
request occurs), while pnpm TypeScript executes the helper during auth-header map construction for
all configured registries. This is a user-visible behavior difference (process execution timing/side
effects) that is not called out as a known divergence, violating the pnpm/pacquet sync requirement.
Code

.changeset/pacquet-token-helper.md[5]

+Added support for the `tokenHelper` auth setting, matching the TypeScript CLI. A `tokenHelper` configured in `~/.npmrc` or the global pnpm `auth.ini` names a command pacquet runs to obtain a registry token; the command runs lazily (only when a request to that registry is actually made), is given a 60-second time limit, and its output becomes the `Authorization` header. A `tokenHelper` in a workspace or project `.npmrc`, or supplied through a URL-scoped environment variable, is refused so a checked-in config can't run an arbitrary command.
Evidence
Rule 713428 requires pnpm TypeScript and pacquet Rust user-visible behavior to be kept in sync, or
divergences to be explicitly called out. The pacquet changeset states the helper runs lazily, and
pacquet resolves/executes helpers during lookup; pnpm TypeScript executes executeTokenHelper()
while building auth headers, before any specific registry request determines which registry is
actually used.

Rule 713428: Keep pnpm TypeScript and pacquet Rust user-visible behavior changes in sync
.changeset/pacquet-token-helper.md[5-5]
pnpm/crates/network/src/auth.rs[516-548]
pnpm11/network/auth-header/src/getAuthHeadersFromConfig.ts[63-67]
pnpm11/network/auth-header/src/index.ts[25-35]

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

## Issue description
Pacquet executes `tokenHelper` lazily per-registry request, but pnpm TypeScript executes `tokenHelper` while building the auth-header map (potentially running helpers for registries that are never contacted). This is a user-visible behavioral divergence (command execution timing/side effects) that should be either aligned or explicitly documented as a known divergence.

## Issue Context
The changeset claims pacquet behavior matches the TypeScript CLI while also stating lazy execution; current pnpm TypeScript code executes the helper when computing auth headers.

## Fix Focus Areas
- .changeset/pacquet-token-helper.md[5-5]
- pnpm11/network/auth-header/src/getAuthHeadersFromConfig.ts[63-67]
- pnpm11/network/auth-header/src/index.ts[25-35]
- pnpm/crates/network/src/auth.rs[516-548]

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


2. pacquet tokenHelper failure only logs ✗ Dismissed 📘 Rule violation ⌂ Architecture
Description
pacquet resolves tokenHelper lazily and, on failure, only logs and proceeds without an auth
header, while pnpm TypeScript throws on helper failure. This creates user-visible pnpm/pacquet
behavioral divergence without an explicit call-out in this PR.
Code

pnpm/crates/network/src/auth.rs[R516-548]

+    /// Resolve a matched [`AuthEntry`] to a header value. A baked header
+    /// is cloned; a `tokenHelper` is executed once and memoized (keyed by
+    /// `scope` + map key so the same command at two registries still runs
+    /// per registry). A helper failure logs and yields `None` — pacquet
+    /// never sends a wrong, partial, or stale credential.
+    fn resolve_entry(&self, key: &str, scope: &str, entry: &AuthEntry) -> Option<String> {
+        match entry {
+            AuthEntry::Header(value) => Some(value.clone()),
+            AuthEntry::TokenHelper(command) => {
+                let cache_key = format!("{scope}\u{0}{key}");
+                let mut cache = self
+                    .resolved_token_helpers
+                    .lock()
+                    .unwrap_or_else(std::sync::PoisonError::into_inner);
+                if let Some(cached) = cache.get(&cache_key) {
+                    return cached.clone();
+                }
+                let runner = self.token_helper_runner.unwrap_or(run_token_helper_command);
+                let resolved = match execute_token_helper(command, runner) {
+                    Ok(header) => Some(header),
+                    Err(error) => {
+                        let program = command.first().map_or("", String::as_str);
+                        tracing::error!(
+                            target: "pacquet::auth",
+                            "token helper {program:?} failed; the request will be sent without \
+                             authentication: {error}",
+                        );
+                        None
+                    }
+                };
+                cache.insert(cache_key, resolved.clone());
+                resolved
+            }
Evidence
The compliance checklist requires pnpm TypeScript and pacquet Rust user-visible behavior to stay in
sync. pacquet’s new logic logs and returns None on tokenHelper failure, while pnpm TypeScript
throws errors for non-zero exit and empty output, so behavior differs for the same configuration.

Rule 713428: Keep pnpm TypeScript and pacquet Rust user-visible behavior changes in sync
Rule 713429: Pacquet must not introduce new user-visible behavior beyond pnpm
pnpm/crates/network/src/auth.rs[516-548]
pnpm11/network/auth-header/src/getAuthHeadersFromConfig.ts[63-95]
.changeset/pacquet-token-helper.md[5-5]

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

## Issue description
pacquet currently executes `tokenHelper` lazily during `AuthHeaders::for_url()` resolution and swallows failures by logging and returning `None`. pnpm TypeScript executes `tokenHelper` when building auth headers and throws on non-zero exit / empty output.

This violates the parity requirements: user-visible behavior differs between pnpm (TS) and pacquet (Rust).

## Issue Context
- pacquet: `resolve_entry()` logs helper failure and returns `None`, causing requests to be sent unauthenticated.
- pnpm (TS): `executeTokenHelper()` throws on failure, making the operation fail fast.

## Fix Focus Areas
- pnpm/crates/network/src/auth.rs[516-548]
- pnpm/crates/network/src/token_helper.rs[66-87]
- pnpm11/network/auth-header/src/getAuthHeadersFromConfig.ts[63-95]

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


3. Token helper can hang ✓ Resolved 🐞 Bug ☼ Reliability
Description
run_token_helper_command uses Command::output() with no timeout/cancellation, so a tokenHelper
that hangs can stall installs indefinitely once a matching registry URL is accessed. Because
resolution is lazy and memoized only after completion, a hung helper also prevents the cache from
ever being populated.
Code

pnpm/crates/network/src/token_helper.rs[R89-105]

+/// Production runner: spawn `command` and capture its output. On Windows a
+/// `.bat`/`.cmd` program is run through `cmd /C` (those files need a
+/// shell), matching pnpm's `shell` handling.
+pub fn run_token_helper_command(command: &[String]) -> io::Result<TokenHelperOutput> {
+    let Some((program, args)) = command.split_first() else {
+        return Ok(TokenHelperOutput {
+            success: true,
+            stdout: String::new(),
+            stderr: String::new(),
+        });
+    };
+    let output = build_command(program, args).output()?;
+    Ok(TokenHelperOutput {
+        success: output.status.success(),
+        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
+        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
+    })
Evidence
The production runner waits on Command::output() without any timeout, and the caller executes it
inline during auth lookup; this can block the fetch/install path indefinitely if the helper never
exits.

pnpm/crates/network/src/token_helper.rs[89-106]
pnpm/crates/network/src/auth.rs[521-548]

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

### Issue description
`tokenHelper` subprocess execution has no timeout. If the helper blocks (waiting for input, deadlock, stuck I/O, etc.), `AuthHeaders` lookup never returns and pnpm/pacquet can hang indefinitely on the first request that needs that credential.

### Issue Context
- `run_token_helper_command` calls `Command::output()` which waits forever.
- `AuthHeaders::resolve_entry` calls the runner synchronously from `for_url_with_package`, which is used while building network requests.

### Fix Focus Areas
- pnpm/crates/network/src/token_helper.rs[89-106]
- pnpm/crates/network/src/auth.rs[521-548]

### Suggested fix
- Introduce a bounded execution time for tokenHelper, with a reasonable default and (optionally) a config/env override.
- Implement the timeout by spawning the child process and polling with `try_wait()` until a deadline; on expiry, kill the process and return an error (which will be memoized as failure).
- Ensure stdout/stderr are still captured for normal completion, and avoid logging token contents.
- Consider also ensuring stdin is not inherited (to reduce the chance of a helper waiting on input).

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


View more (2)
4. Changeset missing pnpm entry ✗ Dismissed 📘 Rule violation § Compliance
Description
The new changeset .changeset/pacquet-token-helper.md does not include a pnpm package entry. This
violates the requirement that changesets explicitly declare pnpm with an appropriate bump type.
Code

.changeset/pacquet-token-helper.md[R1-3]

+---
+"pacquet": minor
+---
Evidence
PR Compliance ID 713436 requires changeset front-matter to contain an entry for pnpm. The new
changeset front-matter lists only pacquet: minor, so it fails the rule as written.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/pacquet-token-helper.md[1-3]

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 changeset `.changeset/pacquet-token-helper.md` lists only `pacquet`, but the compliance rule requires changeset front-matter to explicitly include `pnpm` with a valid bump type.

## Issue Context
This PR adds a new changeset file; it must include a `pnpm` entry (`patch`/`minor`/`major`) per the checklist.

## Fix Focus Areas
- .changeset/pacquet-token-helper.md[1-3]

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


5. tokenHelper not synced to pacquet 📘 Rule violation ⌂ Architecture
Description
This PR changes pnpm's user-visible tokenHelper trust behavior by allowing tokenHelper from the
global auth.ini via trustedConfig. Pacquet does not yet support tokenHelper (it explicitly
rejects it / is not wired), and the PR does not include a corresponding pacquet update or an
explicit divergence call-out, risking pnpm/pacquet behavior drift.
Code

pnpm11/config/reader/src/index.ts[R367-370]

+  const trustedConfig = npmrcResult.trustedConfig as Record<string, string>
  for (const [key, value] of Object.entries(pnpmConfig.authConfig)) {
    if (!key.endsWith('tokenHelper') && key !== 'tokenHelper') continue
-    if (!(key in userConfig) || userConfig[key] !== value) {
+    if (!(key in trustedConfig) || trustedConfig[key] !== value) {
Evidence
The pnpm config reader now validates tokenHelper against npmrcResult.trustedConfig (which
includes global auth.ini) instead of userConfig, changing which configurations are accepted.
Pacquet's config/auth parsing currently rejects tokenHelper as an unsupported auth field and its
publish token-helper execution is documented as not yet wired, indicating no matching user-visible
support in pacquet within this PR.

Rule 713428: Keep pnpm TypeScript and pacquet Rust user-visible behavior changes in sync
pnpm11/config/reader/src/index.ts[365-374]
pacquet/crates/config/src/npmrc_auth/tests.rs[1364-1374]
pacquet/crates/publish/src/execute_token_helper.rs[1-11]

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

## Issue description
pnpm now allows `tokenHelper` configured in global `auth.ini` by validating against `trustedConfig`, which is a user-visible behavior change. Pacquet does not yet support `tokenHelper` (it rejects it / is not wired), so pnpm and pacquet behavior are no longer aligned unless the divergence is explicitly called out or pacquet is updated.

## Issue Context
Compliance requires pnpm TypeScript and pacquet Rust user-visible behavior changes to stay in sync, or for the PR to explicitly call out pending porting work when only one implementation changes.

## Fix Focus Areas
- pnpm11/config/reader/src/index.ts[365-374]
- .changeset/allow-tokenhelper-in-global-auth-ini.md[1-6]

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



Remediation recommended

6. Racy concurrency test 🐞 Bug ☼ Reliability ⭐ New
Description
The new test meant to prove a slow tokenHelper doesn’t block a second registry lookup doesn’t
synchronize to ensure the slow helper has actually started before the fast lookup runs. This can
allow the test to pass without exercising the lock-contention scenario it is intended to catch,
reducing its value as a regression guard.
Code

pnpm/crates/network/src/auth/tests.rs[R91-96]

+    let slow_auth = Arc::clone(&auth);
+    let slow = thread::spawn(move || slow_auth.for_url("https://slow.example/pkg"));
+
+    let started = Instant::now();
+    let fast = auth.for_url("https://fast.example/pkg");
+    let fast_elapsed = started.elapsed();
Evidence
The test starts the slow thread and immediately begins the fast lookup/timing window, with no
barrier/handshake to guarantee the slow helper is already running when the fast lookup occurs.

pnpm/crates/network/src/auth/tests.rs[56-102]

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 concurrency test spawns the slow lookup thread and immediately runs the fast lookup. Without a handshake, the scheduler can run the fast lookup first, so the test may pass even if a future regression reintroduces blocking behavior.

### Issue Context
This test is intended to validate that the resolution-cache lock is not held while running a helper. To reliably detect regressions, it must force the interleaving where the slow helper has started (and would be blocking) before the fast lookup begins.

### Fix Focus Areas
- pnpm/crates/network/src/auth/tests.rs[56-103]

### Suggested fix approach
- Add a deterministic “slow helper started” signal:
 - Add `static SLOW_STARTED: AtomicBool = AtomicBool::new(false);` inside the test.
 - In `runner`, when `command[0] == "slow"`, set `SLOW_STARTED.store(true, Ordering::Release)` before waiting on `FAST_DONE`.
 - After spawning the slow thread, spin-wait (with a timeout) until `SLOW_STARTED.load(Ordering::Acquire)` is true before starting the fast lookup/timer.
- Keep the existing deadline as a safety, but make the ordering deterministic so the test can’t false-pass.

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


7. Unbounded helper output read 🐞 Bug ⛨ Security
Description
read_pipe uses read_to_end with no size limit for both stdout and stderr, so a tokenHelper that
prints large output can cause arbitrarily large allocations before the token is trimmed. This is a
resource-exhaustion risk (and avoidable performance hit) even with trusted configuration, because a
misbehaving helper can OOM the process.
Code

pnpm/crates/network/src/token_helper.rs[R175-183]

+/// Spawn a thread that reads `pipe` to end-of-stream as lossy UTF-8. A
+/// read error or absent pipe yields the empty string.
+fn read_pipe<Pipe: Read + Send + 'static>(pipe: Option<Pipe>) -> thread::JoinHandle<String> {
+    thread::spawn(move || {
+        let Some(mut pipe) = pipe else { return String::new() };
+        let mut buffer = Vec::new();
+        let _ = pipe.read_to_end(&mut buffer);
+        String::from_utf8_lossy(&buffer).into_owned()
+    })
Evidence
The helper output capture path allocates an unbounded Vec and reads to EOF; both stdout and stderr
are fully retained as Strings in TokenHelperOutput.

pnpm/crates/network/src/token_helper.rs[175-183]
pnpm/crates/network/src/token_helper.rs[27-33]

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

### Issue description
`read_pipe` reads the entire pipe into memory via `read_to_end` with no upper bound. A helper that writes excessive stdout/stderr can exhaust memory.

### Issue Context
`tokenHelper` output is expected to be a small token string; bounding output size is a low-risk hardening and avoids pathological memory usage.

### Fix Focus Areas
- pnpm/crates/network/src/token_helper.rs[175-183]

### Suggested fix
Introduce an explicit max output size (e.g. 64KiB or 1MiB) and enforce it while reading:
- In the reader thread, wrap the pipe with `Read::take((MAX_BYTES + 1) as u64)` and detect truncation.
- Return a `Result` from the thread (e.g. `JoinHandle<io::Result<String>>`) so you can surface an `io::Error` when output exceeds the cap.
- Treat over-limit output as a helper failure (mapped to a token-helper error) rather than trying to continue.

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


8. Timeout path detaches threads 🐞 Bug ☼ Reliability
Description
In run_token_helper_command_with_timeout, stdout/stderr reader threads are spawned and the timeout
branch returns early without joining them, so they can remain blocked in read_to_end until the
pipes close. If the helper spawns descendants that inherit stdout/stderr, this can leak
threads/buffers for the rest of the process and degrade performance or cause a local DoS on repeated
helper keys.
Code

pnpm/crates/network/src/token_helper.rs[R149-166]

+    let stdout = read_pipe(child.stdout.take());
+    let stderr = read_pipe(child.stderr.take());
+
+    let deadline = Instant::now() + timeout;
+    let status = loop {
+        if let Some(status) = child.try_wait()? {
+            break status;
+        }
+        if Instant::now() >= deadline {
+            let _ = child.kill();
+            let _ = child.wait();
+            return Err(io::Error::new(
+                io::ErrorKind::TimedOut,
+                "token helper exceeded its time limit",
+            ));
+        }
+        thread::sleep(Duration::from_millis(20));
+    };
Evidence
The timeout branch returns after spawning reader threads, and the reader threads do a blocking
read_to_end; dropping their JoinHandles detaches them, so they can outlive the function when the
pipes don’t close promptly.

pnpm/crates/network/src/token_helper.rs[149-166]
pnpm/crates/network/src/token_helper.rs[175-183]

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

### Issue description
`run_token_helper_command_with_timeout` spawns stdout/stderr drain threads, but on timeout it kills the child and returns immediately, dropping the `JoinHandle`s without joining them. Dropping a `JoinHandle` detaches the thread; the thread may stay blocked in `read_to_end` until the pipe closes.

### Issue Context
This code is meant to bound helper execution time; leaking threads/buffers on timeout undermines that goal in long-lived processes.

### Fix Focus Areas
- pnpm/crates/network/src/token_helper.rs[149-166]

### Suggested fix
Refactor the timeout branch to also clean up the reader threads before returning. One pragmatic approach:
- On timeout: `kill()` + `wait()`, then attempt to `join()` both reader threads (now that the direct child is gone, pipes typically close).
- If you want to avoid a second hang risk, add a small grace period using `JoinHandle::is_finished()` polling; if not finished, proceed while explicitly documenting the remaining edge case (descendants holding FDs).

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


View more (4)
9. Helper runs under mutex ✓ Resolved 🐞 Bug ➹ Performance
Description
AuthHeaders::resolve_entry holds resolved_token_helpers' global Mutex while executing the
tokenHelper, serializing all helper resolutions and blocking concurrent request construction for
helper-backed registries. This can significantly reduce fetch concurrency because
for_url_with_package is called on metadata and tarball request paths.
Code

pnpm/crates/network/src/auth.rs[R525-546]

+                let cache_key = format!("{scope}\u{0}{key}");
+                let mut cache = self
+                    .resolved_token_helpers
+                    .lock()
+                    .unwrap_or_else(std::sync::PoisonError::into_inner);
+                if let Some(cached) = cache.get(&cache_key) {
+                    return cached.clone();
+                }
+                let runner = self.token_helper_runner.unwrap_or(run_token_helper_command);
+                let resolved = match execute_token_helper(command, runner) {
+                    Ok(header) => Some(header),
+                    Err(error) => {
+                        let program = command.first().map_or("", String::as_str);
+                        tracing::error!(
+                            target: "pacquet::auth",
+                            "token helper {program:?} failed; the request will be sent without \
+                             authentication: {error}",
+                        );
+                        None
+                    }
+                };
+                cache.insert(cache_key, resolved.clone());
Evidence
The mutex guard is held across the helper execution call, and the auth lookup is used directly when
constructing async HTTP requests for metadata/tarball fetches, making this contention part of the
request hot path when tokenHelper is configured.

pnpm/crates/network/src/auth.rs[516-548]
pnpm/crates/resolving-npm-resolver/src/fetch_full_metadata.rs[95-107]
pnpm/crates/tarball/src/lib.rs[1760-1767]

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

### Issue description
`AuthHeaders::resolve_entry` locks `resolved_token_helpers` and keeps the lock held across the potentially slow external process execution (`execute_token_helper`). This serializes all tokenHelper resolutions (even for different registries) and can block tokio workers / reduce parallelism on the network hot path.

### Issue Context
- The lock is acquired before checking/inserting the cache and is not released until after the helper finishes and the result is inserted.
- `AuthHeaders::for_url_with_package` is used when building HTTP requests for metadata and tarball fetches, so this can impact install performance whenever tokenHelper is configured.

### Fix Focus Areas
- pnpm/crates/network/src/auth.rs[516-548]

### Suggested fix
- Refactor the cache to avoid holding a global mutex while running the helper.
- One workable pattern (keeps “run once per key” semantics without global lock contention):
 - Change `resolved_token_helpers` to store per-key `OnceLock<Option<String>>` (or an equivalent per-key synchronization primitive).
 - Under the mutex, get-or-insert the per-key `OnceLock` and then drop the mutex.
 - Call `get_or_init` (or equivalent) to run `execute_token_helper` once and memoize the result.
- Ensure the error logging behavior remains the same, and that failure (`None`) is still memoized per key.

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


10. fs.writeFileSync missing trailing comma 📘 Rule violation ⚙ Maintainability
Description
The new multi-line fs.writeFileSync(...) call omits a trailing comma after the last argument,
which violates the repo’s TypeScript trailing-comma requirement and increases diff churn on future
edits.
Code

pnpm11/config/reader/test/index.ts[R1181-1184]

+  fs.writeFileSync(
+    path.join(configHome, 'pnpm', 'auth.ini'),
+    '//registry.example.com/:tokenHelper=/bin/echo'
+  )
Evidence
PR Compliance ID 713434 requires trailing commas in multi-line TypeScript constructs. In
pnpm11/config/reader/test/index.ts, the added multi-line fs.writeFileSync( call ends the last
argument line without a comma before the closing ).

Rule 713434: Require trailing commas in TypeScript collections and multi-line constructs
pnpm11/config/reader/test/index.ts[1181-1184]

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

## Issue description
A multi-line function call was added without a trailing comma after the final argument.

## Issue Context
The compliance rule requires trailing commas in multi-line TypeScript constructs (including argument lists) to keep formatting consistent and reduce noisy diffs.

## Fix Focus Areas
- pnpm11/config/reader/test/index.ts[1181-1184]

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


11. CLI tokenHelper now allowed 🐞 Bug ⛨ Security
Description
The TOKEN_HELPER_IN_PROJECT_CONFIG guard now validates tokenHelper keys against
npmrcResult.trustedConfig, which includes CLI options; this makes tokenHelper injectable via CLI
config rather than being restricted to user-level files. Since tokenHelper is executed via spawnSync
when auth headers are computed, any wrapper/automation that forwards untrusted input into pnpm CLI
config could be turned into arbitrary command execution.
Code

pnpm11/config/reader/src/index.ts[R367-375]

  // tokenHelper must only come from user-level config (~/.npmrc or global auth.ini),
  // not project-level, to prevent project .npmrc from executing arbitrary commands.
-  const userConfig = npmrcResult.userConfig as Record<string, string>
+  const trustedConfig = npmrcResult.trustedConfig as Record<string, string>
  for (const [key, value] of Object.entries(pnpmConfig.authConfig)) {
    if (!key.endsWith('tokenHelper') && key !== 'tokenHelper') continue
-    if (!(key in userConfig) || userConfig[key] !== value) {
+    if (!(key in trustedConfig) || trustedConfig[key] !== value) {
      throw new PnpmError('TOKEN_HELPER_IN_PROJECT_CONFIG',
        'tokenHelper must not be configured in project-level .npmrc',
        { hint: `The key "${key}" was found in project config. Move it to ~/.npmrc or the global pnpm auth.ini.` })
Evidence
The PR changes the guard to validate against trustedConfig. In this repo, trustedConfig is
constructed by merging sources that include cliOptions, and tokenHelper values are executed when
generating auth headers; therefore, allowing CLI as a provenance source broadens where an executable
tokenHelper can originate.

pnpm11/config/reader/src/index.ts[367-376]
pnpm11/config/reader/src/loadNpmrcFiles.ts[172-181]
pnpm11/config/reader/src/loadNpmrcFiles.ts[109-120]
pnpm11/network/auth-header/src/getAuthHeadersFromConfig.ts[63-86]
pnpm11/config/reader/test/index.ts[1244-1249]

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

## Issue description
`tokenHelper` is an executable setting, but the updated guard now treats any source included in `trustedConfig` as sufficient provenance. `trustedConfig` currently includes CLI options, so `tokenHelper` can now be introduced via CLI config (not just `~/.npmrc` or global `auth.ini`).

## Issue Context
- `loadNpmrcConfig()` builds `trustedConfig` by merging multiple sources including `cliOptions`.
- `getConfig()` uses `trustedConfig` to decide whether a `tokenHelper` value is acceptable.
- `tokenHelper` values are executed when constructing auth headers.

## Fix Focus Areas
- pnpm11/config/reader/src/index.ts[367-376]
- pnpm11/config/reader/src/loadNpmrcFiles.ts[109-120]
- pnpm11/config/reader/src/loadNpmrcFiles.ts[172-181]

## Suggested approach
1. Introduce a narrower “tokenHelperTrustedConfig” (or similar) that includes only file-based trusted sources: `userConfig` + `pnpmAuthConfig` (global auth.ini), excluding env-scoped layers and `cliOptions`.
2. Return this new object from `loadNpmrcConfig()`.
3. In `getConfig()`, validate tokenHelper keys against this narrower object instead of `npmrcResult.trustedConfig`.
4. (Optional) Add/adjust a test to assert that a CLI-provided `//host/:tokenHelper` does *not* bypass the guard unless explicitly intended.

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


12. Stale tokenHelper trust comment ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
After switching the tokenHelper guard to validate against npmrcResult.trustedConfig, an existing
comment still states the guard validates against the user ~/.npmrc and that env-layer tokenHelper
would “trip” it. This is now inaccurate and increases the risk of future maintainers
misunderstanding which sources are considered trusted for the guard.
Code

pnpm11/config/reader/src/index.ts[R365-371]

  // tokenHelper must only come from user-level config (~/.npmrc or global auth.ini),
  // not project-level, to prevent project .npmrc from executing arbitrary commands.
-  const userConfig = npmrcResult.userConfig as Record<string, string>
+  const trustedConfig = npmrcResult.trustedConfig as Record<string, string>
  for (const [key, value] of Object.entries(pnpmConfig.authConfig)) {
    if (!key.endsWith('tokenHelper') && key !== 'tokenHelper') continue
-    if (!(key in userConfig) || userConfig[key] !== value) {
+    if (!(key in trustedConfig) || trustedConfig[key] !== value) {
      throw new PnpmError('TOKEN_HELPER_IN_PROJECT_CONFIG',
Evidence
The guard now uses trustedConfig (not userConfig) to decide whether a tokenHelper is allowed.
Separately, trustedConfig is built from several non-project sources, and the env-scoped config
reader has a comment that still describes the older userConfig-based guard, making it stale
relative to the new behavior.

pnpm11/config/reader/src/index.ts[365-374]
pnpm11/config/reader/src/loadNpmrcFiles.ts[172-180]
pnpm11/config/reader/src/loadNpmrcFiles.ts[230-235]

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

### Issue description
`getConfig()` now validates `tokenHelper` values against `npmrcResult.trustedConfig`, but a comment in `loadNpmrcFiles.ts` still claims the guard validates against the user `~/.npmrc` and that env tokenHelper would “trip” the guard. This comment is now misleading.

### Issue Context
`trustedConfig` is a merged view of non-project sources (includes `~/.npmrc` and global `auth.ini`, but also includes some other trusted layers like env-scoped auth and CLI). The env-scoped reader currently drops `:tokenHelper` keys to preserve the “file-only” policy for token helpers; the comment should describe that accurately.

### Fix Focus Areas
- pnpm11/config/reader/src/loadNpmrcFiles.ts[172-180]
- pnpm11/config/reader/src/loadNpmrcFiles.ts[230-235]
- pnpm11/config/reader/src/index.ts[365-374]

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


Grey Divider

Qodo Logo

Comment thread pnpm11/config/reader/src/index.ts Resolved
@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 7, 2026
@qodo-code-review

Copy link
Copy Markdown

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

ⓘ You are approaching your monthly quota for Qodo. Upgrade your plan

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

Copy link
Copy Markdown

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

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

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

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

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

ⓘ You are approaching your monthly quota for Qodo. Upgrade your plan

1 similar comment
@qodo-code-review

Copy link
Copy Markdown

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

ⓘ You are approaching your monthly quota for Qodo. Upgrade your plan

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

Copy link
Copy Markdown

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

The guard that blocks tokenHelper in a project .npmrc validated the value against
~/.npmrc only. A tokenHelper written to the global pnpm auth.ini, where `pnpm config set`
stores it, was treated as project configuration and rejected on every command, and could
not be removed with `pnpm config delete`. Validate against the trusted config, which
includes the global auth.ini but still excludes workspace and project .npmrc files.
The comment said the env layer skips `//host/:tokenHelper` to avoid tripping
the project-config guard, which validated against ~/.npmrc. That guard now
validates against the trusted config, which already includes the env-scoped
layer, so admitting the key here would instead pass the guard and let an env
var run an arbitrary command. Describe that as the actual reason to drop it.
Copilot AI review requested due to automatic review settings July 13, 2026 10:55
@zkochan
zkochan force-pushed the fix/tokenhelper-allow-global-auth-ini branch from b6ab691 to 2d46611 Compare July 13, 2026 10:55

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.

@greptile-apps

greptile-apps Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge — the change is a single-source swap on the TypeScript side with well-reasoned trust semantics, fully mirrored in the Rust port, and tests cover global accept, project reject, reserved-character reject, and env-drop paths on both stacks.

The trust-boundary logic is correct and matches across both stacks. The OnceLock-per-key pattern avoids holding the shared mutex across slow subprocess invocations, ChildGuard prevents process leaks, and pipe-draining threads prevent deadlocks. No logic defects were identified.

No files require special attention.

Reviews (6): Last reviewed commit: "fix(pacquet): kill an orphaned tokenHelp..." | Re-trigger Greptile

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 2d46611

@qodo-code-review

qodo-code-review Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 722a623

Warning

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

CategorySuggestion                                                                                                                                    Impact
Possible issue
Propagate token helper failures

Propagate tokenHelper failures as errors rather than falling back to
unauthenticated requests. Update the lookup APIs to return a Result to mirror
the TypeScript implementation.

pnpm/crates/network/src/auth.rs [550-561]

 match execute_token_helper(command, runner) {
-    Ok(header) => Some(header),
-    Err(error) => {
-        let program = command.first().map_or("", String::as_str);
-        tracing::error!(
-            target: "pacquet::auth",
-            "token helper {program:?} failed; the request will be sent \
-             without authentication: {error}",
-        );
-        None
-    }
+    Ok(header) => Ok(Some(header)),
+    Err(error) => Err(error),
 }
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: Silently ignoring token helper failures can lead to unauthenticated requests, which risks anonymous publishing attempts and breaks parity with the original TypeScript CLI behavior.

Medium
Kill timed-out process trees

Terminate the entire process tree on timeout to prevent child processes from
continuing to run. This avoids leaked processes and hanging reader threads,
especially on Windows.

pnpm/crates/network/src/token_helper.rs [162-168]

 if Instant::now() >= deadline {
-    // Leaving `guard` armed kills the still-running child on drop.
+    guard.kill_process_tree()?;
+    guard.wait()?;
     return Err(io::Error::new(
         io::ErrorKind::TimedOut,
         "token helper exceeded its time limit",
     ));
 }
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: On Windows, killing cmd /c leaves the child script running, which keeps the pipes open and causes the reader threads to hang indefinitely.

Medium
Security
Bound helper output memory

Set a size limit when reading the helper's standard output and standard error.
Return an error if the output exceeds this limit to protect against excessive
memory consumption.

pnpm/crates/network/src/token_helper.rs [205-212]

-fn read_pipe<Pipe: Read + Send + 'static>(pipe: Option<Pipe>) -> thread::JoinHandle<String> {
+const MAX_TOKEN_HELPER_OUTPUT: u64 = 64 * 1024;
+
+fn read_pipe<Pipe: Read + Send + 'static>(
+    pipe: Option<Pipe>,
+) -> thread::JoinHandle<io::Result<String>> {
     thread::spawn(move || {
-        let Some(mut pipe) = pipe else { return String::new() };
+        let Some(pipe) = pipe else { return Ok(String::new()) };
         let mut buffer = Vec::new();
-        let _ = pipe.read_to_end(&mut buffer);
-        String::from_utf8_lossy(&buffer).into_owned()
+        pipe.take(MAX_TOKEN_HELPER_OUTPUT + 1).read_to_end(&mut buffer)?;
+        if buffer.len() as u64 > MAX_TOKEN_HELPER_OUTPUT {
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidData,
+                "token helper output exceeded the size limit",
+            ));
+        }
+        Ok(String::from_utf8_lossy(&buffer).into_owned())
     })
 }
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: Using unbounded read_to_end allows a broken script to spam output for 60 seconds, potentially causing an Out-Of-Memory (OOM) error before the timeout.

Medium
  • More

Previous suggestions

Suggestions up to commit 44a1473
CategorySuggestion                                                                                                                                    Impact
Security
Bound subprocess output memory

Add a limit to the maximum number of bytes read from the helper's stdout/stderr.

pnpm/crates/network/src/token_helper.rs [177-184]

-fn read_pipe<Pipe: Read + Send + 'static>(pipe: Option<Pipe>) -> thread::JoinHandle<String> {
+const TOKEN_HELPER_OUTPUT_LIMIT: u64 = 1024 * 1024;
+
+fn read_pipe<Pipe: Read + Send + 'static>(
+    pipe: Option<Pipe>,
+) -> thread::JoinHandle<io::Result<String>> {
     thread::spawn(move || {
-        let Some(mut pipe) = pipe else { return String::new() };
+        let Some(pipe) = pipe else { return Ok(String::new()) };
         let mut buffer = Vec::new();
-        let _ = pipe.read_to_end(&mut buffer);
-        String::from_utf8_lossy(&buffer).into_owned()
+        pipe.take(TOKEN_HELPER_OUTPUT_LIMIT + 1).read_to_end(&mut buffer)?;
+        if buffer.len() as u64 > TOKEN_HELPER_OUTPUT_LIMIT {
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidData,
+                "token helper output exceeded the size limit",
+            ));
+        }
+        Ok(String::from_utf8_lossy(&buffer).into_owned())
     })
 }
Suggestion importance[1-10]: 8

__

Why: Limiting the amount of data read from a subprocess stream is a crucial security and reliability measure to prevent memory exhaustion from a malicious or hanging helper.

Medium
Possible issue
Propagate token helper failures

Propagate tokenHelper execution errors to the caller instead of silently
returning None.

pnpm/crates/network/src/auth.rs [550-561]

 match execute_token_helper(command, runner) {
-    Ok(header) => Some(header),
-    Err(error) => {
-        let program = command.first().map_or("", String::as_str);
-        tracing::error!(
-            target: "pacquet::auth",
-            "token helper {program:?} failed; the request will be sent \
-             without authentication: {error}",
-        );
-        None
-    }
+    Ok(header) => Ok(Some(header)),
+    Err(error) => Err(error),
 }
Suggestion importance[1-10]: 8

__

Why: Swallowing token helper errors and proceeding unauthenticated can lead to information leaks and breaks parity with the TypeScript CLI, which explicitly throws an error.

Medium
General
Terminate timed-out process trees

Terminate the entire process tree on timeout to prevent orphaned descendant
processes.

pnpm/crates/network/src/token_helper.rs [157-164]

 if Instant::now() >= deadline {
-    let _ = child.kill();
+    terminate_process_tree(&mut child)?;
     let _ = child.wait();
+    let _ = stdout.join();
+    let _ = stderr.join();
     return Err(io::Error::new(
         io::ErrorKind::TimedOut,
         "token helper exceeded its time limit",
     ));
 }
Suggestion importance[1-10]: 5

__

Why: While leaving descendant processes alive is a valid concern, the suggested code introduces an undefined terminate_process_tree function and requires OS-specific implementations to work correctly.

Low
Suggestions up to commit 833f27e
CategorySuggestion                                                                                                                                    Impact
General
Avoid serializing independent helpers

Use a per-key OnceLock within the cache instead of holding the global mutex
during helper execution. This enables token helpers for different registries to
execute concurrently without blocking the cache map.

pnpm/crates/network/src/auth.rs [526-546]

-let mut cache = self
-    .resolved_token_helpers
-    .lock()
-    .unwrap_or_else(std::sync::PoisonError::into_inner);
-if let Some(cached) = cache.get(&cache_key) {
-    return cached.clone();
-}
+let resolution = {
+    let mut cache = self
+        .resolved_token_helpers
+        .lock()
+        .unwrap_or_else(std::sync::PoisonError::into_inner);
+    Arc::clone(
+        cache
+            .entry(cache_key)
+            .or_insert_with(|| Arc::new(std::sync::OnceLock::new())),
+    )
+};
 let runner = self.token_helper_runner.unwrap_or(run_token_helper_command);
-let resolved = match execute_token_helper(command, runner) {
-    ...
-};
-cache.insert(cache_key, resolved.clone());
+resolution
+    .get_or_init(|| execute_token_helper(command, runner))
+    .clone()
Suggestion importance[1-10]: 9

__

Why: This addresses a critical concurrency bottleneck where a slow token helper blocks the entire resolved_token_helpers cache, halting other independent network requests.

High
Possible issue
Propagate authentication helper failures

Modify resolve_entry to return a Result and propagate TokenHelperError rather
than logging and returning None. This prevents sending unauthenticated requests
on helper failure.

pnpm/crates/network/src/auth.rs [521-550]

-fn resolve_entry(&self, key: &str, scope: &str, entry: &AuthEntry) -> Option<String> {
+fn resolve_entry(
+    &self,
+    key: &str,
+    scope: &str,
+    entry: &AuthEntry,
+) -> Result<Option<String>, TokenHelperError> {
     match entry {
-        AuthEntry::Header(value) => Some(value.clone()),
+        AuthEntry::Header(value) => Ok(Some(value.clone())),
         AuthEntry::TokenHelper(command) => {
             ...
-            let resolved = match execute_token_helper(command, runner) {
-                Ok(header) => Some(header),
-                Err(error) => {
-                    ...
-                    tracing::error!(
-                        target: "pacquet::auth",
-                        "token helper {program:?} failed; the request will be sent without \
-                         authentication: {error}",
-                    );
-                    None
-                }
-            };
-            ...
-            resolved
+            let runner = self.token_helper_runner.unwrap_or(run_token_helper_command);
+            let resolved = Some(execute_token_helper(command, runner)?);
+            cache.insert(cache_key, resolved.clone());
+            Ok(resolved)
         }
     }
 }
Suggestion importance[1-10]: 8

__

Why: Propagating the error instead of defaulting to an unauthenticated request addresses a potentially sensitive behavior and aligns with the TypeScript implementation's error handling.

Medium
Suggestions up to commit 83a1156
CategorySuggestion                                                                                                                                    Impact
General
Avoid blocking unrelated auth lookups

Use an Arc per cache key to prevent holding the global mutex during external
process execution.

pnpm/crates/network/src/auth.rs [526-547]

-let mut cache = self
-    .resolved_token_helpers
-    .lock()
-    .unwrap_or_else(std::sync::PoisonError::into_inner);
-if let Some(cached) = cache.get(&cache_key) {
-    return cached.clone();
-}
-let runner = self.token_helper_runner.unwrap_or(run_token_helper_command);
-let resolved = match execute_token_helper(command, runner) {
-    Ok(header) => Some(header),
-    Err(error) => {
-        ...
-    }
+let entry = {
+    let mut cache = self
+        .resolved_token_helpers
+        .lock()
+        .unwrap_or_else(std::sync::PoisonError::into_inner);
+    Arc::clone(
+        cache
+            .entry(cache_key)
+            .or_insert_with(|| Arc::new(std::sync::OnceLock::new())),
+    )
 };
-cache.insert(cache_key, resolved.clone());
-resolved
+entry
+    .get_or_init(|| {
+        let runner =
+            self.token_helper_runner.unwrap_or(run_token_helper_command);
+        execute_token_helper(command, runner).ok()
+    })
+    .clone()
Suggestion importance[1-10]: 8

__

Why: This is an excellent suggestion to avoid blocking all concurrent auth lookups while a slow external process runs, though the implementation should ensure the original error logging is preserved inside the initialization closure.

Medium
Suggestions
CategorySuggestion                                                                                                                                    Impact
General
Avoid locking during subprocess execution

Avoid locking the global cache mutex during subprocess execution to prevent
blocking concurrent auth lookups. Use a per-key synchronization primitive (like
OnceLock) to wait for the result instead.

pnpm/crates/network/src/auth.rs [526-546]

-let mut cache = self
-    .resolved_token_helpers
-    .lock()
-    .unwrap_or_else(std::sync::PoisonError::into_inner);
-if let Some(cached) = cache.get(&cache_key) {
-    return cached.clone();
-}
-let runner = self.token_helper_runner.unwrap_or(run_token_helper_command);
-let resolved = match execute_token_helper(command, runner) {
-    Ok(header) => Some(header),
-    Err(error) => {
-        ...
-        None
-    }
+let resolution = {
+    let mut cache = self
+        .resolved_token_helpers
+        .lock()
+        .unwrap_or_else(std::sync::PoisonError::into_inner);
+    cache
+        .entry(cache_key)
+        .or_insert_with(|| Arc::new(std::sync::OnceLock::new()))
+        .clone()
 };
-cache.insert(cache_key, resolved.clone());
+resolution
+    .get_or_init(|| {
+        let runner = self.token_helper_runner.unwrap_or(run_token_helper_command);
+        execute_token_helper(command, runner).ok()
+    })
+    .clone()
Suggestion importance[1-10]: 9

__

Why: Excellent catch of a major concurrency bottleneck; holding the global resolved_token_helpers lock while awaiting a subprocess blocks all other concurrent requests resolving auth headers.

High
Security
Reject multiline authorization output

Reject helper output containing embedded carriage returns or newlines. This
prevents potential HTTP header injection or downstream request failures.

pnpm/crates/network/src/token_helper.rs [78-86]

 let token = output.stdout.trim_end();
 if token.is_empty() {
     return Err(TokenHelperError::EmptyToken { program: program.clone() });
+}
+if token.contains(['\r', '\n']) {
+    return Err(TokenHelperError::InvalidToken { program: program.clone() });
 }
 if starts_with_auth_scheme(token) {
     Ok(token.to_owned())
 } else {
     Ok(format!("Bearer {token}"))
 }
Suggestion importance[1-10]: 8

__

Why: This effectively prevents potential HTTP header injection vulnerabilities if a token helper command unexpectedly prints multiple lines.

Medium
Possible issue
Propagate token helper failures

Propagate token helper failures instead of swallowing them to prevent requests
from continuing unauthenticated. Change the lookup API to return a Result.

pnpm/crates/network/src/auth.rs [534-545]

-let resolved = match execute_token_helper(command, runner) {
-    Ok(header) => Some(header),
-    Err(error) => {
-        let program = command.first().map_or("", String::as_str);
-        tracing::error!(
-            target: "pacquet::auth",
-            "token helper {program:?} failed; the request will be sent without \
-             authentication: {error}",
-        );
-        None
-    }
-};
+let resolved = execute_token_helper(command, runner).map(Some)?;
Suggestion importance[1-10]: 6

__

Why: While propagating the error correctly aligns with JS pnpm's behavior, the suggested snippet is incomplete as it requires refactoring the entire for_url call chain to return Result.

Low

zkochan and others added 2 commits July 13, 2026 14:23
The comment described the trust rule as "user-level config" while the guard
now validates against trustedConfig. Reword it to name the trusted, non-repo
sources it actually checks (~/.npmrc and the global auth.ini) and to note that
trustedConfig merges exactly those and excludes the repo sources.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Port pnpm's tokenHelper feature to pacquet, the counterpart of this PR's
TypeScript-side guard fix. A tokenHelper configured in ~/.npmrc or the global
auth.ini names a command pacquet runs to obtain a registry token; a tokenHelper
in a workspace or project .npmrc, or supplied through a URL-scoped environment
variable, is refused so a checked-in config cannot run an arbitrary command.

Config layer: parse //host/:tokenHelper (scoped and default too) from trusted
.npmrc/auth.ini sources only; validate reserved characters; and reject a
project-contributed helper by comparing the full merge against the trusted-only
merge (the analog of pnpm's trustedConfig), surfacing the same
ERR_PNPM_TOKEN_HELPER_IN_PROJECT_CONFIG / _UNSUPPORTED_CHARACTER codes.

Network layer: AuthHeaders carries the un-executed command per registry and
runs it lazily on lookup, memoized so it runs at most once and never for a
command that makes no matching request. Baked headers keep their eager,
lock-free hot path. A header is emitted only on success; a failing helper logs
and sends no credential, so pacquet never forwards a wrong, partial, or stale
token. Because AuthHeaders::for_url is infallible, a helper failure surfaces as
a loud error plus an unauthenticated request rather than pnpm's hard
whole-command abort.

Closes the tokenHelper items in pnpm/plans/TEST_PORTING.md.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 13, 2026 12:26

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 13, 2026 12:55

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 .changeset/pacquet-token-helper.md Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 833f27e

@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

🧹 Nitpick comments (1)
pnpm/crates/network/src/token_helper.rs (1)

120-122: 🩺 Stability & Availability | 🔵 Trivial

Caller in auth.rs holds a mutex across run_token_helper_command.

The relevant context shows auth.rs locks resolved_token_helpers before calling execute_token_helper and holds it for the full 60-second timeout window. This serializes all concurrent auth lookups behind a single helper execution. The previous indefinite-hang concern was addressed by the timeout, but consider releasing the lock during helper execution (and handling potential thundering herd) if contention becomes an issue in practice.

🤖 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 `@pnpm/crates/network/src/token_helper.rs` around lines 120 - 122, Update the
auth flow around execute_token_helper so the resolved_token_helpers mutex guard
is not held while run_token_helper_command performs the potentially 60-second
helper execution. Clone or otherwise extract the required helper configuration
while locked, release the guard before execution, and preserve safe coordination
for concurrent lookups if needed to avoid duplicate helper runs.
🤖 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/network/src/token_helper.rs`:
- Around line 139-143: Configure the child process builder in the token helper
spawn chain with kill-on-drop enabled before calling spawn, preserving the
existing stdin, stdout, and stderr configuration. This ensures the spawned
process is terminated if the Child is dropped before polling begins.

---

Nitpick comments:
In `@pnpm/crates/network/src/token_helper.rs`:
- Around line 120-122: Update the auth flow around execute_token_helper so the
resolved_token_helpers mutex guard is not held while run_token_helper_command
performs the potentially 60-second helper execution. Clone or otherwise extract
the required helper configuration while locked, release the guard before
execution, and preserve safe coordination for concurrent lookups if needed to
avoid duplicate helper runs.
🪄 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: 7919834a-e4c7-484e-b56b-3b2deb35f819

📥 Commits

Reviewing files that changed from the base of the PR and between be9df23 and 833f27e.

📒 Files selected for processing (7)
  • .changeset/pacquet-token-helper.md
  • .changeset/token-helper-timeout.md
  • pnpm/crates/config/src/npmrc_auth.rs
  • pnpm/crates/network/src/token_helper.rs
  • pnpm/crates/network/src/token_helper/tests.rs
  • pnpm11/network/auth-header/src/getAuthHeadersFromConfig.ts
  • pnpm11/network/auth-header/test/getAuthHeadersFromConfig.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • pnpm/crates/network/src/token_helper/tests.rs
  • .changeset/pacquet-token-helper.md
  • pnpm/crates/config/src/npmrc_auth.rs
📜 Review details
⏰ Context from checks skipped due to timeout. (2)
  • GitHub Check: Greptile Review
  • GitHub Check: Analyze (javascript)
⚠️ CI failures not shown inline (5)

GitHub Actions: Pacquet Code Coverage / Code Coverage: fix(config): allow tokenHelper to be set in the global auth.ini

Conclusion: failure

View job details

##[group]Run bail() {
 �[36;1mbail() {�[0m
 �[36;1m  printf '::error::install-action: %s\n' "$*"�[0m

GitHub Actions: Pacquet Code Coverage / Code Coverage: fix(config): allow tokenHelper to be set in the global auth.ini

Conclusion: failure

View job details

 serde_core v1.0.228
    Compiling memchr v2.8.0
    Compiling serde v1.0.228
    Compiling version_check v0.9.5
    Compiling portable-atomic v1.13.1
    Compiling bitflags v2.11.1
    Compiling equivalent v1.0.2
    Compiling syn v2.0.117
    Compiling critical-section v1.2.0
    Compiling itoa v1.0.18
    Compiling foldhash v0.2.0
    Compiling getrandom v0.2.17
    Compiling once_cell v1.21.4
    Compiling hashbrown v0.17.0
    Compiling typenum v1.20.0
    Compiling simd-adler32 v0.3.9
    Compiling rand_core v0.6.4
    Compiling zmij v1.0.21
    Compiling shlex v1.3.0
    Compiling jobserver v0.1.34
    Compiling find-msvc-tools v0.1.9
    Compiling adler2 v2.0.1
    Compiling miniz_oxide v0.8.9
    Compiling cc v1.2.60
    Compiling rustix v1.1.4
    Compiling indexmap v2.14.0
    Compiling subtle v2.6.1
    Compiling linux-raw-sys v0.12.1
    Compiling generic-array v0.14.7
    Compiling smallvec v1.15.1
    Compiling serde_json v1.0.150
    Compiling log v0.4.29
    Compiling unicode-width v0.2.2
    Compiling rand_core v0.10.1
    Compiling getrandom v0.4.3
    Compiling is_ci v1.2.0
    Compiling is-terminal v0.4.17
    Compiling owo-colors v4.3.0
    Compiling supports-color v2.1.0
    Compiling supports-color v3.0.2
    Compiling object v0.37.3
    Compiling gimli v0.32.3
    Compiling pin-project-lite v0.2.17
    Compiling rustc-demangle v0.1.27
    Compiling unicode-width v0.1.14
    Compiling unicode-linebreak v0.1.5
    Compiling terminal_size v0.4.4
    Compiling textwrap v0.16.2
    Compiling supports-hyperlinks v3.2.0
    Compiling supports-unicode v3.0.0
    Compiling const-oid v0.9.6
    Compiling unicode-segmentation v1.13.2
    Compiling addr2line v0.25.1
    Compiling unicode-xid v0.2.6
    Compiling convert_case v0.10.0
    Compiling tracing-core v0.1.36
    Compiling serde_derive v1.0.228
    Compiling zeroize_derive v1.4.3
    Compiling miette-derive v7.6.0
    Compiling derive_more-impl v2.1.1
    Compiling zeroize v1.8.2
    Compilin...

GitHub Actions: Pacquet Code Coverage / 1_Code Coverage.txt: fix(config): allow tokenHelper to be set in the global auth.ini

Conclusion: failure

View job details

##[group]Run bail() {
 �[36;1mbail() {�[0m
 �[36;1m  printf '::error::install-action: %s\n' "$*"�[0m

GitHub Actions: Pacquet Code Coverage / Code Coverage: fix(config): allow tokenHelper to be set in the global auth.ini

Conclusion: failure

View job details

##[group]Run bail() {
 �[36;1mbail() {�[0m
 �[36;1m  printf '::error::install-action: %s\n' "$*"�[0m

GitHub Actions: Pacquet Code Coverage / Code Coverage: fix(config): allow tokenHelper to be set in the global auth.ini

Conclusion: failure

View job details

##[group]Run bail() {
 �[36;1mbail() {�[0m
 �[36;1m  printf '::error::install-action: %s\n' "$*"�[0m
🧰 Additional context used
📓 Path-based instructions (6)
.changeset/**/*.{md,mdx}

📄 CodeRabbit inference engine (AGENTS.md)

.changeset/**/*.{md,mdx}: For published TypeScript package changes, create a concise changeset in .changeset describing the user-facing change and affected packages.
Always explicitly include pnpm in a changeset with the appropriate patch, minor, or major bump when the CLI version should change.

Files:

  • .changeset/token-helper-timeout.md
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: For TypeScript changes, install dependencies and compile with pnpm install and pnpm run compile; compile specific packages with pnpm --filter <package_name> run compile.
Run tests for a specific TypeScript project, file, or test case rather than running all repository tests.
Run all TypeScript linting checks with pnpm run lint.
Use Standard Style with trailing commas for TypeScript code.
Prefer functions over classes in TypeScript.
Declare functions after they are used, relying on hoisting.
Limit functions to two or three arguments; use a single options object when more parameters are needed.
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.
Never swallow errors; catch only the specific expected error code, throw on impossible states, and include contextual information such as offending paths in error messages.
Use verb names for functions, specific names for types and fields, existing terminology, and established file-naming conventions.
Prefer plain string operations for string parsing; use the existing object/property-path parser-combinator pattern when structured parsing with backtracking is required.
Route 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; use Promise.all or Promise.any for independent work and hoist invariant work out of loops.

Files:

  • pnpm11/network/auth-header/src/getAuthHeadersFromConfig.ts
  • pnpm11/network/auth-header/test/getAuthHeadersFromConfig.test.ts
**/*.{ts,tsx,rs}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx,rs}: Avoid comments that restate code, repeat callee documentation, describe past implementation history, or narrate the function body.
Write comments only for non-obvious rationale, hidden invariants, workarounds, deliberate exceptions, or temporary technical constraints; prefer renaming or restructuring first.

Files:

  • pnpm11/network/auth-header/src/getAuthHeadersFromConfig.ts
  • pnpm11/network/auth-header/test/getAuthHeadersFromConfig.test.ts
  • pnpm/crates/network/src/token_helper.rs
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

When checking whether a caught error is an Error in Jest tests, use util.types.isNativeError() instead of instanceof Error.

Files:

  • pnpm11/network/auth-header/test/getAuthHeadersFromConfig.test.ts
pnpm/**/*.rs

📄 CodeRabbit inference engine (pnpm/AGENTS.md)

pnpm/**/*.rs: Keep pacquet and the TypeScript pnpm CLI behaviorally identical, including commands, flags, defaults, errors, file formats, logs, layouts, and hooks.
When changing pacquet behavior, update the corresponding TypeScript pnpm workspace in the same PR, or document why the change cannot yet be matched.
Match observable behavior rather than mirroring the TypeScript implementation's structure.
Keep reporter pnpm:<channel> emissions identical between implementations, including call site, payload, and ordering.
Prefer real fixtures such as tempfile::TempDir, the mocked registry, or integration tests; use dependency injection only for unreachable filesystem, time, process-global-state, or external-service branches.
Represent TypeScript branded strings with Rust newtype wrappers rather than plain String or &str.
For branded strings that upstream always validates, construct them only through validating TryFrom<String> and/or FromStr; do not expose an infallible arbitrary-string constructor.
For upstream brands that are never runtime-validated, expose infallible From<String> and, when useful, From<&str> conversions.
When upstream sometimes bypasses validation, provide an explicit from_str_unchecked-style escape hatch while retaining the validating constructor.
Use serde #[serde(try_from = "String")] for validated deserialization and #[serde(into = "String")] for serialization of branded types crossing file-format boundaries.
Use derive_more::From and derive_more::Into for mechanical branded-string conversions; write manual implementations only for validation or normalization logic.
Model TypeScript string-literal unions as Rust enums, not newtype wrappers.
Model TypeScript template-literal string types as branded Rust newtypes using the applicable validation and serde rules.
Use owned or borrowed parameters to minimize copies, widening parameters to types such as &Path over &PathBuf and &str over &String when possible.
Prefer `Ar...

Files:

  • pnpm/crates/network/src/token_helper.rs
pnpm/**/src/**/*.rs

📄 CodeRabbit inference engine (pnpm/AGENTS.md)

Keep tests alongside the code they exercise using standard Cargo layout; use crate tests/ directories for integration tests.

Files:

  • pnpm/crates/network/src/token_helper.rs
🧠 Learnings (7)
📚 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/token-helper-timeout.md
📚 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/network/auth-header/src/getAuthHeadersFromConfig.ts
  • pnpm11/network/auth-header/test/getAuthHeadersFromConfig.test.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/network/auth-header/src/getAuthHeadersFromConfig.ts
  • pnpm11/network/auth-header/test/getAuthHeadersFromConfig.test.ts
📚 Learning: 2026-06-05T13:47:05.929Z
Learnt from: vsumner
Repo: pnpm/pnpm PR: 12190
File: installing/deps-installer/test/install/frozenStore.ts:2-17
Timestamp: 2026-06-05T13:47:05.929Z
Learning: In the pnpm/pnpm repository, the shared Jest preset keeps `injectGlobals` at its default (`true`), so `test` and `expect` are available as Jest globals. Therefore, reviewers should not flag (or treat as TypeScript/compilation errors) missing `import { test, expect } from 'jest/globals'` when a test file uses `test`/`expect` without importing them. Importing from `jest/globals` may still be used for consistency with sibling files, but it is not required for execution in this repo unless a Jest preset is explicitly configured with `injectGlobals: false`.

Applied to files:

  • pnpm11/network/auth-header/test/getAuthHeadersFromConfig.test.ts
📚 Learning: 2026-06-06T18:58:37.156Z
Learnt from: zkochan
Repo: pnpm/pnpm PR: 12243
File: pacquet/crates/package-manager/src/install_package_by_snapshot.rs:319-322
Timestamp: 2026-06-06T18:58:37.156Z
Learning: When reviewing Rust code, do not assume `matches!(expr, Pattern(_))` will move out of `expr` if `Pattern(_)` contains no by-value bindings. `matches!` desugars to a `match` that auto-borrows the scrutinee for discrimination, so even if `expr` is a non-`Copy` value behind a shared reference (e.g., `&T`), the macro should not move-out of the borrowed data purely due to `matches!`. Treat `matches!(&expr, Pattern(_))` as a readability/clarity improvement, not a correctness requirement. Only flag potential move-out-of-borrow risks when the pattern includes by-value bindings that would require moving the matched value.

Applied to files:

  • pnpm/crates/network/src/token_helper.rs
📚 Learning: 2026-06-12T20:41:57.558Z
Learnt from: zkochan
Repo: pnpm/pnpm PR: 12364
File: pacquet/crates/package-manager/src/install/tests.rs:5717-5717
Timestamp: 2026-06-12T20:41:57.558Z
Learning: In the pnpm/pnpm Rust workspace (toolchain Rust 1.95.0), keep using `std::time::Duration::from_mins(...)` and `std::time::Duration::from_hours(...)` as-is. Do not flag these as invalid or suggest replacing them with `Duration::from_secs(...)`, because Clippy’s `clippy::duration_suboptimal_units` lint is denied by `-D warnings` in CI, and changing to seconds may trigger CI failures.

Applied to files:

  • pnpm/crates/network/src/token_helper.rs
📚 Learning: 2026-06-29T10:07:32.128Z
Learnt from: KSXGitHub
Repo: pnpm/pnpm PR: 12719
File: pacquet/crates/cli/tests/update.rs:56-56
Timestamp: 2026-06-29T10:07:32.128Z
Learning: When reviewing Rust code, do not flag `format!`, `write!`, or `writeln!` calls as having “missing format arguments” if the format string is a raw string literal (e.g., `r#"...{name}..."#`, `br#"...{spec}..."#`) that uses Rust’s captured-format-argument syntax (`{name}`, `{spec}`, etc.). Raw string literals still support captured-format placeholders, so the code is valid as long as those captured names correspond to in-scope variables and compiles.

Applied to files:

  • pnpm/crates/network/src/token_helper.rs
🪛 ast-grep (0.44.1)
pnpm11/network/auth-header/src/getAuthHeadersFromConfig.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)
.changeset/token-helper-timeout.md (1)

1-7: LGTM!

pnpm11/network/auth-header/src/getAuthHeadersFromConfig.ts (1)

77-92: LGTM!

pnpm11/network/auth-header/test/getAuthHeadersFromConfig.test.ts (1)

6-6: LGTM!

Also applies to: 88-93

pnpm/crates/network/src/token_helper.rs (1)

11-25: LGTM!

Also applies to: 45-55, 58-79, 88-114, 175-184, 206-216

Comment thread pnpm/crates/network/src/token_helper.rs Resolved
resolve_entry held the shared resolved-token-helpers Mutex for the entire
duration of the helper subprocess, so a slow (up to the 60s timeout) or hung
helper for one registry blocked every other registry's auth lookup that hit a
tokenHelper entry.

Key each cache slot by a per-key OnceLock instead: the shared Mutex is now held
only briefly to fetch-or-insert the slot, and the subprocess runs while the
Mutex is free. OnceLock still serializes concurrent first-lookups of the same
key, so a helper runs at most once. A regression test asserts a second
registry's lookup completes while a slow helper is still running.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 13, 2026 13: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.

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 44a1473

…anic

run_token_helper_command spawned the child and then created reader threads
before the wait loop; a panic in between (a failed thread::spawn) would drop the
Child without killing it, leaving an orphaned process. std has no
`kill_on_drop`, so wrap the child in a ChildGuard that kills it on drop until it
is disarmed once the process has been reaped (killing a reaped pid could hit a
recycled process). This also subsumes the explicit kill on the timeout path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 13, 2026 13:23

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 was updated up to the latest commit 722a623

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

project-level validation error for global-level tokenHelper config

3 participants