Skip to content

feat(pacquet-cli): port the self-update command - #12693

Merged
zkochan merged 2 commits into
mainfrom
feat/pacquet-self-update
Jun 27, 2026
Merged

zkochan merged 2 commits into
mainfrom
feat/pacquet-self-update

Conversation

@zkochan

@zkochan zkochan commented Jun 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Ports pnpm's self-update command to the Rust pacquet CLI, matching the TypeScript implementation in pnpm11/engine/pm/commands/src/self-updater. The pnpm side already has this command, so this is the pacquet side catching up — no TypeScript change is needed.

pacquet self-update [VERSION]:

  • Resolves the target version from the trusted package-manager bootstrap registry (never the repo-controlled project registries), honoring minimumReleaseAge / trustPolicy; strict resolution fails closed on a policy violation (mirrors makeResolutionStrict).
  • Guards against running under corepack, refuses to downgrade on an implicit latest (explicit self-update latest forces it), prints the already-up-to-date / downgrade no-op messages, and emits the major-upgrade migration hint.
  • Project-pin branch: when the project pins pnpm via packageManager / devEngines.packageManager, updates the pin in place — preserving the range-operator style and persisting integrities — instead of touching the global install.
  • Global switch: resolves integrities into the env lockfile, verifies the engine's npm registry signature against npm's embedded public keys, installs the engine into the global packages dir (scripts disabled), hard-links the host's native @pnpm/exe.<target> binary into the wrapper, and links the bins into the global bin dir with a cache-keyed hash symlink.

New modules under crates/cli/src/cli_args/self_update:

  • install_pnpm — ports installPnpm + linkExePlatformBinary (legacy <os>-<arch> and exe.<platform>-<arch>[-musl] schemes; Windows alias hardlinks + bin-field rewrite).
  • verify_engine — ports verifyPnpmEngineIdentity (embedded npm keys, ECDSA-P256 over name@version:integrity, fail-closed on tamper / unreachable registry).

config_deps gains resolve_pnpm_version, the policy-aware version probe reusing the existing bootstrap-registry resolver.

Error codes mirror pnpm's PnpmError codes (ERR_PNPM_CANT_SELF_UPDATE_IN_COREPACK, ERR_PNPM_CANNOT_RESOLVE_PNPM, ERR_PNPM_PNPM_ENGINE_IDENTITY_UNVERIFIABLE / _MISMATCH, ERR_PNPM_NO_GLOBAL_BIN_DIR).

Squash Commit Body

feat(pacquet-cli): port the self-update command

Ports pnpm's self-update command to the Rust pacquet CLI. Resolves the
target version from the trusted package-manager bootstrap registry
(honoring minimumReleaseAge / trustPolicy, strict resolution failing
closed), guards against corepack, refuses to downgrade on an implicit
`latest`, and emits the major-upgrade migration hint.

When the project pins pnpm via packageManager / devEngines.packageManager,
the pin is updated in place (range-style preserved, integrities persisted).
Otherwise the engine is installed into the global packages directory:
integrities are resolved into the env lockfile, the engine's npm registry
signature is verified against npm's embedded public keys, the host's native
platform binary is hard-linked into the wrapper (the preinstall is skipped
because the engine installs with scripts disabled), and the bins are linked
into the global bin directory with a cache-keyed hash symlink.

New modules: self_update/install_pnpm (installPnpm + linkExePlatformBinary)
and self_update/verify_engine (verifyPnpmEngineIdentity). config_deps gains
resolve_pnpm_version, the policy-aware version probe.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pacquet/ port, or the description notes what still needs porting.
    (TypeScript side already exists; this is the pacquet port.)
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. (Not applicable — Rust-only change; changesets version the
    TypeScript workspace.)
  • Added or updated tests. (Unit tests for platform dir-name parity,
    version-constraint preservation, and semver comparison. An end-to-end
    install+verify integration test still needs the mock registry to serve
    pnpm / @pnpm/exe.<target> with valid signatures — flagged as a
    follow-up.)
  • Updated the documentation if needed. (No doc change — the pnpm.io
    self-update docs already cover the command.)

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

Summary by CodeRabbit

  • New Features
    • Added a pnpm self-update CLI command to upgrade a project-pinned pnpm (updating the pin when present) or install/link a verified global pnpm when not pinned, including major-upgrade migration hints.
    • Enforces strict trusted-registry upgrade rules and blocks execution under corepack.
  • Bug Fixes
    • Strengthened lockfile-driven pnpm engine identity verification with signature/integrity checks that fail closed when unverifiable.
    • Improved cross-platform linking of the correct pnpm engine binary into the wrapper.
  • Tests
    • Expanded coverage for self-update version/policy handling, semver behavior, binary linking, and signature verification.

@coderabbitai

coderabbitai Bot commented Jun 27, 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 a self-update subcommand that resolves pnpm versions, updates pinned projects when applicable, or installs and links a global pnpm copy after verifying engine identity. Tests cover version handling, install/link behavior, and signature checks.

Changes

Self-update command

Layer / File(s) Summary
CLI wiring and version resolution
pacquet/crates/cli/src/cli_args.rs, pacquet/crates/cli/src/config_deps.rs
self_update is added to CLI parsing and dispatch, and resolve_pnpm_version resolves pnpm@<specifier> with policy metadata.
Self-update flow and pin rewrite
pacquet/crates/cli/src/cli_args/self_update.rs, pacquet/crates/cli/src/cli_args/self_update/tests.rs
Implements the top-level self-update flow, typed errors, corepack refusal, major-upgrade messaging, project pin rewriting, and semver/version helper tests.
Global install and wrapper linking
pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs, pacquet/crates/cli/src/cli_args/self_update/install_pnpm/tests.rs
Creates or reuses the global pnpm install area, runs an isolated install, resolves platform-specific executable names, links wrapper binaries, and rewrites Windows bin entries.
Engine verification
pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs, pacquet/crates/cli/src/cli_args/self_update/verify_engine/tests.rs
Collects lockfile-backed pnpm engine components, fetches packuments, verifies registry signatures, and classifies verification failures, with tests for signature and version parsing behavior.

Sequence Diagram(s)

sequenceDiagram
  participant CliArgsRun
  participant SelfUpdateRun
  participant ResolvePnpmVersion
  participant Handler
  participant VerifyEngine
  participant InstallPnpm
  participant GlobalBin

  CliArgsRun->>ResolvePnpmVersion: resolve pnpm target version
  CliArgsRun->>SelfUpdateRun: CliCommand::SelfUpdate
  SelfUpdateRun->>Handler: run with config and dir
  alt project pin exists
    Handler->>Handler: update_project_pin
  else global update
    Handler->>VerifyEngine: verify engine identity
    Handler->>InstallPnpm: install pnpm
    Handler->>GlobalBin: link binaries and hash-link
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related issues

  • Rust Roadmap #11633: Adds the missing self-update CLI surface that the roadmap explicitly lists under Engine & self-management, matching the new subcommand and orchestration work here.

Possibly related PRs

  • pnpm/pnpm#12471: The self-update version resolution path uses the trusted package-manager bootstrap plumbing added there.
  • pnpm/pnpm#12277: The self-update flow reads pnpm pin/version data from lockfiles, so lockfile representation changes here affect the new parsing logic.
  • pnpm/pnpm#12663: Both PRs implement ECDSA-P256-based npm registry signature verification.

Suggested labels

product: pacquet

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/pacquet-self-update

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

❤️ Share

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

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

Copy link
Copy Markdown

PR Summary by Qodo

feat(pacquet-cli): port pnpm-style self-update with policy checks and engine verification
✨ Enhancement 🧪 Tests 🕐 40+ Minutes

Grey Divider

Description

• Add pacquet self-update [VERSION] with project-pin update and global engine switching.
• Resolve target version via trusted bootstrap registry, honoring minimumReleaseAge/trustPolicy
 strictly.
• Verify engine identity using npm signing keys, link native binaries, and add parity unit tests.
Diagram

graph TD
  cli["CLI dispatcher"] --> su["self-update flow"] --> res["Resolve pnpm version"] --> reg{{"Bootstrap registry"}}
  su --> lock[("Env lockfile")]
  su --> ver["Verify engine identity"] --> reg
  su --> inst["Install + link engine"] --> global[("Global dirs + bin")]

  subgraph Legend
    direction LR
    _mod["Module"] ~~~ _store[("On-disk state")] ~~~ _ext{{"External"}}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Implement via existing `add -g pnpm@version` path only
  • ➕ Less bespoke code; reuses global install plumbing and bin linking
  • ➖ Doesn’t naturally enforce bootstrap-registry-only resolution for the version probe
  • ➖ Would still need wrapper/platform-binary linking logic (scripts are disabled)
  • ➖ Doesn’t cover project-pin update semantics without additional manifest logic
2. Skip npm registry signature verification (trust lockfile integrity only)
  • ➕ Simpler and avoids extra network fetch for packument signatures
  • ➕ Works in more offline-ish environments
  • ➖ Weakens security: a repo-controlled lockfile/registry could supply arbitrary native bytes
  • ➖ Diverges from pnpm’s intended fail-closed model for self-update
3. Delegate updates to corepack when available
  • ➕ Leverages Node’s supported updater path where applicable
  • ➖ Not applicable for non-corepack installs; still need native global engine switch for pacquet
  • ➖ Less parity with pnpm’s behavior outside corepack-managed environments

Recommendation: Keep the current approach: it matches pnpm’s semantics and preserves the key security property (bootstrap-registry-only resolution + embedded-key signature verification) before executing native bytes. As follow-ups, add an integration test with a mock registry serving valid signatures and consider factoring any shared global-install/linking helpers to reduce duplication with other global install flows.

Files changed (7) +1401 / -0

Enhancement (5) +1353 / -0
cli_args.rsWire 'self-update' into the CLI command enum and reporter dispatch +14/-0

Wire 'self-update' into the CLI command enum and reporter dispatch

• Adds the 'SelfUpdate' subcommand and exposes the 'self_update' module. Hooks command execution into the existing reporter-type routing so 'self-update' can emit logs consistently across default/ndjson/silent reporters.

pacquet/crates/cli/src/cli_args.rs

self_update.rsImplement 'pacquet self-update' flow (project pin update + global switch) +465/-0

Implement 'pacquet self-update' flow (project pin update + global switch)

• Introduces the main self-update handler: corepack guard, policy-aware version resolution, strict fail-closed behavior on release-policy violations, and major-upgrade migration hints. Implements the project-pin branch (update 'packageManager' / 'devEngines.packageManager' while preserving constraint style and optionally persisting integrities) and the global-switch branch (sync integrities into env lockfile, verify engine identity, install and link into global bin).

pacquet/crates/cli/src/cli_args/self_update.rs

install_pnpm.rsAdd self-update engine installer and platform-binary linking logic +276/-0

Add self-update engine installer and platform-binary linking logic

• Implements the global engine install used by self-update: installs 'pnpm@version' into a fresh global packages directory location with scripts disabled, then hard-links the host platform binary into the wrapper. Includes legacy and next platform package naming schemes, and Windows-specific alias hardlinks plus 'package.json' bin-field rewrite.

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs

verify_engine.rsVerify pnpm engine identity via npm embedded signing keys +514/-0

Verify pnpm engine identity via npm embedded signing keys

• Adds engine identity verification that builds 'name@version:integrity' messages from env lockfile metadata, fetches signed packuments from the trusted bootstrap registry, and validates ECDSA-P256 signatures against embedded npm public keys. Fails closed on missing integrity, missing signatures, absent packages, signature mismatch, or registry/network failures.

pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs

config_deps.rsAdd policy-aware 'resolve_pnpm_version' for self-update probing +84/-0

Add policy-aware 'resolve_pnpm_version' for self-update probing

• Introduces 'resolve_pnpm_version' that resolves 'pnpm@<specifier>' using the package-manager bootstrap resolver and applies minimumReleaseAge/trustPolicy gates. Returns both the resolved version and whether resolution required bypassing policy (so self-update can fail closed under strict resolution).

pacquet/crates/cli/src/config_deps.rs

Tests (2) +48 / -0
tests.rsUnit tests for legacy/next platform package dir naming parity +21/-0

Unit tests for legacy/next platform package dir naming parity

• Adds tests covering the '<os>-<arch>' legacy scheme and 'exe.<platform>-<arch>[-musl]' scheme, including Windows ia32→x86 normalization and Linux musl naming.

pacquet/crates/cli/src/cli_args/self_update/install_pnpm/tests.rs

tests.rsUnit tests for version constraint preservation and semver comparisons +27/-0

Unit tests for version constraint preservation and semver comparisons

• Tests that 'devEngines.packageManager' constraints preserve pinning style (caret/tilde/exact) and that semver comparisons behave correctly (including prereleases and invalid inputs).

pacquet/crates/cli/src/cli_args/self_update/tests.rs

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

qodo-free-for-open-source-projects Bot commented Jun 27, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Overrides taint self-update 🐞 Bug ⛨ Security
Description
install_pnpm::run_install clones the project-loaded Config and does not clear repo-controlled
manifest-rewrite settings (overrides / package_extensions), so a repository can influence which
dependency graph gets installed during a self-update. This weakens the trust boundary of “verified
self-update” because the installed engine’s closure may diverge from the intended published
dependency graph even though the top-level engine components are signature-checked.
Code

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[R98-123]

+    let mut cfg = base_config.clone();
+    // Resolve and fetch the engine bytes through the trusted
+    // package-manager bootstrap registry/network/auth, never the
+    // repository-controlled project settings — otherwise a malicious
+    // project `.npmrc` could redirect the downloaded pnpm bytes to an
+    // attacker registry. This mirrors how `config_deps` resolves the
+    // package manager and how the engine signature is verified.
+    apply_package_manager_bootstrap(&mut cfg, &base_config.package_manager_bootstrap);
+    cfg.modules_dir = install_dir.join("node_modules");
+    cfg.virtual_store_dir = install_dir.join("node_modules").join(".pnpm");
+    // The engine install is self-contained, so its virtual store lives
+    // inside its own install dir, never the shared global one.
+    cfg.enable_global_virtual_store = false;
+    cfg.lockfile = true;
+    cfg.workspace_dir = None;
+    cfg.supported_architectures = supported_architectures;
+    // pnpm installs the engine with `ignoreScripts: true` — the wrapper's
+    // preinstall (which links the platform binary) is replicated by
+    // `link_exe_platform_binary`, so running it here is both unnecessary
+    // and a code-execution surface during a privileged self-update.
+    cfg.ignore_scripts = true;
+    cfg.dangerously_allow_all_builds = false;
+    cfg.allow_builds.clear();
+    cfg.strict_dep_builds = false;
+
+    let config: &'static Config = Config::leak(cfg);
Evidence
run_install clones the project config and only applies bootstrap network/registry settings,
leaving other repo-derived config intact. Config::overrides and Config::package_extensions are
explicitly sourced from pnpm-workspace.yaml, and the install pipeline applies them as read-package
hooks that rewrite manifests during resolution/installation.

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[98-137]
pacquet/crates/config/src/lib.rs[1296-1322]
pacquet/crates/package-manager/src/install_with_fresh_lockfile.rs[844-922]

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 self-update` should not allow repo-controlled resolution rewrite features (e.g. `pnpm-workspace.yaml` `overrides` / `packageExtensions`) to affect the engine install. Today `run_install` clones the fully-loaded project `Config` and only swaps the bootstrap registry/proxy/tls/auth, leaving those rewrite knobs enabled.
### Issue Context
Even with `ignore_scripts=true`, these settings can still change what dependency set is laid out in the installed engine directory, weakening the security guarantee that self-update installs the intended, verified engine content.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[98-123]

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


2. Wrong lockfile directory 🐞 Bug ≡ Correctness
Description
read_project_pinned_pnpm_version reads pnpm-lock.yaml from the command’s current dir, not the
workspace root/lockfile dir, so workspace executions from a package subdirectory can miss the actual
pinned pnpm version. This can skip the implicit-latest downgrade refusal and suppress the
major-upgrade migration hint in the project-pin flow.
Code

pacquet/crates/cli/src/cli_args/self_update.rs[R391-405]

+fn read_project_pinned_pnpm_version(dir: &Path, spec: Option<&str>) -> Option<String> {
+    let lockfile_pinned = EnvLockfile::read(dir).ok().flatten().and_then(|env| {
+        env.importers
+            .get(EnvLockfile::ROOT_IMPORTER_KEY)
+            .and_then(|importer| importer.package_manager_dependencies.as_ref())
+            .and_then(|deps| deps.get("pnpm"))
+            .map(|dep| dep.version.clone())
+    });
+    let spec_min = spec.and_then(super::package_manager::exact_version);
+    match (lockfile_pinned, spec_min) {
+        (Some(lockfile), Some(spec)) => {
+            Some(if version_lt(&spec, &lockfile) { lockfile } else { spec })
+        }
+        (lockfile, spec) => lockfile.or(spec),
+    }
Evidence
The helper reads /pnpm-lock.yaml via EnvLockfile::read(dir), but env lockfile reads are rooted
at the passed directory. Elsewhere in the same command, lockfile operations intentionally target
config.workspace_dir when present, showing the mismatch.

pacquet/crates/cli/src/cli_args/self_update.rs[319-327]
pacquet/crates/cli/src/cli_args/self_update.rs[391-405]
pacquet/crates/lockfile/src/env_lockfile.rs[109-131]

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

## Issue description
In workspaces, the env lockfile (`pnpm-lock.yaml` first document) typically lives at the workspace root. `read_project_pinned_pnpm_version` currently reads it from the command working directory, which can be a subproject directory, causing the pinned-version logic to silently degrade.
### Issue Context
The same command already uses `config.workspace_dir` when choosing where to sync `packageManagerDependencies`, indicating the workspace root is the intended lockfile directory.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update.rs[319-327]
- pacquet/crates/cli/src/cli_args/self_update.rs[391-405]

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


3. Policy check wrong package 🐞 Bug ⛨ Security
Description
resolve_pnpm_version returns only the resolved version suffix without validating the resolved
package name, so self-update can apply minimumReleaseAge/trustPolicy decisions to a different
package than pnpm when given npm: alias specifiers. This can bypass strict policy gating and
allow switching to a pnpm version that should have been blocked by policy.
Code

pacquet/crates/cli/src/config_deps.rs[R137-166]

+    let wanted = WantedDependency {
+        alias: Some("pnpm".to_string()),
+        bare_specifier: Some(bare_specifier.to_string()),
+        ..WantedDependency::default()
+    };
+    let opts = ResolveOptions {
+        default_tag: Some("latest".to_string()),
+        published_by,
+        published_by_exclude,
+        trust_policy,
+        trust_policy_exclude,
+        trust_policy_ignore_after: config.trust_policy_ignore_after,
+        ..ResolveOptions::default()
+    };
+    let result = context
+        .resolver
+        .resolve(&wanted, &opts)
+        .await
+        .map_err(|error| miette::miette!("{error}"))
+        .wrap_err_with(|| format!("resolve pnpm@{bare_specifier}"))?;
+    let Some(result) = result else {
+        return Ok(None);
+    };
+    let Some(name_ver) = result.name_ver else {
+        return Ok(None);
+    };
+    Ok(Some(ResolvedPnpm {
+        version: name_ver.suffix.to_string(),
+        policy_violation: result.policy_violation.is_some(),
+    }))
Evidence
resolve_pnpm_version constructs a wanted dep with alias "pnpm" but returns name_ver.suffix
without checking name_ver.name. The npm bare-specifier parser explicitly supports npm: inputs
that can change the resolved package name to something other than the alias, which would detach
policy_violation from pnpm itself.

pacquet/crates/cli/src/config_deps.rs[91-166]
pacquet/crates/resolving-npm-resolver/src/parse_bare_specifier.rs[37-69]

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_deps::resolve_pnpm_version` resolves `pnpm@<specifier>` but then discards the resolved package identity and returns only the version. Because the npm resolver supports `npm:` alias forms that can change the underlying package name, the returned `(version, policy_violation)` can reflect a different package than `pnpm`, letting `self-update` make a trust decision based on the wrong metadata.
### Issue Context
- `parse_bare_specifier` supports `npm:` specifiers that can override the resolved package name.
- `resolve_pnpm_version` sets `alias: "pnpm"` but does not verify `result.name_ver.name == "pnpm"` before returning.
### Fix Focus Areas
- pacquet/crates/cli/src/config_deps.rs[91-166]
### Suggested change
After `let Some(name_ver) = result.name_ver ...`, ensure `name_ver.name.to_string() == "pnpm"` (or compare to `PkgName::parse("pnpm")`). If it does not match, return `Ok(None)` (or a dedicated error) so `self-update` fails closed with `CannotResolvePnpm` rather than using a mismatched version/policy_violation.
Optionally also reject `bare_specifier` forms that are not version/range/dist-tag up front (e.g. `npm:`).

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


View more (3)
4. Scoped auth lookup skipped 🐞 Bug ☼ Reliability
Description
verify_engine::fetch_packument computes the Authorization header via
AuthHeaders::for_url(registry_url), which ignores scope-specific credentials and can break
self-update against bootstrap registries that require @pnpm/* scoped auth. This can cause false
"unreachable" verification failures (e.g. 401/404) even when valid bootstrap credentials are
configured.
Code

pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs[R420-430]

+    let registry_url = with_trailing_slash(&component.registry);
+    let packument_url = format!("{registry_url}{}", encode_package_name(&component.name));
+    let display_url = redact_url_credentials(&packument_url);
+    let authorization = config.package_manager_bootstrap.auth_headers.for_url(&registry_url);
+
+    let (_guard, response) = send_with_retry(client, &packument_url, retry_opts, |client| {
+        let mut request = client.get(&packument_url).header("accept", "application/json");
+        if let Some(value) = &authorization {
+            request = request.header("authorization", value);
+        }
+        request
Evidence
The self-update verification request builds its auth header without package context, but the auth
system only applies scope credentials when for_url_with_package(..., Some(pkg)) is used; the main
registry fetcher uses the scope-aware lookup.

pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs[420-430]
pacquet/crates/network/src/auth.rs[193-237]
pacquet/crates/registry/src/package.rs[122-128]

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

## Issue description
`fetch_packument` uses `auth_headers.for_url(&registry_url)`, which is equivalent to `for_url_with_package(..., None)` and therefore **does not consider** scope-scoped credentials (e.g. tokens configured for `@pnpm:*`). Since `pick_registry()` routes scoped components to registries, this can make `self-update` fail verification with 401/404 even when bootstrap auth is correctly configured.
### Issue Context
- `AuthHeaders::for_url` intentionally skips scope-specific credential lookup.
- The normal registry fetch path uses `for_url_with_package(url, Some(name))` to apply scope tokens.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs[420-430]
### Expected fix
- Compute the authorization header with the package name context, and against the actual request URL:
- Prefer `config.package_manager_bootstrap.auth_headers.for_url_with_package(&packument_url, Some(&component.name))`
- (At minimum, pass `Some(&component.name)` so `@scope:registry` credentials can apply.)
- Keep redaction behavior unchanged.

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


5. Repo registry controls self-update 🐞 Bug ⛨ Security
Description
install_pnpm::run_install clones the normal Config and then uses State::init/add_package, so
the self-update install fetches pnpm using repo-controlled registry/proxy/auth settings instead of
package_manager_bootstrap. A malicious project .npmrc can redirect the downloaded pnpm@ bytes
to an attacker registry even though signature verification is performed against the trusted
bootstrap registry.
Code

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[R99-131]

+    let mut cfg = base_config.clone();
+    cfg.modules_dir = install_dir.join("node_modules");
+    cfg.virtual_store_dir = install_dir.join("node_modules").join(".pnpm");
+    // The engine install is self-contained, so its virtual store lives
+    // inside its own install dir, never the shared global one.
+    cfg.enable_global_virtual_store = false;
+    cfg.lockfile = true;
+    cfg.workspace_dir = None;
+    cfg.supported_architectures = supported_architectures;
+    // pnpm installs the engine with `ignoreScripts: true` — the wrapper's
+    // preinstall (which links the platform binary) is replicated by
+    // `link_exe_platform_binary`, so running it here is both unnecessary
+    // and a code-execution surface during a privileged self-update.
+    cfg.ignore_scripts = true;
+    cfg.dangerously_allow_all_builds = false;
+    cfg.allow_builds.clear();
+    cfg.strict_dep_builds = false;
+
+    let config: &'static Config = Config::leak(cfg);
+    let manifest_path = install_dir.join("package.json");
+    let state = State::init(manifest_path, config, false)
+        .wrap_err("initialize the self-update install state")?;
+    add_package::<Reporter, _, _>(
+        state,
+        &format!("{PNPM_PACKAGE_NAME}@{version}"),
+        PinnedVersion::Patch,
+        None,
+        false,
+        config.supported_architectures.clone(),
+        || std::iter::once(DependencyGroup::Prod),
+    )
+    .await
+}
Evidence
The self-update install path uses base_config.clone() and then initializes install state
(State::init) and runs add_package, both of which use the passed config for HTTP client/network
and resolution. The config layer explicitly documents package_manager_bootstrap as the mechanism
to prevent project .npmrc from redirecting package-manager bytes, and tests demonstrate
config.registry is project-controlled while package_manager_bootstrap.registry is not.

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[93-131]
pacquet/crates/cli/src/state.rs[59-92]
pacquet/crates/cli/src/cli_args/add.rs[241-266]
pacquet/crates/config/src/lib.rs[1564-1568]
pacquet/crates/config/src/tests.rs[1996-2015]

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 self-update` is intended to *always* resolve and install pnpm from the trusted `package_manager_bootstrap` registry/network/auth configuration, but `install_pnpm::run_install` currently clones the normal (repo-influenced) `Config` and uses it to initialize the installer state. This lets a project-controlled `.npmrc`/workspace config steer the actual bytes fetched during self-update.
## Issue Context
- Signature verification in `verify_engine` uses `config.package_manager_bootstrap`, but installation uses `base_config` as-is.
- `State::init` builds its HTTP client from the passed `Config`’s proxy/TLS settings.
- `Add` uses the passed `Config` to resolve/fetch packages.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[93-131]
### Implementation notes
- In `run_install`, before leaking `cfg`, override **all** trust-relevant network/registry/auth fields from `base_config.package_manager_bootstrap`:
- `cfg.registry`, `cfg.registries`
- `cfg.proxy`, `cfg.tls`, `cfg.tls_by_uri`
- `cfg.auth_headers` (use `package_manager_bootstrap.auth_headers`, not the project’s)
- Ensure this matches the same bootstrap routing used by `config_deps::EnvInstallerContext::for_package_manager`.
- Consider factoring a small helper (e.g. `apply_package_manager_bootstrap(&mut Config, &PackageManagerBootstrap)`) to reduce future drift.

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


6. Silent binary-link failure 🐞 Bug ☼ Reliability
Description
link_exe_platform_binary returns early on missing binaries, canonicalization failure, or hard-link
failure, and those errors are not propagated, so self-update can report success while leaving the
installed wrapper without a working native pnpm executable. This is especially risky because
scripts are disabled during install specifically to avoid code execution, making this manual linking
step the critical path.
Code

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[R174-214]

+fn link_exe_platform_binary(install_dir: &Path, wrapper_pkg_name: &str) {
+    let mut wrapper_dir = install_dir.join("node_modules");
+    for segment in wrapper_pkg_name.split('/') {
+        wrapper_dir.push(segment);
+    }
+    if !wrapper_dir.exists() {
+        return;
+    }
+    let platform = host_platform();
+    let arch = host_arch();
+    let libc = host_libc();
+    let executable = if platform == "win32" { "pnpm.exe" } else { "pnpm" };
+
+    // Resolve the platform binary by its explicit adjacent path in the
+    // real virtual store, not via a `node_modules` walk (which a
+    // repo-controlled store-dir could shadow). `@pnpm/exe`'s parent is
+    // already `@pnpm`; the unscoped `pnpm` descends into `@pnpm`.
+    let Ok(wrapper_real_dir) = fs::canonicalize(&wrapper_dir) else {
+        return;
+    };
+    let Some(parent) = wrapper_real_dir.parent() else {
+        return;
+    };
+    let scope_dir =
+        if wrapper_pkg_name.starts_with('@') { parent.to_path_buf() } else { parent.join("@pnpm") };
+
+    let candidate_dir_names = [
+        exe_platform_pkg_dir_name(platform, arch, libc),
+        exe_platform_pkg_dir_name_next(platform, arch, libc),
+    ];
+    let Some(src) = candidate_dir_names
+        .iter()
+        .map(|dir_name| scope_dir.join(dir_name).join(executable))
+        .find(|candidate| candidate.exists())
+    else {
+        return;
+    };
+    let dest = wrapper_dir.join(executable);
+    if force_link(&src, &dest).is_err() {
+        return;
+    }
Evidence
The linking function is implemented as best-effort with many early returns and ignored link
failures, and the install flow explicitly relies on manual linking because scripts are disabled.

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[108-112]
pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[174-226]

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 self-update path can succeed even if the native `pnpm` binary was not linked into place. This can leave users with a broken installation (or missing Windows alias executables) while printing a success message.
## Issue Context
- The install intentionally sets `ignore_scripts = true`, so the wrapper’s preinstall hook that normally wires the platform binary is not run.
- `link_exe_platform_binary` is intended to replicate that preinstall step.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[43-79]
- pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[170-226]
### Implementation notes
- Change `link_exe_platform_binary(...)` to return `miette::Result<()>` (or a dedicated `SelfUpdateError`) and:
- error if the wrapper dir exists but no candidate platform binary is found
- error if canonicalize fails
- error if `force_link` fails
- on Windows, consider surfacing alias-link failures too (or at least warn)
- In `install_pnpm`, propagate that error so `self-update` fails instead of claiming success.
- Add a targeted unit/integration test that simulates missing optional platform binary and asserts the command errors.

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



Remediation recommended

7. Windows bin rewrite silently ignored 🐞 Bug ☼ Reliability ⭐ New
Description
link_exe_platform_binary calls rewrite_windows_bin_field but the helper returns () and
swallows every I/O and serialization failure via early return, so a failed rewrite is invisible to
the caller. The subsequent link_into_global_bin step reads the (now stale) package.json bin
field to generate cmd-shims, so the pn, pnpx, and pnx shims can be created pointing at the
wrong targets, breaking those aliases under MSYS2/Git Bash even though self-update reports success.
Code

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[259]

+        rewrite_windows_bin_field(&wrapper_dir);
Evidence
rewrite_windows_bin_field is defined to return () and uses early return on every failure path
(read, parse, write, rename). The call site at line 259 does not check any result. The global
bin-linking step (self_update.rs link_into_global_bin) calls read_installed_packages then
link_bins_of_packages_with_excludes, which reads each package's package.json bin field via
get_bins_from_package_manifest to decide what shims to create. If the bin field was not rewritten to
.exe targets, the generated shims will not invoke the .exe hardlinks created earlier.

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[285-311]
pacquet/crates/cli/src/cli_args/self_update.rs[418-421]
pacquet/crates/cmd-shim/src/bin_resolver.rs[49-63]

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

## Issue description
`rewrite_windows_bin_field` swallows all I/O and serialization failures and returns `()`. Its call site in `link_exe_platform_binary` ignores the result, so a failed rewrite leaves the installed `pnpm` wrapper's `package.json` with stale `bin` entries while self-update reports success. The subsequent global-bin linking step reads those stale entries to generate cmd-shims, breaking `pn`/`pnpx`/`pnx` under MSYS2/Git Bash.

## Issue Context
The function is called only on Windows after the `.exe` hardlinks have been created. Its purpose is to update the `bin` field in `package.json` so that the cmd-shim generator later writes shims pointing at `.exe` targets. A silent failure here means the shims are generated from the original (non-.exe) bin entries.

## Fix Focus Areas
- `pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[285-311]` — change `rewrite_windows_bin_field` to return `miette::Result<()>` and propagate errors instead of early-returning on failure
- `pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[259]` — propagate the returned error from the call site with `?` or `.wrap_err(...)?`

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


8. Unvalidated hardlink source type 🐞 Bug ⛨ Security
Description
force_link() hard-links src into the wrapper and then chmods the destination to 0755 without
verifying that src is a regular file; if a tampered store/install tree ever yields a symlink or
other non-file at src, hard_link() can preserve the symlink and the subsequent permission change
can apply to the symlink’s target. This is a filesystem-safety hazard on a trust-critical
self-update path (similar to the symlink+hardlink risk already called out elsewhere in the repo).
Code

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[R264-277]

+/// Hard-link `src` to `dest`, replacing any existing file. Marks the
+/// result executable on Unix (a copy/link can lose the bit).
+fn force_link(src: &Path, dest: &Path) -> std::io::Result<()> {
+    match fs::remove_file(dest) {
+        Ok(()) => {}
+        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
+        Err(err) => return Err(err),
+    }
+    fs::hard_link(src, dest)?;
+    #[cfg(unix)]
+    {
+        use std::os::unix::fs::PermissionsExt;
+        fs::set_permissions(dest, fs::Permissions::from_mode(0o755))?;
+    }
Evidence
force_link() currently performs fs::hard_link(src, dest) and then applies executable
permissions, with no file-type validation of src or dest. The codebase explicitly documents that
a symlinked store/CAS entry can cause downstream fs::hard_link to hardlink the symlink itself
(rather than the target), which is precisely the class of risk this self-update path should
defensively reject.

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[264-277]
pacquet/crates/fs/src/ensure_file.rs[254-266]

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 self-update` links the platform binary into the wrapper via `force_link()`, which calls `fs::hard_link(src, dest)` and then (on Unix) `fs::set_permissions(dest, 0o755)`. If `src` is ever a symlink or non-regular file (e.g. due to a tampered / backed-up-and-restored store or otherwise corrupted install tree), `hard_link()` can create a destination that is not a regular file, and the subsequent permission change can affect an unexpected target.
## Issue Context
The repo already treats “symlinked store entry + downstream hard_link” as a meaningful hazard and defends against it in the CAS layer; self-update’s linking path should apply the same file-type validation before hard-linking and chmodding.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[264-277]
### Suggested fix
- Before removing/replacing `dest`, check `fs::symlink_metadata(src)` and require `file_type().is_file()`.
- If `src` is not a regular file, return an error (preferred for self-update) rather than proceeding.
- (Optional) Consider also validating `dest` after linking (`symlink_metadata(dest)`) to ensure it is a regular file before chmod.

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


9. Packument size cap ineffective 🐞 Bug ⛨ Security
Description
verify_engine::fetch_packument calls response.text().await (full buffering) before enforcing the
MAX_PACKUMENT_BYTES limit, so a chunked/no-Content-Length response can still allocate
arbitrarily large memory and potentially OOM/crash self-update during signature verification.
Code

pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs[R466-479]

+    // Bound the buffered body so an oversized response from a
+    // misconfigured/compromised registry can't exhaust memory on this
+    // trust-critical path.
+    if let Some(length) = response.content_length()
+        && length > MAX_PACKUMENT_BYTES
+    {
+        return Err(format!("{display_url} returned an oversized packument ({length} bytes)"));
+    }
+    let body = response.text().await.map_err(|source| {
+        format!("{display_url}: {}", redact_url_credentials(&source.to_string()))
+    })?;
+    if body.len() as u64 > MAX_PACKUMENT_BYTES {
+        return Err(format!("{display_url} returned an oversized packument"));
+    }
Evidence
The code only rejects oversized bodies based on response.content_length() (optional) and then
performs a full buffered read via response.text().await before checking body.len(), which cannot
prevent unbounded allocation when Content-Length is missing/incorrect.

pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs[466-482]

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

## Issue description
`fetch_packument` tries to bound packument size, but it reads the entire response into memory via `response.text().await` before checking `body.len()`. If the server omits `Content-Length` (or uses chunked transfer), the pre-check is skipped and the post-check happens too late to prevent peak memory exhaustion.
### Issue Context
This code runs on a trust-critical verification path (`self-update` engine identity verification). The implementation comment explicitly intends to prevent memory exhaustion, but the current approach cannot enforce that intent without streaming/limiting the body during read.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs[466-483]
### Implementation notes
- Replace `response.text().await` with a streaming read that enforces a hard maximum while reading (e.g., consume `bytes_stream()` and stop/error once `MAX_PACKUMENT_BYTES + 1` is reached).
- Keep the existing `content_length()` pre-check as an early reject, but don’t rely on it.
- Parse JSON from the bounded buffer (or from a capped reader) after the streaming limit is enforced.

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


View more (7)
10. No global-bin precheck 🐞 Bug ☼ Reliability
Description
link_into_global_bin links pnpm shims without validating the global bin dir is on PATH and
writable, unlike other mutating global commands. This can lead to a partial self-update state
(engine installed but activation/linking fails) and harder-to-diagnose failures under misconfigured
global-bin-dir/PNPM_HOME.
Code

pacquet/crates/cli/src/cli_args/self_update.rs[R409-416]

+fn link_into_global_bin(config: &Config, install_dir: &Path) -> miette::Result<()> {
+    let global_bin = config.global_bin.clone().ok_or(SelfUpdateError::NoGlobalDir)?;
+    let global_pkg_dir = config.global_pkg_dir.clone().ok_or(SelfUpdateError::NoGlobalDir)?;
+
+    let pkgs = read_installed_packages(install_dir);
+    link_bins_of_packages_with_excludes::<CmdShimHost>(&pkgs, &global_bin, &HashSet::new())
+        .map_err(miette::Report::new)
+        .wrap_err("link the updated pnpm bins")?;
Evidence
self-update links bins directly using config.global_bin but does not perform the
PATH/writability preflight that other global-mutating commands enforce, so activation can fail late
and leave a partial update.

pacquet/crates/cli/src/cli_args/self_update.rs[406-424]
pacquet/crates/cli/src/cli_args/global.rs[73-99]
pacquet/crates/config/src/global_bin_check.rs[47-71]

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 self-update` links shims into the configured global bin dir without running the same preflight validation used by other global-mutating commands (PATH membership + writability). This can cause self-update to download/install successfully but fail to activate, leaving a confusing partial state.
## Issue Context
Global commands (`pnpm add -g` / `update -g`) run `check_global_bin_dir(...)` before writing shims.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update.rs[409-416]
- pacquet/crates/cli/src/cli_args/global.rs[73-99]
## Suggested fix
- Add a `check_bin_dir` helper (or inline call) in `self_update` that calls `pacquet_config::check_global_bin_dir(global_bin, PATH, true)`.
- Run this check before any install/linking work (ideally in the global-switch branch before `sync_package_manager_dependencies` and before writing shims), so failures don’t leave an installed-but-not-activated engine.
- Let `CheckGlobalBinDirError` bubble up (it already carries pnpm-matching error codes) rather than mapping everything to `NoGlobalDir`.

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


11. Temp write follows symlink 🐞 Bug ⛨ Security
Description
rewrite_windows_bin_field writes a predictable temp file (package.json.pnpm-tmp) via
fs::write, which follows symlinks if that path already exists. In a shared or attacker-influenced
global package directory, this can become a file-clobber primitive during self-update on Windows.
Code

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[R296-302]

+    let temp_path = pkg_json_path.with_extension("json.pnpm-tmp");
+    if fs::write(&temp_path, serialized).is_err() {
+        let _ = fs::remove_file(&temp_path);
+        return;
+    }
+    if fs::rename(&temp_path, &pkg_json_path).is_err() {
+        let _ = fs::remove_file(&temp_path);
Evidence
The current implementation writes to a fixed temp path with fs::write (symlink-following), while
other write paths in-repo explicitly unlink first to prevent symlink clobbering.

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[273-303]
pacquet/crates/cmd-shim/src/link_bins.rs[475-490]

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

## Issue description
On Windows, `rewrite_windows_bin_field` writes JSON to `package.json.pnpm-tmp` using `fs::write`. If an attacker can cause that temp path to exist as a symlink, the write can be redirected to an arbitrary target.
## Issue Context
Elsewhere, the repo explicitly unlinks pre-existing paths before writing because writes follow symlinks and can clobber arbitrary targets.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[273-303]
- pacquet/crates/cmd-shim/src/link_bins.rs[475-490]
## Suggested fix
- Avoid deterministic temp names in package directories. Prefer `tempfile::NamedTempFile::new_in(wrapper_dir)` (or `tempfile::Builder`) to create an unpredictable temp file.
- Before replacing `package.json`, consider `symlink_metadata` on the destination and refuse or remove it if it’s a symlink (defense-in-depth).
- Persist via atomic rename/replace (`NamedTempFile::persist` or write-then-rename), ensuring the final file is a regular file in `wrapper_dir`.
- Keep the existing “write via temp + rename” behavior, but make the temp creation and destination replacement symlink-safe.

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


12. Stale shims after self-update 🐞 Bug ☼ Reliability
Description
link_into_global_bin links shims for the new pnpm install but never removes any global-bin shims
that existed only in the previously active pnpm install. If the exposed bin set changes across
versions (or the old install dir is later pruned), stale shims can remain in the global bin dir,
pointing at outdated or missing binaries.
Code

pacquet/crates/cli/src/cli_args/self_update.rs[R409-416]

+fn link_into_global_bin(config: &Config, install_dir: &Path) -> miette::Result<()> {
+    let global_bin = config.global_bin.clone().ok_or(SelfUpdateError::NoGlobalDir)?;
+    let global_pkg_dir = config.global_pkg_dir.clone().ok_or(SelfUpdateError::NoGlobalDir)?;
+
+    let pkgs = read_installed_packages(install_dir);
+    link_bins_of_packages_with_excludes::<CmdShimHost>(&pkgs, &global_bin, &HashSet::new())
+        .map_err(miette::Report::new)
+        .wrap_err("link the updated pnpm bins")?;
Evidence
link_into_global_bin only links bins for the new install and never performs any removal; the
underlying bin-linker also does not delete unchosen shims. The existing global update implementation
demonstrates the intended stale-bin cleanup pattern by explicitly removing bins from the old install
prior to swapping and relinking.

pacquet/crates/cli/src/cli_args/self_update.rs[406-424]
pacquet/crates/cmd-shim/src/link_bins.rs[314-358]
pacquet/crates/cli/src/cli_args/global.rs[207-230]

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 self-update` links bins for the newly installed pnpm into the global bin dir, but it does not remove shims from the previously active pnpm install that are no longer produced by the new version.
This can leave stale commands in `PNPM_HOME`/global bin that (a) keep invoking an older pnpm install or (b) break once the old install directory is cleaned up as an orphan.
## Issue Context
- `link_bins_of_packages_with_excludes` only *writes* the selected shims; it does not delete any existing shims that are no longer part of the chosen set.
- The global update flow explicitly removes stale bins from the old install before swapping to the new install.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update.rs[406-424]
- pacquet/crates/cmd-shim/src/link_bins.rs[314-358]
- pacquet/crates/cli/src/cli_args/global.rs[207-230]
### Implementation direction
1. Before swapping the hash symlink / linking new bins, determine the previously active pnpm install dir (e.g., resolve the existing hash symlink for the pnpm group, or locate the current global pnpm group).
2. Compute the bins owned by that previous install and remove them from `global_bin` (ideally mirroring `global update -g`’s protection logic so bins owned by other global groups are not removed).
3. Proceed with `link_bins_of_packages_with_excludes` for the new install and then update the hash symlink.
4. (Optional) If safe, delete the old install dir after swapping, similar to the global update path.

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


13. Registry creds leak in errors 🐞 Bug ⛨ Security
Description
Signature-verification failures embed component.registry verbatim in user-facing error reasons,
which can leak embedded URL credentials (e.g. https://user:pass@host/...) when verification fails.
This undermines the repo’s existing URL credential redaction practice used elsewhere in network
error paths.
Code

pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs[R265-289]

+    let label = format!("{}@{}", component.name, component.version);
+    let packument = match fetch_packument(component, client, retry_opts, config).await {
+        Ok(Some(packument)) => packument,
+        Ok(None) => {
+            return Some(SignatureFailure {
+                reason: format!("{} is not published on {}", component.name, component.registry),
+                category: FailureCategory::Absent,
+                label,
+            });
+        }
+        Err(reason) => {
+            return Some(SignatureFailure {
+                reason,
+                category: FailureCategory::Unreachable,
+                label,
+            });
+        }
+    };
+
+    let Some(version) = packument.versions.get(&component.version) else {
+        return Some(SignatureFailure {
+            reason: format!("{label} was not found on {}", component.registry),
+            category: FailureCategory::Absent,
+            label,
+        });
Evidence
The failure reasons interpolate component.registry into strings. The repo’s
redact_url_credentials explicitly exists to prevent embedded user:pass@ in registry URLs from
leaking into error messages.

pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs[259-290]
pacquet/crates/network/src/auth.rs[460-480]

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

## Issue description
`verify_engine::find_signature_failure` formats failure reasons with `component.registry` directly. If the bootstrap registry is configured with embedded basic-auth userinfo in the URL, that secret will be printed in the final self-update error message.
### Issue Context
The codebase already has `redact_url_credentials()` specifically to prevent leaking `user:pass@` in URLs within errors/logs.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs[259-290]
### Suggested change
Introduce a redacted display value, e.g.:

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


14. Bad package.json blocks update 🐞 Bug ☼ Reliability
Description
self_update::handler aborts on JSON parse errors in the current directory’s package.json, even
when doing the global self-update flow where the project manifest should be best-effort. This
prevents pnpm self-update from working in directories with malformed manifests, despite the
command otherwise intentionally avoiding repo config influence.
Code

pacquet/crates/cli/src/cli_args/self_update.rs[R147-148]

+    let manifest_value = super::read_manifest_json(&dir.join("package.json"))?;
+    let wanted = manifest_value.as_ref().and_then(super::wanted_package_manager);
Evidence
handler uses read_manifest_json(...)?, and read_manifest_json propagates JSON parse failures
as errors, so a malformed package.json aborts the command instead of behaving like an unpinned
project (or proceeding with global update).

pacquet/crates/cli/src/cli_args/self_update.rs[121-149]
pacquet/crates/cli/src/cli_args.rs[1380-1387]

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

## Issue description
`self_update::handler` calls `super::read_manifest_json(...)?;` which returns an error on invalid JSON. That makes `self-update` fail before it can take the global-update path, even though the manifest is only used to detect/modify project pinning and to compute messaging.
### Issue Context
`read_manifest_json` returns `Ok(None)` for missing files but returns an error for malformed JSON.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update.rs[121-190]
### Suggested change
Change manifest reading in `handler` to be best-effort:
- On `Ok(Some(v))`, proceed as today.
- On `Ok(None)`, treat as no pin.
- On `Err(e)`, emit a warning (via reporter) and treat as no pin, allowing the global self-update path to continue.
Avoid changing `read_manifest_json` globally if other commands rely on it being strict; handle this locally in `self_update::handler`.

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


15. Downgrade guard parse bypass 🐞 Bug ⛨ Security
Description
In the project-pin path, the implicit-latest downgrade refusal can be bypassed when the pinned
version read from pnpm-lock.yaml is not valid semver, because version_lt returns false on
parse failure. This can allow an implicit pacquet self-update to proceed even when it would
otherwise refuse a downgrade based on the current pinned version.
Code

pacquet/crates/cli/src/cli_args/self_update.rs[R450-455]

+fn version_lt(left: &str, right: &str) -> bool {
+    match (node_semver::Version::parse(left), node_semver::Version::parse(right)) {
+        (Ok(left), Ok(right)) => left < right,
+        _ => false,
+    }
+}
Evidence
The implicit-latest downgrade refusal compares the resolved target against a lockfile-derived
"current" value, but the comparator intentionally treats unparseable inputs as not-less-than. This
means a malformed lockfile version disables the downgrade check instead of failing closed.

pacquet/crates/cli/src/cli_args/self_update.rs[262-270]
pacquet/crates/cli/src/cli_args/self_update.rs[389-403]
pacquet/crates/cli/src/cli_args/self_update.rs[450-455]
pacquet/crates/cli/src/cli_args/self_update/tests.rs[19-27]

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

## Issue description
`version_lt()` returns `false` whenever either side fails semver parsing. In the project-pin downgrade guard (`is_implicit_latest && version_lt(target_version, &current)`), `current` is derived from the env lockfile and can be malformed/unparseable; that makes the downgrade guard silently skip, allowing an implicit update that should have been refused.
### Issue Context
This is specifically about the *implicit* `latest` downgrade protection in the project-pin flow, where `current` comes from `read_project_pinned_pnpm_version()` (lockfile-derived) and is not validated before comparison.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update.rs[262-271]
- pacquet/crates/cli/src/cli_args/self_update.rs[385-405]
- pacquet/crates/cli/src/cli_args/self_update.rs[450-455]
### Suggested fix
Change the downgrade-guard logic to **fail closed** when `current` cannot be parsed as semver:
- Parse `current` and `target_version` explicitly in the guard.
- If parsing `current` fails, return a user-facing message like: "Cannot determine the currently pinned pnpm version from pnpm-lock.yaml; refusing implicit `latest` downgrade. Re-run with `pnpm self-update latest` to force." (mirrors the existing pattern of requiring explicit `latest` for downgrades).
- Alternatively, change `version_lt` to return `Option<bool>` (or `Option<Ordering>`) and make the guard treat `None` as a policy violation in the implicit-latest path.
Also update/add a unit test demonstrating that an unparseable `current` triggers the fail-closed behavior in the implicit-downgrade guard.

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


16. Existing install skips relink 🐞 Bug ☼ Reliability
Description
When install_pnpm detects the target version is already installed, it returns early without
re-running link_exe_platform_binary, so a previously partial/corrupted install won’t be repaired.
self-update can then link bins and report activation while the wrapper still lacks a working
native pnpm executable.
Code

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[R54-60]

+    if let Some(existing) = find_global_package(&global_pkg_dir, PNPM_PACKAGE_NAME)
+        .into_diagnostic()
+        .wrap_err("scan global packages")?
+        && installed_version(&existing.install_dir).as_deref() == Some(version)
+    {
+        return Ok(InstallPnpmResult { install_dir: existing.install_dir, already_existed: true });
+    }
Evidence
The early-return path only checks the recorded package.json version, while the binary-link step is
only executed on the fresh-install path. The command later reports activation for the
already-existing case, so a broken wrapper/native link can persist.

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[54-78]
pacquet/crates/cli/src/cli_args/self_update.rs[234-241]

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

## Issue description
`install_pnpm()` returns `already_existed: true` when it finds an existing global `pnpm` install directory matching the requested version, but this path skips `link_exe_platform_binary()`. If the existing install is missing the linked native binary (or aliases on Windows), self-update won’t fix it.
### Issue Context
The fresh-install path explicitly calls `link_exe_platform_binary()` after `run_install()`, but the reuse path does not.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[54-78]
- pacquet/crates/cli/src/cli_args/self_update.rs[227-241]
### Suggested fix
Before returning `already_existed: true`, run a repair step:
- Call `link_exe_platform_binary(&existing.install_dir, PNPM_PACKAGE_NAME)` (and propagate errors) before returning.
- Optionally, only do it when `node_modules/<wrapper>/pnpm[.exe]` is missing, but unconditional relink is simplest and cheap.
This makes `self-update` idempotent and able to heal a partial previous update.

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


Grey Divider

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

🤖 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 `@pacquet/crates/cli/src/cli_args.rs`:
- Around line 1058-1060: The SelfUpdate dispatch path in CliCommand::SelfUpdate
currently calls config() before checking Corepack, which can surface config
errors instead of the intended Corepack refusal. Reorder the logic in this arm
so the Corepack guard is evaluated first, before loading project config, and
ensure it returns the same ERR_PNPM_CANT_SELF_UPDATE_IN_COREPACK behavior as
handler and the self-update contract require.

In `@pacquet/crates/cli/src/cli_args/self_update.rs`:
- Around line 145-149: Use the resolved project pin when computing
`previous_version` in `self_update.rs` so major-upgrade detection works for
range pins like `^10.0.0`. Update the `match &wanted` logic to reuse
`read_project_pinned_pnpm_version` (instead of relying only on
`pm.version`/`coerce_major`) so the exact env-lockfile version is available, and
then compare that resolved version against `target_version` in the same
`previous_version` flow.
- Around line 441-445: The range_satisfies helper currently rejects prerelease
versions like 1.2.3-beta.1 even when the stripped base version 1.2.3 would
satisfy the range. Update range_satisfies in self_update.rs to detect prerelease
targets, retry the check with the base version, and use that fallback when
node_semver::Range::satisfies fails on the prerelease form.

In `@pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs`:
- Around line 77-78: The self-update flow is reporting success even when the
native wrapper link step fails, so `install_pnpm()` should surface any failure
from `link_exe_platform_binary()` instead of continuing. Update the
`install_pnpm` path and the related wrapper-linking logic in
`link_exe_platform_binary` so missing platform packages, hardlink failures, or
other early returns become errors that abort the install. Make sure the same
failure handling is applied to the other wrapper-linking call sites referenced
by this flow so `InstallPnpmResult` is only returned after a runnable native
`pnpm` binary is actually installed.

In `@pacquet/crates/cli/src/cli_args/self_update/install_pnpm/tests.rs`:
- Around line 3-21: The existing tests only validate the platform directory name
helpers, but they do not cover the filesystem behavior introduced by
link_exe_platform_binary() and rewrite_windows_bin_field(). Add TempDir-based
regression tests that exercise hardlinking the wrapper binary, alias creation,
and the Windows bin-field rewrite, and assert the installed layout/metadata
matches the expected cross-platform contract. Prefer real fixture-style coverage
in the test module so the behavior is proven end-to-end rather than only by
helper function outputs.

In `@pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs`:
- Around line 77-514: Add regression coverage for the trust-decision flow in
verify_pnpm_engine_identity and its helpers. Create tests that prove signature
acceptance, expired-key rejection, malformed signatures metadata, and
unreachable-vs-mismatch classification, exercising find_signature_failure,
signature_validates, and fetch_packument behavior. Keep the tests aligned with
pnpm-parity expectations and fail-closed behavior so the self-update gate is
covered end to end.
- Around line 82-86: Remove the runtime environment-variable bypass from
verify_engine::verify_engine so engine signature verification cannot be disabled
in non-test builds. Move the PACQUET_SELF_UPDATE_SKIP_ENGINE_VERIFY_FOR_TESTS
seam behind cfg(test) or route it through the test harness only, and keep the
normal trust check path in place for all production calls. Use the existing
verify_engine function and its early-return branch as the fix location.

In `@pacquet/crates/cli/src/config_deps.rs`:
- Around line 99-102: The maturity cutoff computation in `config_deps.rs`
currently falls back to `None` via `resolved_minimum_release_age`/`published_by`
when conversion or date arithmetic fails, which disables the gate. Update the
logic around `resolved_minimum_release_age`, `try_minutes`, and
`Utc::now().checked_sub_signed` so failures return an error instead of silently
producing `None`, ensuring `minimumReleaseAge`-based self-update checks fail
closed.
🪄 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: c563dc0e-dab2-4879-bb0a-ea8a1a94ef96

📥 Commits

Reviewing files that changed from the base of the PR and between 687e92b and 90f686a.

📒 Files selected for processing (7)
  • pacquet/crates/cli/src/cli_args.rs
  • pacquet/crates/cli/src/cli_args/self_update.rs
  • pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs
  • pacquet/crates/cli/src/cli_args/self_update/install_pnpm/tests.rs
  • pacquet/crates/cli/src/cli_args/self_update/tests.rs
  • pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs
  • pacquet/crates/cli/src/config_deps.rs

Comment thread pacquet/crates/cli/src/cli_args.rs Resolved
Comment thread pacquet/crates/cli/src/config_deps.rs Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 90f686a

@zkochan
zkochan force-pushed the feat/pacquet-self-update branch from 90f686a to 2344563 Compare June 27, 2026 09:51

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

🤖 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 `@pacquet/crates/cli/src/cli_args/self_update/tests.rs`:
- Line 25: The self-update test comment contains a misspelled word; update the
comment in the self_update tests so it uses “Unparsable” instead of
“Unparseable” to satisfy the spell-check rule. Locate the affected comment near
the self_update test case in tests.rs and make only the wording correction.

In `@pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs`:
- Around line 152-183: The self-update verification flow in verify_components is
failing open when the host platform binary for `@pnpm/exe` cannot be resolved from
the snapshot or optional_dependencies, allowing verification to succeed after
only checking pnpm and `@pnpm/exe`. Update the logic around engine_component,
plain_version, and the candidate_names loop so that missing/unparseable snapshot
data, absent optional deps, or no matching host package cause verification to
fail closed instead of returning Ok(to_verify); treat the host package as
required whenever `@pnpm/exe` is present.
🪄 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: 7ba4d676-ac50-4b5b-9ec9-777ee6ba0b09

📥 Commits

Reviewing files that changed from the base of the PR and between 90f686a and 2344563.

📒 Files selected for processing (7)
  • pacquet/crates/cli/src/cli_args.rs
  • pacquet/crates/cli/src/cli_args/self_update.rs
  • pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs
  • pacquet/crates/cli/src/cli_args/self_update/install_pnpm/tests.rs
  • pacquet/crates/cli/src/cli_args/self_update/tests.rs
  • pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs
  • pacquet/crates/cli/src/config_deps.rs
🚧 Files skipped from review as they are similar to previous changes (5)
  • pacquet/crates/cli/src/cli_args.rs
  • pacquet/crates/cli/src/config_deps.rs
  • pacquet/crates/cli/src/cli_args/self_update/install_pnpm/tests.rs
  • pacquet/crates/cli/src/cli_args/self_update.rs
  • pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs

@github-actions

github-actions Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
tarball/download_dependency    1.00      6.8±0.36ms   638.1 KB/sec    1.00      6.8±0.50ms   637.7 KB/sec

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

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown

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

@codecov-commenter

codecov-commenter commented Jun 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 14.76888% with 756 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.88%. Comparing base (4e18e44) to head (1967227).

Files with missing lines Patch % Lines
pacquet/crates/cli/src/cli_args/self_update.rs 7.86% 281 Missing ⚠️
...ates/cli/src/cli_args/self_update/verify_engine.rs 12.57% 278 Missing ⚠️
...rates/cli/src/cli_args/self_update/install_pnpm.rs 35.55% 116 Missing ⚠️
pacquet/crates/cli/src/config_deps.rs 0.00% 67 Missing ⚠️
pacquet/crates/cli/src/cli_args/dispatch_query.rs 0.00% 12 Missing ⚠️
pacquet/crates/cli/src/cli_args/dispatch.rs 0.00% 1 Missing ⚠️
pacquet/crates/cli/src/cli_args/package_manager.rs 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #12693      +/-   ##
==========================================
- Coverage   86.96%   85.88%   -1.08%     
==========================================
  Files         382      385       +3     
  Lines       58161    59044     +883     
==========================================
+ Hits        50577    50708     +131     
- Misses       7584     8336     +752     

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

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 640b0db

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

qodo-free-for-open-source-projects Bot commented Jun 27, 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

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

Copy link
Copy Markdown

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

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

qodo-free-for-open-source-projects Bot commented Jun 27, 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-free-for-open-source-projects

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown

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

Ports pnpm's `self-update` command to the Rust pacquet CLI, matching the
TypeScript implementation in pnpm11/engine/pm/commands/src/self-updater.
The pnpm side already has this command, so this is the pacquet port — no
TypeScript change is needed.

`pacquet self-update [VERSION]` resolves the target version from the trusted
package-manager bootstrap registry (never the repo-controlled project
registries), honoring minimumReleaseAge / trustPolicy with strict
resolution failing closed. It guards against corepack (before loading
project config), refuses to downgrade on an implicit `latest`, prints the
already-up-to-date / downgrade no-op messages, and emits the major-upgrade
migration hint (using the resolved env-lockfile version so range pins still
trigger it).

When the project pins pnpm via packageManager / devEngines.packageManager,
the pin is updated in place (range-style preserved, integrities persisted).
Otherwise the engine is installed into the global packages directory through
the bootstrap config: integrities are resolved into the env lockfile, the
engine's npm registry signature is verified against npm's embedded public
keys (failing closed, including when the host platform binary can't be
collected), the host's native platform binary is hard-linked into the
wrapper (the preinstall is skipped because the engine installs with scripts
disabled; link failures are propagated), and the bins are linked into the
global bin directory with a bootstrap-registry cache-keyed hash symlink.

New modules under cli_args/self_update: install_pnpm (installPnpm +
linkExePlatformBinary) and verify_engine (verifyPnpmEngineIdentity).
config_deps gains resolve_pnpm_version, the policy-aware version probe,
which fails closed if the specifier resolves to a package other than pnpm.
The shared packageManager helpers move to pub(crate) so the new module can
reuse them. Unit tests cover platform dir-name parity, version-constraint
preservation, semver comparison, signature accept/expiry/unknown-key
rejection, and platform-binary linking.
@zkochan
zkochan force-pushed the feat/pacquet-self-update branch from 8be8ae7 to 7b28a19 Compare June 27, 2026 10:50
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 7b28a19

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 7b28a19

…ile from the workspace root

Address the latest review findings:

- run_install now clears repo-controlled resolution-rewrite settings
  (overrides, packageExtensions, catalogs, patchedDependencies) before
  installing the engine, so a project's pnpm-workspace.yaml can't change the
  installed engine's dependency closure even though the top-level engine
  components are signature-verified.
- read_project_pinned_pnpm_version now reads the env lockfile from the
  workspace root (config.workspace_dir, falling back to --dir) instead of
  the command's working directory, so a workspace self-update invoked from a
  package subdirectory still sees the pinned pnpm version (preserving the
  implicit-latest downgrade refusal and the major-upgrade hint).
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown

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

@zkochan
zkochan merged commit f8e5a0d into main Jun 27, 2026
33 checks passed
@zkochan
zkochan deleted the feat/pacquet-self-update branch June 27, 2026 11:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants