Skip to content

feat(pacquet): port the stage command and add its -/stage endpoints to pnpr - #12922

Merged
zkochan merged 12 commits into
mainfrom
pq-stage
Jul 10, 2026
Merged

zkochan merged 12 commits into
mainfrom
pq-stage

Conversation

@zkochan

@zkochan zkochan commented Jul 10, 2026 •

Copy link
Copy Markdown
Member

Summary

Ports pnpm stage to the Rust CLI and implements the registry side of staged publishing in pnpr, so the two stacks stay at feature parity and the Rust CLI has a real registry to stage against.

Rust CLI (pnpm/):

  • All six subcommands with the TypeScript CLI's surface, error codes, endpoints, and output: publish (regular publish pipeline against the staging endpoint, + [email protected] (staged with id …) / (would stage) lines or a name-keyed --json map), list (paginated with package filter and package-scoped auth), view, approve / reject (full OTP / web-auth challenge handling, configured --otp on the first attempt), and download (tarball summary in the publish --json shape, with traversal-safe filenames).
  • Fixes the staged-publish route in pacquet-publish: a staged upload now sends POST /-/stage/package/:pkg (libnpmpublish's stage route) instead of the regular packument PUT. This path was previously unreachable because the CLI hardcoded stage: false.

pnpr:

  • POST /-/stage/package/:pkg validates and authorizes exactly like a direct publish, then holds the document under a fresh UUID; GET /-/stage (paginated, package filter, filtered to what the caller may publish), GET /-/stage/:id, GET /-/stage/:id/tarball, POST /-/stage/:id/approve (replays through the regular validate → stage → commit flow, so a version published in the meantime surfaces as the usual 409), DELETE /-/stage/:id. Each route has a /~<registry>/-prefixed twin, and a record is only visible through the address it was staged with. Records persist under a reserved .staged/ namespace on both the fs and S3 backends.

Also fixes a broken test on main (a semantic conflict between two green-merged PRs, #12910 and #12914): pacquet install scaffolded a root package.json at a manifest-less workspace root, which the verify-deps-before-run install wrote to disk and a [<since>] filter then selected as a runnable project with the init template's failing test script. State::init now uses the scaffold in memory without persisting it when a pnpm-workspace.yaml sits next to the missing manifest, matching the TypeScript CLI (which never scaffolds).

The TypeScript side needed one change, prompted by review: pnpm stage list gained the same fail-safe pagination cap (1000 pages) as the Rust port, with a patch changeset. The Rust download path additionally caps the tarball body and its decompression at 512 MiB each — following the dist-tag precedent of hardening beyond the TypeScript implementation, which reads these unbounded. One deliberate micro-divergence: a 401 OTP challenge on the read-only stage GETs surfaces as ERR_PNPM_STAGE_REGISTRY_ERROR rather than TS's internal SyntheticOtpError leaking through; no registry challenges GETs in practice.

Squash Commit Body

Port `pnpm stage` (publish, list, view, approve, reject, download) to the
Rust CLI, mirroring the TypeScript command's flags, error codes, endpoints,
and output. `stage publish` reuses the publish pipeline (PublishArgs is
split into a reusable PublishFlags, and the pipeline returns summaries
instead of printing); approve/reject drive the shared OTP / web-auth flow;
download summarizes the tarball with the same traversal protections as
the TypeScript implementation. Also fixes the staged-publish route in
pacquet-publish to POST -/stage/package/:pkg (libnpmpublish's stage route)
instead of the regular packument PUT — previously unreachable because the
CLI hardcoded stage: false.

pnpr grows the server half: POST /-/stage/package/:pkg validates and
authorizes like a direct publish and holds the document under a UUID;
list/view/tarball inspect held records; approve replays the document
through the regular validate/stage/commit flow; reject deletes it. Records
persist under a reserved .staged/ namespace on the fs and S3 backends,
with stage-id validation ahead of any path or object key.

Shared plumbing: the capped response-body reader moves from the dist-tag
command into pacquet-network, and pacquet-pack exports its en-locale path
sort for the tarball summary.

Also fixes a broken test on main (semantic conflict between
pnpm/pnpm#12910 and pnpm/pnpm#12914): State::init no longer persists a
scaffolded root package.json when a pnpm-workspace.yaml sits next to the
missing manifest, so a verify-deps-before-run install can't turn the
workspace root into a selectable project with the init template's failing
test script.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port (the TypeScript stage command already exists; this PR is its
    Rust port, plus the pnpr server side).
  • Added a changeset (for the TypeScript-side stage list pagination cap).
  • Added or updated tests.

Written by an agent (Claude Code, claude-fable-5).

Summary by CodeRabbit

  • New Features
    • Added staged publishing via pnpm stage (publish, list, view, approve, reject, download) with both JSON and human-readable output, including staged tarball details.
    • Introduced server-side staging endpoints backed by filesystem and cloud storage.
  • Bug Fixes
    • Prevented workspace root package.json scaffolding when only pnpm-workspace.yaml is present.
    • Added a fail-safe cap to stop stage list pagination after excessive pages.
    • Hardened error/body handling and made stage download filenames/paths safer against traversal.

zkochan and others added 5 commits July 10, 2026 23:13
…workspace

A workspace root defined by pnpm-workspace.yaml alone is legal without a
root manifest, and the TypeScript CLI never scaffolds one. pacquet's
State::init did, which turned the workspace root into a selectable
project carrying the init template's failing test script: a
verify-deps-before-run install spawned by a recursive run would write
the manifest, and a changed-packages filter picking up a root-level
change would then select and run it. State::init now uses the scaffold
manifest in memory without persisting it when a pnpm-workspace.yaml
sits next to the missing package.json.

Co-Authored-By: Claude Fable 5 <[email protected]>
The server half of the stage command. POST -/stage/package/:pkg accepts
a regular publish document, validates and authorizes it exactly like a
direct publish, and holds it back under a fresh UUID stage id instead of
committing it. GET -/stage lists the held records (paginated, package
filter, filtered to what the caller may publish), GET -/stage/:id and
GET -/stage/:id/tarball inspect one, POST -/stage/:id/approve replays
the held document through the regular validate/stage/commit publish flow
(so a version published in the meantime surfaces as the usual 409), and
DELETE -/stage/:id rejects it. Every route has a registry-prefixed twin,
and a record is only visible through the address it was staged with.

Records persist as two objects (metadata plus the raw publish body)
under a reserved .staged/ namespace of the hosted store on both the fs
and S3 backends. The leading dot keeps them out of the package
namespace, the storage layer validates stage ids before they reach a
path or object key, and the package-name listings never surface them.

Co-Authored-By: Claude Fable 5 <[email protected]>
Ports pnpm stage with all six subcommands, matching the TypeScript CLI's
surface, error codes, endpoints, and output:

- stage publish runs the regular publish pipeline (packing, lifecycle
  scripts, OIDC, OTP/web-auth) against the registry's staging endpoint
  and renders staged-with-id lines or a name-keyed --json map.
- stage list / view read the -/stage API (paginated, package filter with
  package-scoped auth, version specifiers rejected).
- stage approve / reject drive POST -/stage/:id/approve and
  DELETE -/stage/:id through the shared OTP / web-auth flow, sending any
  configured --otp on the first attempt.
- stage download fetches -/stage/:id/tarball, summarizes the tarball in
  the publish --json shape, and writes it under a validated filename
  (package name, semver version, and separator checks block traversal
  through a hostile manifest).

Also fixes the staged-publish route in pacquet-publish: a staged upload
now sends POST -/stage/package/:pkg (libnpmpublish's stage route)
instead of the regular packument PUT. The path was previously
unreachable because the CLI hardcoded stage: false.

Supporting refactors: PublishArgs splits its flags into a reusable
PublishFlags and returns summaries instead of printing them; the capped
response-body reader moves into pacquet-network (shared with dist-tag);
pacquet-pack exports its en-locale path sort for the tarball summary.

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@coderabbitai

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: ead0eb2c-cffe-42a8-b1e8-2cf72ff9e4e7

📥 Commits

Reviewing files that changed from the base of the PR and between 593c7dd and 599672b.

📒 Files selected for processing (2)
  • pnpm/crates/cli/tests/stage.rs
  • pnpm11/releasing/commands/test/stage.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • pnpm11/releasing/commands/test/stage.test.ts
  • pnpm/crates/cli/tests/stage.rs

📝 Walkthrough

Walkthrough

Adds Rust support for two-phase package publishing through pnpm stage, including CLI subcommands, staging-aware publish requests, registry endpoints, filesystem/S3 persistence, tarball handling, authorization, and tests. It also centralizes bounded response handling and prevents workspace-root manifest scaffolding.

Changes

Staged publishing

Layer / File(s) Summary
CLI stage commands and publish pipeline
pnpm/crates/cli/src/cli_args/*, pnpm/crates/cli/tests/stage.rs
Adds stage subcommands, staging-aware publishing, output rendering, OTP handling, pagination, validation, tarball summarization, and end-to-end tests.
Shared response and publish primitives
pnpm/crates/network/*, pnpm/crates/pack/src/lib.rs, pnpm/crates/package-manifest/src/lib.rs, pnpm/crates/publish/src/*
Adds bounded response-body reading, shared path sorting, manifest initialization, and staging-specific publish URLs and HTTP methods.
Staged record persistence
pnpr/crates/pnpr/src/storage.rs, pnpr/crates/pnpr/src/s3.rs
Stores staged metadata and bodies separately and supports filesystem and S3 operations.
Registry stage routes and lifecycle
pnpr/crates/pnpr/src/server.rs, pnpr/crates/pnpr/src/server/staged.rs, pnpr/crates/pnpr/tests/staged_publish.rs
Adds stage creation, listing, viewing, approval, rejection, tarball download, authorization, UUID generation, and lifecycle tests.
Workspace and release safeguards
pnpm/crates/cli/src/state.rs, pnpm/crates/cli/tests/workspace_install.rs, pnpm11/releasing/commands/*, .changeset/*
Keeps workspace roots without package.json from being scaffolded and limits stage-list pagination to 1000 pages.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI as pnpm stage
  participant Registry as pnpr stage routes
  participant Storage as staged storage
  CLI->>Registry: POST staged publish
  Registry->>Storage: write staged body and metadata
  CLI->>Registry: GET list/view/download
  Registry->>Storage: read staged record or tarball
  CLI->>Registry: POST approve or DELETE reject
  Registry->>Storage: promote or remove staged data
Loading

Possibly related issues

  • Rust Roadmap #11633 — Directly covers the Rust stage command and staged publishing workflow implemented here.

Possibly related PRs

  • pnpm/pnpm#12195 — Refactors the pnpr storage layer extended here with staged-record operations.
  • pnpm/pnpm#12691 — Provides related publish-pipeline behavior extended with staging support.
  • pnpm/pnpm#12747 — Changes pnpr registry routing related to the staged endpoints added here.

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

Suggested reviewers: juanpicado

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch pq-stage

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

Copy link
Copy Markdown

PR Summary by Qodo

Port pnpm stage to Rust CLI and add pnpr -/stage staged publishing API

✨ Enhancement 🐞 Bug fix 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Add pacquet stage subcommands mirroring pnpm’s flags, output, and error codes.
• Implement pnpr -/stage endpoints with .staged/ persistence on fs and S3 backends.
• Fix workspace install scaffolding root package.json; add CLI/server integration tests.
Diagram

graph TD
  cli["pacquet CLI"] --> stage["stage command"] --> publish["publish pipeline"] --> pnpr["pnpr registry"] --> routes["-/stage endpoints"] --> storage[".staged records"] --> backend[("FS / S3")]
  stage --> tarball[["tarball summary"]]

  subgraph Legend
    direction LR
    _svc["Service/Module"] ~~~ _lib[["Library/helper"]] ~~~ _db[("Storage")]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use `uuid` crate for stage-id validation/generation
  • ➕ Less bespoke UUID parsing/formatting code to maintain
  • ➕ Built-in validation for v4, hyphenation, and edge cases
  • ➖ Adds/expands dependency surface
  • ➖ Current implementation is already constrained and well-tested
2. Parse list query via `serde_urlencoded`/axum `Query` extractor
  • ➕ More robust decoding and typing for page/perPage/package
  • ➕ Less custom parsing logic
  • ➖ Behavioral parity risk vs pnpm’s permissive parsing (ignoring unknown/unparsable keys)
  • ➖ May require extra struct tagging or custom deserializers

Recommendation: The PR’s approach (reuse publish pipeline + add explicit staged storage + mirror pnpm UX) is the right baseline for parity and reduces duplicated logic. Consider swapping to the uuid crate later if UUID handling grows; current manual UUID generation/validation is acceptable given the added tests and storage-layer guardrails.

Files changed (29) +3248 / -105

Enhancement (14) +1871 / -34
cli_args.rsRegister new 'stage' CLI args module +1/-0

Register new 'stage' CLI args module

• Exports 'cli_args::stage' so the command is available to the CLI command enum and dispatcher.

pnpm/crates/cli/src/cli_args.rs

cli_command.rsAdd 'stage' command to top-level CLI command enum +4/-0

Add 'stage' command to top-level CLI command enum

• Introduces 'CliCommand::Stage(StageArgs)' with help text describing staged/two-phase publish behavior.

pnpm/crates/cli/src/cli_args/cli_command.rs

dispatch.rsRoute 'CliCommand::Stage' to query dispatcher +1/-0

Route 'CliCommand::Stage' to query dispatcher

• Wires the new stage command into the central command routing so it executes within the existing run context.

pnpm/crates/cli/src/cli_args/dispatch.rs

dispatch_query.rsAdd stage dispatcher with sanitized output printing +37/-1

Add stage dispatcher with sanitized output printing

• Adds a 'stage()' dispatcher mirroring 'publish()'’s dispatch shape: capture owned values, run subcommand, sanitize output, and print based on reporter type. Adjusts publish dispatch to reflect refactored 'PublishArgs.flags' field.

pnpm/crates/cli/src/cli_args/dispatch_query.rs

publish.rsSplit publish args into reusable flags and return publish summaries +78/-26

Split publish args into reusable flags and return publish summaries

• Splits 'PublishArgs' into positional 'package' plus reusable 'PublishFlags' for 'stage publish' parity. Refactors publish execution to return 'PublishedPackages' summaries so callers can render either pnpm publish JSON or stage-specific output, and adds 'stage' parameter to route staged uploads.

pnpm/crates/cli/src/cli_args/publish.rs

recursive.rsThread stage mode through recursive publish pipeline +7/-6

Thread stage mode through recursive publish pipeline

• Updates recursive publish flow to read flags from 'PublishFlags' and propagate 'stage' to publish options so recursive staging uses the staging endpoint.

pnpm/crates/cli/src/cli_args/publish/recursive.rs

stage.rsImplement 'pacquet stage' subcommands and OTP/web-auth flow +763/-0

Implement 'pacquet stage' subcommands and OTP/web-auth flow

• Adds the Rust 'stage' command with 'publish/list/view/approve/reject/download' subcommands, matching pnpm endpoints, output formats, and error codes. Implements pagination and package-scoped auth for list, UUID validation for stage ids, registry error rendering with capped bodies, and OTP/web-auth challenge handling for mutations.

pnpm/crates/cli/src/cli_args/stage.rs

summarize_tarball.rsSummarize staged tarball bytes into pnpm publish-summary shape +137/-0

Summarize staged tarball bytes into pnpm publish-summary shape

• Implements tarball parsing (gzip or plain) to extract manifest/name/version, compute summary fields, list contents in pnpm-like locale order, and detect bundled dependencies. Adds traversal-safe tarball filename construction based on validated name/version/suffix.

pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs

switch_cli_version.rsInclude 'stage' in command-name mapping +1/-0

Include 'stage' in command-name mapping

• Ensures the command name resolver recognizes 'stage', keeping CLI-version switching consistent with other commands.

pnpm/crates/cli/src/cli_args/switch_cli_version.rs

limited_body.rsImplement capped response-body buffering helper +33/-0

Implement capped response-body buffering helper

• Adds 'read_limited_body()' to cap buffered responses and record truncation, preventing large registry responses from exhausting memory for buffered reads (errors/JSON bodies).

pnpm/crates/network/src/limited_body.rs

s3.rsAdd S3 support for staged record objects under '.staged/' +49/-1

Add S3 support for staged record objects under '.staged/'

• Implements read/write/delete/list helpers for staged meta/body objects in S3 using the shared staged namespace and stage-id filtering. Enables staged publishing persistence on the S3 backend.

pnpr/crates/pnpr/src/s3.rs

server.rsRegister staged publishing routes in pnpr router +20/-0

Register staged publishing routes in pnpr router

• Adds '/-/stage' endpoints and '/~<registry>/'-prefixed twins to the main router, and wires in the new 'staged' module.

pnpr/crates/pnpr/src/server.rs

staged.rsImplement pnpr '-/stage' API: hold/list/view/tarball/approve/reject +596/-0

Implement pnpr '-/stage' API: hold/list/view/tarball/approve/reject

• Adds the server-side staged publishing surface: stage publish stores validated publish docs under a UUID, list filters by caller publish rights and optional package, view returns metadata, tarball decodes attachment bytes, approve replays the publish flow and then cleans up, reject deletes record. Enforces registry-prefix visibility and adds capability-oriented UUID stage ids with storage-layer validation.

pnpr/crates/pnpr/src/server/staged.rs

storage.rsAdd staged record storage API and '.staged/' backend support +144/-0

Add staged record storage API and '.staged/' backend support

• Introduces staged meta/body read/write/remove/list operations on 'Storage', backed by a reserved '.staged/' namespace. Adds validation to prevent stage-id path/key smuggling and implements fs+S3 hosted-store support including listing only meta objects.

pnpr/crates/pnpr/src/storage.rs

Bug fix (2) +21 / -3
state.rsAvoid persisting scaffolded root manifest in manifest-less workspaces +10/-0

Avoid persisting scaffolded root manifest in manifest-less workspaces

• Changes manifest creation logic to keep an in-memory scaffold when 'pnpm-workspace.yaml' exists without a root 'package.json'. Prevents 'install' and recursive selection from turning the workspace root into a runnable project.

pnpm/crates/cli/src/state.rs

publish_packed_pkg.rsFix staged publish to use 'POST /-/stage/package/:pkg' +11/-3

Fix staged publish to use 'POST /-/stage/package/:pkg'

• Updates staged publishing to target the staging endpoint and to POST (libnpmpublish-compatible) rather than PUTting the packument route. Keeps regular publish behavior unchanged.

pnpm/crates/publish/src/publish_packed_pkg.rs

Refactor (5) +42 / -50
dist_tag.rsRefactor limited-body reading into reusable network helper +13/-41

Refactor limited-body reading into reusable network helper

• Switches dist-tag error handling to use 'pacquet_network::LimitedBody' + 'read_limited_body'. Extracts a shared 'body_display_string()' for rendering sanitized/truncated response bodies.

pnpm/crates/cli/src/cli_args/dist_tag.rs

lib.rsExport limited-body reader from pacquet-network +2/-0

Export limited-body reader from pacquet-network

• Adds a new 'limited_body' module and re-exports 'LimitedBody' and 'read_limited_body' for safe capped buffering of registry responses.

pnpm/crates/network/src/lib.rs

lib.rsExport pnpm-like locale path sorting for tarball listings +12/-4

Export pnpm-like locale path sorting for tarball listings

• Refactors packed-contents sorting into a public 'sort_paths_en_locale()' function and reuses it internally. Enables stage tarball summary output to match pnpm’s ordering.

pnpm/crates/pack/src/lib.rs

lib.rsExpose init scaffold manifest value without writing to disk +11/-4

Expose init scaffold manifest value without writing to disk

• Extracts 'PackageManifest::init_value_for()' so callers (like 'State::init') can build scaffold manifests in-memory without persisting files. Keeps existing 'create_if_needed' behavior by reusing the extracted helper.

pnpm/crates/package-manifest/src/lib.rs

search.rsExpose percent-decoder for staged query parsing +4/-1

Expose percent-decoder for staged query parsing

• Makes 'percent_decode' public(crate) so staged list query parsing can reuse it consistently for ASCII-oriented query decoding.

pnpr/crates/pnpr/src/search.rs

Tests (7) +1311 / -15
tests.rsUpdate publish unit tests for 'PublishFlags' and staged option +21/-12

Update publish unit tests for 'PublishFlags' and staged option

• Reworks test helpers to construct 'PublishArgs' via 'PublishFlags' and updates calls to 'publish_options(..., stage)' to match the new signature.

pnpm/crates/cli/src/cli_args/publish/tests.rs

tests.rsAdd unit tests for stage helpers and tarball summarization +240/-0

Add unit tests for stage helpers and tarball summarization

• Covers UUID validation, stage-id requirement errors, package filter parsing rules, output rendering, traversal protections in filename generation, and tarball summarization behavior (gzipped/plain, bundled deps).

pnpm/crates/cli/src/cli_args/stage/tests.rs

stage.rsAdd integration tests for 'pacquet stage' against mock registry +543/-0

Add integration tests for 'pacquet stage' against mock registry

• Introduces end-to-end tests covering staging publish (POST to '/-/stage/package/:pkg'), list/view pagination and filtering, package-scoped auth, approve/reject headers + OTP, web-auth/non-interactive behavior, and download tarball traversal protections and JSON output shape.

pnpm/crates/cli/tests/stage.rs

workspace_install.rsTest that workspace install does not scaffold a root package.json +36/-0

Test that workspace install does not scaffold a root package.json

• Adds a regression test ensuring installs in a workspace defined only by 'pnpm-workspace.yaml' do not create a root manifest on disk.

pnpm/crates/cli/tests/workspace_install.rs

tests.rsAdjust publish HTTP method expectations for staged publish +11/-3

Adjust publish HTTP method expectations for staged publish

• Updates tests to expect POST for staged publish and PUT for regular publish, and verifies stage-id extraction only occurs in staged mode.

pnpm/crates/publish/src/publish_packed_pkg/tests.rs

tests.rsUnit test stage-id generation shape and version bits +12/-0

Unit test stage-id generation shape and version bits

• Adds a focused test ensuring stage ids are hyphenated v4 UUIDs and do not trivially collide.

pnpr/crates/pnpr/src/server/staged/tests.rs

staged_publish.rsAdd integration tests for pnpr staged publishing endpoints +448/-0

Add integration tests for pnpr staged publishing endpoints

• Adds hermetic static-mode tests covering stage holdback semantics, list/view/tarball download, approve promotion into regular package storage, reject deletion, scoped packages, pagination/filtering, auth enforcement, conflict on approval when version published meanwhile, and rejection of traversal-shaped stage ids.

pnpr/crates/pnpr/tests/staged_publish.rs

Other (1) +3 / -3
Cargo.tomlAdd stage-command dependencies (tar/flate2/web-auth) to CLI crate +3/-3

Add stage-command dependencies (tar/flate2/web-auth) to CLI crate

• Moves 'pacquet-network-web-auth' to regular dependencies for runtime OTP/web-auth handling. Adds 'flate2' and 'tar' as runtime deps to support 'stage download' tarball summarization.

pnpm/crates/cli/Cargo.toml

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 18 rules

Grey Divider


Action required

1. Stage download OOM risk ✓ Resolved 🐞 Bug ⛨ Security
Description
StageArgs::stage_download buffers the full tarball response in memory and then summarize_tarball
may fully gunzip it into a Vec, so a hostile registry can trigger memory exhaustion via a huge
body or a gzip bomb. This can crash pacquet (including in CI) when users run `pnpm stage
download`.
Code

pnpm/crates/cli/src/cli_args/stage.rs[R310-324]

+    async fn stage_download(&self, dir: &Path, config: &Config) -> miette::Result<Option<String>> {
+        let stage_id = require_stage_id(&self.params, "download")?;
+        let context = self.stage_context(config, None)?;
+        let url = stage_endpoint_url(&context.registry, &format!("-/stage/{stage_id}/tarball"))?;
+        let action = format!("download staged package {stage_id}");
+        let (_guard, response) = stage_send(&context, reqwest::Method::GET, url.as_str(), None)
+            .await
+            .map_err(|source| request_failed(&action, source))?;
+        if !response.status().is_success() {
+            return Err(registry_error_from_response(response, &action).await.into());
+        }
+        let tarball_data =
+            response.bytes().await.map_err(|source| request_failed(&action, source))?;
+
+        let mut summary = summarize_tarball(&tarball_data)?;
Evidence
stage_download reads the entire tarball into memory via response.bytes(), and
summarize_tarball calls maybe_gunzip, which uses read_to_end to fully decompress untrusted
gzip data into a Vec with no output limit, enabling memory amplification.

pnpm/crates/cli/src/cli_args/stage.rs[308-326]
pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs[19-33]
pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs[125-132]

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 stage download` currently calls `response.bytes()` and then summarizes the tarball by optionally gunzipping the whole payload into memory. A malicious or compromised registry can respond with (a) a very large body or (b) a small gzip payload that expands massively, causing OOM/panic and crashing the CLI.

### Issue Context
This is a newly introduced command path that treats registry responses/tarballs as trusted. Per repo security guidance, tarballs/registry responses must be treated as attacker-controlled.

### Fix Focus Areas
- Add a hard cap when downloading the tarball (e.g. 100 MiB, matching pnpr’s publish/tarball cap), rejecting bodies that exceed it.
- Avoid full in-memory gunzip. Prefer streaming tar parsing directly from a `Read`/decoder, and enforce a maximum *decompressed* byte budget when iterating entries.
- If you still need the original bytes for hashing/summary, write the downloaded tarball to a temp file while hashing, then summarize by streaming from the file.

### Fix Focus Areas (code pointers)
- pnpm/crates/cli/src/cli_args/stage.rs[308-339]
- pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs[19-33]
- pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs[125-132]

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


2. Staged list order wrong 🐞 Bug ≡ Correctness
Description
serve_staged_list claims results are "newest-first" but sorts created_at ascending, producing
oldest-first output and violating the documented listing/pagination contract. Clients relying on
pnpm parity will see reversed ordering.
Code

pnpr/crates/pnpr/src/server/staged.rs[R331-367]

+/// `GET /-/stage?page=&perPage=&package=` — the staged records visible to
+/// the caller through this registry address, newest-first-insensitive
+/// (sorted by staging time, then id, for stable pagination).
+async fn serve_staged_list(
+    state: &AppState,
+    identity: &Identity,
+    registry: Option<&str>,
+    query: &StagedListQuery,
+) -> Response {
+    let per_page = query.per_page.clamp(1, MAX_PER_PAGE);
+    let ids = match state.inner.storage.list_staged_ids().await {
+        Ok(ids) => ids,
+        Err(err) => return error_response(&err),
+    };
+    let mut records: Vec<StagedRecord> = Vec::new();
+    for stage_id in ids {
+        let Ok(Some(record)) = read_staged_record(state, &stage_id).await else {
+            continue;
+        };
+        if record.registry.as_deref() != registry {
+            continue;
+        }
+        if let Some(package) = &query.package
+            && &record.package_name != package
+        {
+            continue;
+        }
+        // The listing shows only what the caller could publish (and thus
+        // approve); records outside their rights are simply not theirs to see.
+        if authorize_staged(state, identity, &record).await.is_err() {
+            continue;
+        }
+        records.push(record);
+    }
+    records.sort_by(|left, right| {
+        left.created_at.cmp(&right.created_at).then_with(|| left.id.cmp(&right.id))
+    });
Evidence
The code comment states newest-first, but cmp on created_at is applied in ascending order, which
yields oldest-first ordering.

pnpr/crates/pnpr/src/server/staged.rs[331-367]

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 staged list endpoint documents newest-first ordering, but the comparator is ascending on `created_at`.

### Issue Context
This is user-visible API behavior and affects pagination stability and pnpm parity.

### Fix Focus Areas
- Reverse the sort (`right.created_at.cmp(&left.created_at)`) and keep the stable tiebreak on `id` (also reversed if you want strict newest-first on ties).
- Consider adding a unit/integration test that asserts ordering with multiple records.

### Fix Focus Areas (code pointers)
- pnpr/crates/pnpr/src/server/staged.rs[331-379]

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



Remediation recommended

3. Rust test HTTP hangs ✓ Resolved 🐞 Bug ☼ Reliability ⭐ New
Description
The new pnpr end-to-end stage tests perform reqwest HTTP requests without any timeout (e.g., in
add_user/packument_status), so a stalled hosted registry can hang the test process indefinitely and
stall CI. Because these are synchronous tests, there’s no per-test timeout safety net.
Code

pnpm/crates/cli/tests/stage.rs[R450-475]

+    block_on(async {
+        let response = reqwest::Client::new()
+            .put(&url)
+            .json(&body)
+            .send()
+            .await
+            .expect("send the adduser request");
+        assert_eq!(response.status().as_u16(), 201, "adduser must succeed");
+        let payload: Value = response.json().await.expect("parse the adduser response");
+        payload["token"].as_str().expect("token in the adduser response").to_owned()
+    })
+}
+
+/// The HTTP status of a plain packument read, bypassing the CLI.
+fn packument_status(registry: &str, token: &str, name: &str) -> u16 {
+    let url = format!("{registry}{name}");
+    block_on(async {
+        reqwest::Client::new()
+            .get(&url)
+            .bearer_auth(token)
+            .send()
+            .await
+            .expect("send the packument request")
+            .status()
+            .as_u16()
+    })
Evidence
The tests issue HTTP requests via reqwest but never configure a timeout or wrap the futures with
tokio::time::timeout, meaning an unresponsive registry can block forever at .send().await.

pnpm/crates/cli/tests/stage.rs[431-475]
pnpm/crates/cli/tests/stage.rs[638-659]

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/crates/cli/tests/stage.rs` makes live HTTP requests to the hosted in-process pnpr using `reqwest::Client::new()` without any timeout. If pnpr stops responding (panic in server thread, deadlock, or request handler bug), the await can block forever, stalling CI.

### Issue Context
These are end-to-end tests; network calls are expected, but they should be *bounded* so failures surface as test failures instead of indefinite hangs.

### Fix Focus Areas
- Add request timeouts (e.g., build a shared `reqwest::Client` via `Client::builder().timeout(...)`) and use it in `add_user`, `packument_status`, and the HTTP seeding loop.
- Alternatively (or additionally), wrap the awaited request futures with `tokio::time::timeout` inside `block_on` to enforce a global bound for all async operations.

- pnpm/crates/cli/tests/stage.rs[431-475]
- pnpm/crates/cli/tests/stage.rs[638-659]

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


4. Gzip errors misclassified 🐞 Bug ☼ Reliability
Description
maybe_gunzip treats any gzip decode error as “not gzipped” and falls back to raw bytes, so
malformed gzip input won’t be reported as a decompression failure. This can surface as misleading
tar/manifest errors and makes diagnosing bad registry responses harder.
Code

pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs[R135-144]

+        Ok(_) if decompressed.len() as u64 > MAX_DECOMPRESSED_TARBALL_BYTES => {
+            Err(StageError::RequestFailed {
+                operation: "read the staged tarball".to_owned(),
+                reason: format!(
+                    "tarball exceeded {MAX_DECOMPRESSED_TARBALL_BYTES} bytes when decompressed",
+                ),
+            })
+        }
+        Ok(_) => Ok(decompressed),
+        Err(_) => Ok(data.to_vec()),
Evidence
The function’s documentation claims fallback for non-gzip inputs, but the `Err(_) =>
Ok(data.to_vec())` branch triggers for malformed gzip streams too, misclassifying corruption as a
plain-tar case.

pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs[125-145]

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

### Issue description
`maybe_gunzip` currently falls back to `Ok(data.to_vec())` on *any* `GzDecoder` error, which conflates “not gzipped” with “gzipped but corrupt.” This can hide decompression failures behind later tar parsing errors.

### Issue Context
The comment says fallback should happen when the tarball is not gzipped, but the code uses a broad `Err(_)` catch.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs[125-145]

Suggested fix pattern:
- Detect gzip by magic bytes (0x1F, 0x8B) before attempting to decode.
- If magic matches and decoding fails, return a `StageError::RequestFailed` (or a dedicated error) instead of falling back.
- (Optional) Consider returning `Cow<[u8]>` to avoid copying in the non-gzip case.

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


5. Staged body delete leak 🐞 Bug ☼ Reliability
Description
Storage::remove_staged logs and ignores failures deleting the staged body after removing metadata,
leaving orphaned .body.json objects that are no longer discoverable via the normal staged listing
flow. This can cause persistent storage growth and unintended retention of unpublished package
contents when the backend delete intermittently fails.
Code

pnpr/crates/pnpr/src/storage.rs[R533-535]

+        if let Err(err) = self.hosted.remove_staged(&staged_body_object(stage_id)?).await {
+            tracing::warn!(error = %err, stage_id, "staged body cleanup failed after removing its metadata");
+        }
Evidence
The storage layer explicitly swallows body-deletion errors after removing metadata, and staged
discovery/listing is metadata-driven (body objects are ignored), so a body-delete failure can strand
data. The server endpoints treat remove_staged as success and return 204, so callers are not
prompted to retry cleanup.

pnpr/crates/pnpr/src/storage.rs[525-537]
pnpr/crates/pnpr/src/storage.rs[812-819]
pnpr/crates/pnpr/src/server/staged.rs[401-413]

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

### Issue description
`Storage::remove_staged` deletes the staged metadata and then swallows body-deletion errors (warn-only). If body deletion fails, the orphaned body becomes operationally hard/impossible to clean up via the normal staged APIs because staged discovery is driven by metadata.

### Issue Context
The implementation currently prefers removing metadata first (to avoid listing records whose body is gone), but this also means a body-delete failure can strand large blobs.

### Fix Focus Areas
- pnpr/crates/pnpr/src/storage.rs[525-537]

Potential approaches:
- Read and keep the metadata bytes first; if body deletion fails, best-effort restore/rewrite the metadata and return an error so callers can retry.
- Alternatively, enqueue a durable cleanup job/tombstone so orphaned bodies can be retried/GC’d later.
- If keeping the current order, consider scanning and cleaning orphaned bodies (body-without-meta) as part of a periodic maintenance task or during `list_staged_ids`.

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


View more (4)
6. stage_download adds tarball size cap 📘 Rule violation ≡ Correctness
Description
pnpm stage download now errors if the registry tarball response exceeds STAGE_TARBALL_BODY_LIMIT
(512 MiB), which is user-visible behavior not present in pnpm’s TypeScript implementation. This
creates a compatibility divergence for very large (or malicious) staged tarballs.
Code

pnpm/crates/cli/src/cli_args/stage.rs[R331-339]

+        let tarball_data = read_limited_body(response, STAGE_TARBALL_BODY_LIMIT)
+            .await
+            .map_err(|source| request_failed(&action, source))?;
+        if tarball_data.truncated {
+            return Err(StageError::RequestFailed {
+                operation: action,
+                reason: format!("registry response exceeded {STAGE_TARBALL_BODY_LIMIT} bytes"),
+            }
+            .into());
Evidence
Pacquet truncates/blocks staged tarball downloads over 512 MiB and emits an explicit error, while
pnpm’s TypeScript stageDownload reads the entire tarball into memory without any equivalent cap,
creating an observable divergence.

Rule 713429: Pacquet must not introduce new user-visible behavior beyond pnpm
pnpm/crates/cli/src/cli_args/stage.rs[331-339]
pnpm11/releasing/commands/src/stage/download.ts[17-24]

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’s `stage download` enforces a hard response-size cap (`STAGE_TARBALL_BODY_LIMIT`) and returns `ERR_PNPM_STAGE_REGISTRY_ERROR` when exceeded, but pnpm’s TypeScript `stage download` reads the full tarball with no equivalent limit. This introduces user-visible behavior beyond pnpm.

## Issue Context
Compliance requires pacquet not to introduce new user-visible behavior beyond pnpm (or to keep both implementations in sync).

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/stage.rs[331-339]
- pnpm11/releasing/commands/src/stage/download.ts[17-24]

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


7. maybe_gunzip adds inflate cap 📘 Rule violation ≡ Correctness
Description
Pacquet’s tarball summarization rejects gzipped tarballs that inflate beyond
MAX_DECOMPRESSED_TARBALL_BYTES (512 MiB), which is a user-visible behavior change not present in
pnpm’s TypeScript maybeGunzip. This can make pacquet fail on inputs pnpm would accept (or attempt
to process), creating a behavior mismatch.
Code

pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs[R125-142]

+/// Cap on the decompressed tarball; the bytes come from the registry, so a
+/// gzip bomb must not inflate past this into memory.
+const MAX_DECOMPRESSED_TARBALL_BYTES: u64 = 512 * 1024 * 1024;
+
+/// Gunzip `data`, falling back to the raw bytes when it is not gzipped.
+/// Decompression past [`MAX_DECOMPRESSED_TARBALL_BYTES`] is an error.
+fn maybe_gunzip(data: &[u8]) -> Result<Vec<u8>, StageError> {
+    let mut decoder = GzDecoder::new(data).take(MAX_DECOMPRESSED_TARBALL_BYTES + 1);
+    let mut decompressed = Vec::new();
+    match decoder.read_to_end(&mut decompressed) {
+        Ok(_) if decompressed.len() as u64 > MAX_DECOMPRESSED_TARBALL_BYTES => {
+            Err(StageError::RequestFailed {
+                operation: "read the staged tarball".to_owned(),
+                reason: format!(
+                    "tarball exceeded {MAX_DECOMPRESSED_TARBALL_BYTES} bytes when decompressed",
+                ),
+            })
+        }
Evidence
Pacquet explicitly errors when decompressed data exceeds 512 MiB, while pnpm’s TypeScript
maybeGunzip simply attempts gunzip and falls back to raw bytes on error, with no size guard. That
means pacquet has an additional failure mode not present in pnpm.

Rule 713429: Pacquet must not introduce new user-visible behavior beyond pnpm
pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs[125-142]
pnpm11/releasing/commands/src/tarball/summarizeTarball.ts[91-96]

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 imposes a maximum decompressed size for gzipped staged tarballs during summary generation, while pnpm’s TypeScript implementation has no such limit. This is new user-visible behavior beyond pnpm.

## Issue Context
If the limit is intended as a security hardening, pnpm should implement the same limit (and error shape) to preserve parity; otherwise pacquet should avoid adding new externally observable constraints.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs[125-142]
- pnpm11/releasing/commands/src/tarball/summarizeTarball.ts[91-96]

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


8. Staged list scans all 🐞 Bug ➹ Performance
Description
serve_staged_list enumerates every staged id, reads every record, authorizes each, sorts globally,
and only then slices for page/perPage, making the endpoint O(total_records) per request. On S3
this becomes a list of the entire .staged/ prefix plus many GETs, enabling easy CPU/storage
amplification for authorized users.
Code

pnpr/crates/pnpr/src/server/staged.rs[R340-376]

+    let per_page = query.per_page.clamp(1, MAX_PER_PAGE);
+    let ids = match state.inner.storage.list_staged_ids().await {
+        Ok(ids) => ids,
+        Err(err) => return error_response(&err),
+    };
+    let mut records: Vec<StagedRecord> = Vec::new();
+    for stage_id in ids {
+        let Ok(Some(record)) = read_staged_record(state, &stage_id).await else {
+            continue;
+        };
+        if record.registry.as_deref() != registry {
+            continue;
+        }
+        if let Some(package) = &query.package
+            && &record.package_name != package
+        {
+            continue;
+        }
+        // The listing shows only what the caller could publish (and thus
+        // approve); records outside their rights are simply not theirs to see.
+        if authorize_staged(state, identity, &record).await.is_err() {
+            continue;
+        }
+        records.push(record);
+    }
+    records.sort_by(|left, right| {
+        left.created_at.cmp(&right.created_at).then_with(|| left.id.cmp(&right.id))
+    });
+
+    let total = records.len();
+    let items: Vec<Value> = records
+        .iter()
+        .skip(query.page.saturating_mul(per_page))
+        .take(per_page)
+        .map(StagedRecord::metadata)
+        .collect();
+    json_response(
Evidence
The handler calls list_staged_ids() (returns all IDs), then loops through all of them and reads
each record before sorting and applying pagination; on S3, list_staged_ids iterates the full
.staged prefix.

pnpr/crates/pnpr/src/server/staged.rs[334-375]
pnpr/crates/pnpr/src/storage.rs[534-538]
pnpr/crates/pnpr/src/s3.rs[299-313]

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 staged listing endpoint does a full scan+load+authorize+sort of all staged records and only then paginates, so cost grows linearly with total staged records.

### Issue Context
This is especially expensive on S3 backends (full prefix list + per-record reads). It also increases tail latency and can be used for resource amplification by any caller who has publish rights and can create many staged records.

### Fix Focus Areas
- Introduce a pagination-friendly index for staged metadata (e.g., append-only index keyed by `created_at`, or a directory/object layout that supports lexicographic ordering by time while still looking up by stage id).
- If a full redesign is too large: add a server-side cap on max records scanned per request, and/or require/encourage `package` filtering for large result sets.
- Ensure any optimization preserves the “only visible if caller may publish” rule.

### Fix Focus Areas (code pointers)
- pnpr/crates/pnpr/src/server/staged.rs[334-379]
- pnpr/crates/pnpr/src/storage.rs[534-538]
- pnpr/crates/pnpr/src/s3.rs[299-313]

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


9. Staged tarball eager decode 🐞 Bug ➹ Performance
Description
GET /-/stage/:id/tarball base64-decodes the attachment into a Vec<u8> before responding, forcing
a full in-memory tarball allocation per request rather than streaming. This increases memory
pressure and reduces throughput for large staged tarballs or concurrent downloads.
Code

pnpr/crates/pnpr/src/server/staged.rs[R483-513]

+    let body = match state.inner.storage.read_staged_body(stage_id).await {
+        Ok(Some(body)) => body,
+        Ok(None) => return not_found(),
+        Err(err) => return error_response(&err),
+    };
+    let mut incoming: Value = match serde_json::from_slice(&body) {
+        Ok(value) => value,
+        Err(err) => return error_response(&RegistryError::Json(err)),
+    };
+    let attachments = match extract_attachments(&mut incoming) {
+        Ok(attachments) => attachments,
+        Err(err) => return error_response(&err),
+    };
+    let Some(attachment) = attachments.into_iter().next() else {
+        return not_found();
+    };
+    let bytes = match BASE64.decode(attachment.data.as_bytes()) {
+        Ok(bytes) => bytes,
+        Err(err) => {
+            return error_response(&RegistryError::InvalidAttachment {
+                filename: attachment.filename,
+                reason: format!("invalid base64 data: {err}"),
+            });
+        }
+    };
+    Response::builder()
+        .status(StatusCode::OK)
+        .header(header::CONTENT_TYPE, "application/octet-stream")
+        .header(header::CONTENT_LENGTH, bytes.len())
+        .body(Body::from(bytes))
+        .expect("static-shape response always builds")
Evidence
The staged tarball handler decodes directly into memory (BASE64.decode), while the publish path
has an established streaming decode implementation that avoids loading decoded bytes at once.

pnpr/crates/pnpr/src/server/staged.rs[472-513]
pnpr/crates/pnpr/src/publish.rs[78-150]

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 staged tarball endpoint eagerly decodes base64 to a full `Vec<u8>` before sending the response.

### Issue Context
The regular publish pipeline already has a streaming base64 decode path (`stream_decode_verify_and_write`) that avoids holding decoded tarball bytes in memory.

### Fix Focus Areas
- Stream base64 decoding into the HTTP response body (or to a temp file and then stream the file) instead of allocating the entire decoded tarball.
- Use the attachment’s declared decoded `length` (when present) to set `Content-Length` without decoding first.

### Fix Focus Areas (code pointers)
- pnpr/crates/pnpr/src/server/staged.rs[472-514]
- pnpr/crates/pnpr/src/publish.rs[78-150]

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



Informational

10. Eager mock token lookup ✓ Resolved 🐞 Bug ☼ Reliability ⭐ New
Description
The stage TS tests now compute CONFIG_BY_URI by calling getRegistryMockToken() at module load time,
which throws if REGISTRY_MOCK_TOKEN is unset, causing the entire file to fail during import before
any test runs. This makes local/ad-hoc execution brittle and produces a less localized failure mode.
Code

pnpm11/releasing/commands/test/stage.test.ts[R15-19]

+const CONFIG_BY_URI = {
+  [`//localhost:${REGISTRY_MOCK_PORT}/`]: {
+    '@': { authToken: getRegistryMockToken() },
+  },
+}
Evidence
The test file calls getRegistryMockToken() while defining CONFIG_BY_URI. The helper explicitly
throws if REGISTRY_MOCK_TOKEN is absent, so the module can crash during evaluation rather than
failing a specific test with a controlled setup error.

pnpm11/releasing/commands/test/stage.test.ts[15-19]
pnpm11/testing/registry-mock/src/index.ts[24-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
`CONFIG_BY_URI` is initialized at module scope using `getRegistryMockToken()`. That helper throws when `process.env.REGISTRY_MOCK_TOKEN` is missing, so importing this test module can fail before Jest runs any tests.

### Issue Context
The with-registry preset usually sets `REGISTRY_MOCK_TOKEN`, but making the token lookup lazy improves debuggability and allows running subsets of the file in environments where the preset isn’t applied.

### Fix Focus Areas
- Replace `CONFIG_BY_URI` with a function (e.g. `getConfigByUri()`) that calls `getRegistryMockToken()` inside the specific tests that need it, or initialize it in a `beforeAll` so the failure is clearly associated with the test suite setup.

- pnpm11/releasing/commands/test/stage.test.ts[15-19]
- pnpm11/testing/registry-mock/src/index.ts[24-33]

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


Grey Divider

Qodo Logo

Comment thread pnpm/crates/cli/src/cli_args/stage.rs Resolved
Comment thread pnpr/crates/pnpr/src/server/staged.rs Resolved
@github-actions

github-actions Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
tarball/download_dependency    1.00      6.7±0.03ms   652.0 KB/sec    1.00      6.7±0.25ms   649.0 KB/sec

@qodo-code-review

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 593c7dd

Warning

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

CategorySuggestion                                                                                                                                    Impact
Possible issue
Tighten staged listing prefix

Add a trailing slash to the S3 listing prefix. This prevents inadvertently
matching and exposing objects from similarly named directories like
.staged-backup.

pnpr/crates/pnpr/src/s3.rs [299-313]

 pub async fn list_staged_ids(&self) -> Result<Vec<String>> {
-    let scope = ObjectPath::from(format!("{}{STAGED_DIR}", self.prefix));
+    let scope = ObjectPath::from(format!("{}{STAGED_DIR}/", self.prefix));
     let mut listing = self.store.list(Some(&scope));
     let mut ids = Vec::new();
     while let Some(meta) = listing.next().await {
         let meta = meta?;
         let Some(object) = meta.location.as_ref().rsplit('/').next() else {
             continue;
         };
         if let Some(id) = staged_id_of_meta_object(object) {
             ids.push(id.to_string());
         }
     }
     Ok(ids)
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies a potential bug with S3 prefix matching, but the proposed fix may be ineffective since object_store::path::Path typically strips trailing slashes, requiring manual stream filtering instead.

Low
Reject truncated paginated results

Throw a user-facing error when the pagination limit is reached to avoid silently
truncating results.

pnpm11/releasing/commands/src/stage/list.ts [12-32]

 const MAX_PAGES = 1000
 ...
     page++
-    if (page >= MAX_PAGES) break
+    if (page >= MAX_PAGES) {
+      throw new PnpmError('STAGE_LIST_TOO_MANY_PAGES', `The registry returned more than ${MAX_PAGES} pages of staged packages. Narrow the query with a package name filter.`)
+    }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 5

__

Why: Throwing an error prevents silently hiding results from the user, but it contradicts the PR's explicit design and tests which expect the command to return the truncated list.

Low
Serialize staged approvals

Acquire a lock on the stage ID before processing an approval to serialize
concurrent requests.

pnpr/crates/pnpr/src/server/staged.rs [424-436]

+let _stage_guard = state.inner.package_locks.lock(&format!("stage:{stage_id}")).await;
 let record = match load_authorized_record(state, identity, registry, stage_id).await {
     Ok(record) => record,
     Err(response) => return *response,
 };
 let body = match state.inner.storage.read_staged_body(stage_id).await {
     Ok(Some(body)) => body,
     Ok(None) => {
         return error_response(&RegistryError::Io(std::io::Error::other(format!(
             "staged publish {stage_id} has no stored body",
         ))));
     }
     Err(err) => return error_response(&err),
 };
  • Apply / Chat
Suggestion importance[1-10]: 4

__

Why: While locking earlier could prevent redundant validation during a race condition, the existing commit_publishes logic already handles duplicate publishes safely via 409 conflicts.

Low
General
Validate pagination at parsing

Validate and clamp the perPage query parameter during parsing rather than when
processing the list request.

pnpr/crates/pnpr/src/server/staged.rs [99-103]

 "perPage" => {
-    if let Ok(per_page) = decoded.parse() {
-        parsed.per_page = per_page;
+    if let Ok(per_page) = decoded.parse::<usize>()
+        && per_page > 0
+    {
+        parsed.per_page = per_page.min(MAX_PER_PAGE);
     }
 }
  • Apply / Chat
Suggestion importance[1-10]: 3

__

Why: The per_page value is already safely clamped to a valid range before use, making this suggestion a minor stylistic preference with no functional impact.

Low
  • More

Previous suggestions

Suggestions up to commit 0a5319b
CategorySuggestion                                                                                                                                    Impact
Security
Validate path-derived identifiers

Add validation to ensure stage_id conforms to a valid UUID format before it is
processed. This prevents potential path traversal attacks by rejecting malformed
or malicious IDs.

pnpr/crates/pnpr/src/server/staged.rs [523-533]

 async fn load_authorized_record(
     state: &AppState,
     identity: &Identity,
     registry: Option<&str>,
     stage_id: &str,
 ) -> Result<StagedRecord, Box<Response>> {
+    if !is_stage_id(stage_id) {
+        return Err(Box::new(not_found()));
+    }
+
     let record = match read_staged_record(state, stage_id).await {
         Ok(Some(record)) => record,
         Ok(None) => return Err(Box::new(not_found())),
         Err(err) => return Err(Box::new(error_response(&err))),
     };
 
+fn is_stage_id(value: &str) -> bool {
+    value.len() == 36
+        && value.char_indices().all(|(index, ch)| match index {
+            8 | 13 | 18 | 23 => ch == '-',
+            _ => ch.is_ascii_hexdigit(),
+        })
+}
+
Suggestion importance[1-10]: 10

__

Why: Adding strict validation for stage_id effectively prevents path traversal vulnerabilities, which is critical since this parameter originates from the URL and is directly used in storage operations.

High
Suggestions up to commit 8cd7ccc
CategorySuggestion                                                                                                                                    Impact
Possible issue
Serialize approval validation

Move the package lock acquisition to happen before the re-validation of the
publish document.

pnpr/crates/pnpr/src/server/staged.rs [445-457]

+let _packument_guard = state.inner.package_locks.lock(name.as_str()).await;
+
 // Re-validate against the registry state of *now*: rules may have
 // changed since staging, and the version may have been published in
 // the meantime (which surfaces as the usual 409).
 let (validated, target) =
     match validate_publish_doc(state, identity, record.registry.as_deref(), name, incoming)
         .await
     {
         Ok(validated) => validated,
         Err(response) => return *response,
     };
 
-let _packument_guard = state.inner.package_locks.lock(validated.name.as_str()).await;
 let staged = match stage_publish(state, validated, &now_iso(), Some(&target.org)).await {
Suggestion importance[1-10]: 9

__

Why: Acquiring the package_locks guard before validate_publish_doc fixes a race condition (TOCTOU) where concurrent requests could bypass duplicate publish checks.

High
Security
Validate server-side identifiers

Add server-side UUID validation for stage_id inside load_authorized_record.

pnpr/crates/pnpr/src/server/staged.rs [523-533]

 async fn load_authorized_record(
     state: &AppState,
     identity: &Identity,
     registry: Option<&str>,
     stage_id: &str,
 ) -> Result<StagedRecord, Box<Response>> {
+    if !is_stage_id(stage_id) {
+        return Err(Box::new(not_found()));
+    }
+
     let record = match read_staged_record(state, stage_id).await {
         Ok(Some(record)) => record,
         Ok(None) => return Err(Box::new(not_found())),
         Err(err) => return Err(Box::new(error_response(&err))),
     };
+}
 
+fn is_stage_id(value: &str) -> bool {
+    value.len() == 36
+        && value.char_indices().all(|(index, char)| match index {
+            8 | 13 | 18 | 23 => char == '-',
+            _ => char.is_ascii_hexdigit(),
+        })
+}
+
Suggestion importance[1-10]: 8

__

Why: Validating identifiers on the server side adds a crucial layer of defense against potential path traversal or injection attacks on the storage backend.

Medium
Suggestions up to commit bbc9366
CategorySuggestion                                                                                                                                    Impact
High-level
GET /-/stage is vulnerable to DoS

The suggestion warns that serve_staged_list sequentially reads and authorizes
every staged record before paginating, making it vulnerable to DoS. It
recommends using a secondary index or concurrent fetching to resolve this
bottleneck.

Examples:

pnpr/crates/pnpr/src/server/staged.rs [345-364]
    let mut records: Vec<StagedRecord> = Vec::new();
    for stage_id in ids {
        let Ok(Some(record)) = read_staged_record(state, &stage_id).await else {
            continue;
        };
        if record.registry.as_deref() != registry {
            continue;
        }
        if let Some(package) = &query.package
            && &record.package_name != package

 ... (clipped 10 lines)

Solution Walkthrough:

Before:

let mut records: Vec<StagedRecord> = Vec::new();
for stage_id in ids {
    let Ok(Some(record)) = read_staged_record(state, &stage_id).await else {
        continue;
    };
    // ... filtering logic ...
    if authorize_staged(state, identity, &record).await.is_err() {
        continue;
    }
    records.push(record);
}

After:

use futures::StreamExt;

let records: Vec<StagedRecord> = futures::stream::iter(ids)
    .map(|stage_id| async move {
        let Ok(Some(record)) = read_staged_record(state, &stage_id).await else {
            return None;
        };
        // ... filtering logic ...
        if authorize_staged(state, identity, &record).await.is_ok() {
            Some(record)
        } else {
            None
        }
    })
    .buffer_unordered(50) // Configure appropriate concurrency limit
    .filter_map(|res| async { res })
    .collect()
    .await;
Suggestion importance[1-10]: 9

__

Why: The suggestion identifies a critical Denial of Service (DoS) vulnerability where unbounded sequential network operations in serve_staged_list could cause the endpoint to hang, correctly proposing concurrency or indexing as solutions.

High
Possible issue
Fix sorting to be newest-first

Reverse the sorting condition for created_at to accurately implement
newest-first sorting.

pnpr/crates/pnpr/src/server/staged.rs [365-367]

 records.sort_by(|left, right| {
-    left.created_at.cmp(&right.created_at).then_with(|| left.id.cmp(&right.id))
+    right.created_at.cmp(&left.created_at).then_with(|| left.id.cmp(&right.id))
 });
Suggestion importance[1-10]: 8

__

Why: The current code sorts records oldest-first, contradicting the doc comment that specifies newest-first order; swapping the left and right parameters correctly implements descending order.

Medium

@codecov-commenter

codecov-commenter commented Jul 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.51020% with 202 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.43%. Comparing base (2b02764) to head (599672b).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
pnpr/crates/pnpr/src/server/staged.rs 73.33% 104 Missing ⚠️
pnpm/crates/cli/src/cli_args/stage.rs 90.69% 43 Missing ⚠️
pnpr/crates/pnpr/src/s3.rs 0.00% 32 Missing ⚠️
...crates/cli/src/cli_args/stage/summarize_tarball.rs 90.29% 10 Missing ⚠️
pnpr/crates/pnpr/src/storage.rs 88.50% 10 Missing ⚠️
pnpm/crates/cli/src/cli_args/dispatch_query.rs 92.85% 2 Missing ⚠️
pnpm/crates/cli/src/cli_args/publish.rs 97.72% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #12922      +/-   ##
==========================================
- Coverage   85.51%   85.43%   -0.08%     
==========================================
  Files         469      474       +5     
  Lines       72988    74546    +1558     
==========================================
+ Hits        62417    63691    +1274     
- Misses      10571    10855     +284     

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

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

@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: 5

🧹 Nitpick comments (1)
pnpm/crates/cli/src/cli_args/dispatch_query.rs (1)

238-241: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the implementation-narrating doc comment.

This explains local control flow rather than a public contract or non-obvious constraint. As per coding guidelines, “Avoid comments that restate code … or narrate the function body.”

🤖 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/cli/src/cli_args/dispatch_query.rs` around lines 238 - 241,
Remove the implementation-narrating doc comment immediately above the stage
dispatch logic, leaving the code unchanged.

Source: Coding guidelines

🤖 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/cli/src/cli_args/dispatch_query.rs`:
- Around line 242-245: Propagate the global recursive report-summary setting in
`stage()` by reading `ctx.recursive_report_summary` and merging it into the
`StageArgs` or publish dispatch path before invoking
`StageArgs::stage_publish()` and `run_recursive()`, matching the behavior in
`publish()` while keeping pacquet and pnpm implementations identical.

In `@pnpm/crates/cli/src/cli_args/stage.rs`:
- Around line 310-349: stage_download currently loads the entire registry
tarball via response.bytes() without limiting attacker-controlled input. Replace
this with the existing read_limited_body helper, using an explicit appropriate
tarball-size cap, and preserve request-failure error mapping before passing the
bounded bytes to summarize_tarball.
- Around line 217-251: Bound pagination in stage_list so repeated full pages or
an inflated response.total cannot cause unbounded requests and memory growth.
Add a hard maximum page count or equivalent fail-safe while preserving the
existing completion checks based on total and page length, and handle the cap
consistently with the command’s error/result behavior.

In `@pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs`:
- Around line 126-133: Prevent gzip-bomb memory exhaustion in maybe_gunzip by
enforcing a maximum decompressed size while reading from GzDecoder. Use a
bounded reader or otherwise stop decompression once the configured limit is
exceeded, and preserve the existing fallback behavior for invalid or oversized
gzip data by returning the original input bytes.

In `@pnpr/crates/pnpr/src/storage.rs`:
- Around line 525-532: Update remove_staged to treat body deletion as
best-effort after metadata removal: preserve and return the removed result,
catch non-NotFound errors from the staged body removal, and log them instead of
propagating them. Keep expected NotFound handling consistent with existing
cleanup behavior, using remove_staged and the surrounding storage logging
conventions.

---

Nitpick comments:
In `@pnpm/crates/cli/src/cli_args/dispatch_query.rs`:
- Around line 238-241: Remove the implementation-narrating doc comment
immediately above the stage dispatch logic, leaving the code unchanged.
🪄 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: 6f47ee7e-5305-4b51-89e1-e6f57737b568

📥 Commits

Reviewing files that changed from the base of the PR and between 84e3d3b and bbc9366.

📒 Files selected for processing (29)
  • pnpm/crates/cli/Cargo.toml
  • pnpm/crates/cli/src/cli_args.rs
  • pnpm/crates/cli/src/cli_args/cli_command.rs
  • pnpm/crates/cli/src/cli_args/dispatch.rs
  • pnpm/crates/cli/src/cli_args/dispatch_query.rs
  • pnpm/crates/cli/src/cli_args/dist_tag.rs
  • pnpm/crates/cli/src/cli_args/publish.rs
  • pnpm/crates/cli/src/cli_args/publish/recursive.rs
  • pnpm/crates/cli/src/cli_args/publish/tests.rs
  • pnpm/crates/cli/src/cli_args/stage.rs
  • pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs
  • pnpm/crates/cli/src/cli_args/stage/tests.rs
  • pnpm/crates/cli/src/cli_args/switch_cli_version.rs
  • pnpm/crates/cli/src/state.rs
  • pnpm/crates/cli/tests/stage.rs
  • pnpm/crates/cli/tests/workspace_install.rs
  • pnpm/crates/network/src/lib.rs
  • pnpm/crates/network/src/limited_body.rs
  • pnpm/crates/pack/src/lib.rs
  • pnpm/crates/package-manifest/src/lib.rs
  • pnpm/crates/publish/src/publish_packed_pkg.rs
  • pnpm/crates/publish/src/publish_packed_pkg/tests.rs
  • pnpr/crates/pnpr/src/s3.rs
  • pnpr/crates/pnpr/src/search.rs
  • pnpr/crates/pnpr/src/server.rs
  • pnpr/crates/pnpr/src/server/staged.rs
  • pnpr/crates/pnpr/src/server/staged/tests.rs
  • pnpr/crates/pnpr/src/storage.rs
  • pnpr/crates/pnpr/tests/staged_publish.rs

Comment thread pnpm/crates/cli/src/cli_args/stage.rs Resolved
Comment thread pnpm/crates/cli/src/cli_args/stage.rs Resolved
Comment thread pnpr/crates/pnpr/src/storage.rs Resolved
zkochan and others added 2 commits July 10, 2026 23:43
- Cap the staged tarball download and its decompression at 512 MiB each;
  the response bytes are attacker-controlled input and previously went
  through response.bytes() and an unbounded gunzip.
- Bound the stage list pagination loop at 1000 pages in both stacks, so
  a registry that keeps answering full pages with an inflated total
  cannot drive it forever (with a changeset for the TypeScript side).
- Thread the global --report-summary flag into stage publish and accept
  it on the stage command, matching publish.
- Make the staged-body removal in pnpr best-effort once the metadata is
  gone, so a body-removal failure cannot orphan an undiscoverable object
  while misreporting the record as still present.
- Fix the staged-list doc comment: records are sorted oldest-first.

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@coderabbitai coderabbitai Bot 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

🤖 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/releasing/commands/src/stage/list.ts`:
- Around line 10-12: Add a regression test for the pagination logic in the list
command that mocks registry responses with full pages and an inflated total,
then verifies pagination stops at the MAX_PAGES cap rather than continuing
indefinitely. Assert the resulting request count or termination behavior and
keep the test focused on the MAX_PAGES fail-safe.
🪄 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: 644583c3-e942-4e92-887c-a42f6355f7fd

📥 Commits

Reviewing files that changed from the base of the PR and between bbc9366 and 8cd7ccc.

📒 Files selected for processing (8)
  • .changeset/stage-list-page-cap.md
  • pnpm/crates/cli/src/cli_args/cli_command.rs
  • pnpm/crates/cli/src/cli_args/dispatch_query.rs
  • pnpm/crates/cli/src/cli_args/stage.rs
  • pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs
  • pnpm11/releasing/commands/src/stage/list.ts
  • pnpr/crates/pnpr/src/server/staged.rs
  • pnpr/crates/pnpr/src/storage.rs
✅ Files skipped from review due to trivial changes (1)
  • .changeset/stage-list-page-cap.md
🚧 Files skipped from review as they are similar to previous changes (5)
  • pnpm/crates/cli/src/cli_args/cli_command.rs
  • pnpm/crates/cli/src/cli_args/dispatch_query.rs
  • pnpm/crates/cli/src/cli_args/stage/summarize_tarball.rs
  • pnpr/crates/pnpr/src/server/staged.rs
  • pnpm/crates/cli/src/cli_args/stage.rs

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 8cd7ccc

Copilot AI review requested due to automatic review settings July 10, 2026 22:01

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@zkochan

zkochan commented Jul 10, 2026

Copy link
Copy Markdown
Member Author

Re the two latest qodo suggestions (up to 8cd7ccc):

Serialize approval validation — declined. validate_publish_doc reads only static configuration (write-target routing, the registry's publish rule, attachment shape); it never reads mutable registry state, so there is nothing for a concurrent writer to invalidate. The duplicate-version check that the suggestion is worried about (VersionAlreadyPublished) lives inside stage_publish, which already runs under the package lock — the approve handler takes the lock at exactly the same point as the direct publish path (publish_package), and moving it earlier would only hold the lock across work that doesn't need serializing.

Validate server-side identifiers — already in place, one layer down: the storage layer rejects any stage id that isn't hex-and-hyphens before it can reach a filesystem path or object key (validated_stage_id in pnpr/crates/pnpr/src/storage.rs), so every handler is covered without each one repeating the check. The integration test a_bogus_stage_id_is_not_found_or_rejected covers a traversal-shaped id end-to-end.

The earlier high-level note about serve_staged_list reading records sequentially is fair as a scaling observation, but the set it iterates is bounded by records that authorized publishers created (approve/reject both delete them), not by the caller — so it isn't attacker-inflatable. Happy to add concurrent reads if staged volume ever warrants it.


Written by an agent (Claude Code, claude-fable-5).

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants