Skip to content

feat(pacquet): logout - #12568

Merged
zkochan merged 10 commits into
mainfrom
claude/magical-shannon-cnmpl6
Jun 27, 2026
Merged

zkochan merged 10 commits into
mainfrom
claude/magical-shannon-cnmpl6

Conversation

@KSXGitHub

@KSXGitHub KSXGitHub commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Ports pnpm logout to pacquet (the Rust port). Part of the Rust Roadmap (pnpm/pnpm#11633).

pnpm logout revokes the registry auth token on the server (DELETE -/user/token/<token>) and removes it from auth.ini. It warns when the token actually lives in .npmrc or another source pnpm doesn't own (revoked on the registry, but must be removed manually), and fails only when the registry rejects the revocation and there is no local token left to remove.

Implemented as a new pacquet-auth-commands crate plus a pacquet logout [--registry <url>] CLI command. Behavior, flags, error codes (ERR_PNPM_NOT_LOGGED_IN, ERR_PNPM_LOGOUT_FAILED), and messages mirror the TypeScript @pnpm/auth.commands implementation.

Dependency injection. Upstream injects its side effects (fetch, readIniFile, writeIniFile, globalInfo, globalWarn) through a LogoutContext object of functions. This port uses pacquet's documented capability-trait seam instead: FsReadToString / FsWrite / RevokeToken are Sys-bound capabilities with no &self receiver (production provider Host; test fakes are unit structs), and the two global* channels go through the Reporter seam.

Config. Adds Config::auth_tokens_by_uri (raw _authToken per nerf-darted registry URI) and Config::config_dir. Config previously baked credentials into ready-to-send Authorization headers and discarded the raw token; logout needs the raw token to build the revoke URL/header, and the config dir to locate auth.ini.

Tests

  • All 13 cases from pnpm11/auth/commands/test/logout.test.ts ported as DI unit tests. (pnpm11/pnpm/test/ has no logout end-to-end test to port — the only upstream logout coverage is that unit file.)
  • Real-fixture integration tests covering the production paths the DI fakes bypass:
    • The Host provider via tempfile::TempDir + mockito (revoke-success / registry-rejects / unreachable).
    • A binary test that spawns pacquet logout against a mocked registry, covering the CLI adapter (LogoutArgs::run) and dispatch end-to-end.
  • Unit tests closing the remaining defensive branches: auth_tokens_by_uri population for default credentials, and the missing-config-dir guard.

Parity / changeset

pacquet-only (Rust) change — the TypeScript pnpm logout already exists upstream, so there is nothing to mirror on the TS side, and no changeset is needed (changesets cover published TS packages only).

Squash Commit Body

Port `pnpm logout` to pacquet as a new pacquet-auth-commands crate and a
`pacquet logout [--registry <url>]` CLI command, mirroring the TypeScript
@pnpm/auth.commands behavior, flags, error codes, and messages.

The command revokes the registry auth token (DELETE -/user/token/<token>)
and removes it from auth.ini. It warns when the token lives in .npmrc or
another source pnpm does not own, and fails only when the registry rejects
revocation and no local token is left to remove.

Upstream wires side effects through a LogoutContext object of functions;
this port uses pacquet's capability-trait DI seam instead: FsReadToString /
FsWrite / RevokeToken on Sys (production provider Host, test fakes are unit
structs), and the global* log channels through the Reporter seam.

Config gains auth_tokens_by_uri (raw _authToken per nerf-darted registry
URI) and config_dir, since Config previously baked credentials into
Authorization headers and discarded the raw token that logout must revoke.

Tests: all 13 upstream logout.test.ts cases ported as DI unit tests, plus
real-fixture integration tests (the Host provider via TempDir + mockito, and
a binary test spawning `pacquet logout`) covering the production code paths
the DI fakes bypass.

Part of the Rust Roadmap (pnpm/pnpm#11633).

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust pacquet/ port — the TypeScript pnpm logout already exists upstream; this PR is the matching pacquet port.
  • Added a changeset — N/A: pacquet is Rust-only and changes no published package, so no changeset is required.
  • Added or updated tests — 13 ported DI unit tests, real-fixture integration tests (Host provider + pacquet logout binary), and coverage-closing unit tests.
  • Updated the documentation if needed — updated pacquet/plans/TEST_PORTING.md; no user-facing docs change (the command mirrors the already-documented pnpm logout).

Written by an agent (Claude Code).

Summary by CodeRabbit

  • New Features
    • Added a new logout CLI command to sign out from an npm registry.
    • Introduced local auth token storage to enable remote token revocation and auth.ini updates.
  • Bug Fixes
    • Improved handling when auth.ini is missing or the token isn’t present locally, with clearer warnings and consistent error reporting (including unreachable/non-OK registries).
  • Security / Logging
    • Improved log redaction and retry error handling to avoid leaking sensitive URL details and control characters.
  • File Safety
    • Added atomic, symlink-safe config/INI writes.
  • Tests
    • Added unit and end-to-end coverage for token revocation, registry URL normalization/encoding, local auth.ini cleanup, redaction, and atomic write behavior.

@coderabbitai

coderabbitai Bot commented Jun 22, 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 new logout command, raw auth-token capture in config, flat auth.ini handling, atomic INI writes, and CLI wiring. Also adds a shared sanitizer for logged URL text and uses it in ping and retry logging.

Changes

pnpm logout implementation

Layer / File(s) Summary
Auth token config plumbing
Cargo.toml, pacquet/crates/auth-commands/Cargo.toml, pacquet/crates/auth-commands/src/lib.rs, pacquet/crates/cli/Cargo.toml, pacquet/crates/config/src/lib.rs, pacquet/crates/config/src/npmrc_auth.rs, pacquet/crates/config/src/npmrc_auth/tests.rs, pacquet/crates/package-manager/src/install_package_from_registry/tests.rs
Adds the pacquet-auth-commands workspace crate and dependency, exports it through the crate entrypoints, stores raw auth tokens on Config, and records those tokens while building registry auth headers.
IniSettings flat INI reader/writer
pacquet/crates/auth-commands/src/ini.rs, pacquet/crates/auth-commands/src/ini/tests.rs
Introduces IniSettings for parsing, removing, serializing, and testing flat key=value auth.ini entries.
Atomic INI writes
pacquet/crates/fs/Cargo.toml, pacquet/crates/fs/src/lib.rs, pacquet/crates/fs/src/write_atomic.rs, pacquet/crates/fs/src/write_atomic/tests.rs, pacquet/crates/cli/src/cli_args/config/ini.rs
Adds write_atomic in pacquet-fs, re-exports it, and changes the CLI INI writer to delegate atomic, symlink-safe file replacement to that helper.
Logout capability traits and flow
pacquet/crates/auth-commands/src/logout.rs
Defines the logout capability traits, the production Host, registry normalization and encoding helpers, LogoutOptions, the async logout flow, and LogoutError.
CLI command wiring
pacquet/crates/cli/src/cli_args.rs, pacquet/crates/cli/src/cli_args/cli_command.rs, pacquet/crates/cli/src/cli_args/dispatch.rs, pacquet/crates/cli/src/cli_args/dispatch_query.rs, pacquet/crates/cli/src/cli_args/logout.rs, pacquet/crates/cli/src/cli_args/logout/tests.rs, pacquet/crates/cli/tests/logout.rs
Registers the logout subcommand, routes it through dispatch, and builds the adapter that loads config, constructs the HTTP client, and calls the logout command.
Logout unit and integration tests
pacquet/crates/auth-commands/src/logout/tests.rs, pacquet/plans/TEST_PORTING.md
Adds reporter and system fakes, branch coverage for logout outcomes, end-to-end Host coverage, and the porting plan entry for the logout test cases.

Shared URL sanitization

Layer / File(s) Summary
Shared sanitizer
pacquet/crates/network/src/auth.rs, pacquet/crates/network/src/lib.rs, pacquet/crates/network/src/auth/tests.rs
Adds redact_and_sanitize, re-exports it from the network crate, and tests that it removes embedded credentials and control characters.
Ping and retry logging
pacquet/crates/cli/src/cli_args/ping.rs, pacquet/crates/network/src/retry.rs
Switches ping to the shared sanitizer, removes the local helper, and strips URLs from retry errors before warning logs.

Sequence Diagram(s)

sequenceDiagram
  participant LogoutArgsRun as LogoutArgs::run
  participant LogoutFn as pacquet_auth_commands::logout
  participant Host
  participant Registry
  participant IniSettings
  participant FsWrite

  LogoutArgsRun->>LogoutFn: LogoutOptions + ThrottledClient
  LogoutFn->>Host: revoke(http_client, revoke_url, token, retry)
  Host->>Registry: DELETE /-/user/token/:encoded_token
  Registry-->>Host: RevokeOutcome
  LogoutFn->>IniSettings: parse(auth.ini)
  LogoutFn->>IniSettings: remove(token_key)
  LogoutFn->>FsWrite: write(auth.ini, serialize())
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • pnpm/pnpm#12011: Introduces the logout/revocation HTTP flow that matches the new DELETE /-/user/token/<token> behavior.
  • pnpm/pnpm#12666: Shares the ping sanitization path updated here to use redact_and_sanitize.
  • pnpm/pnpm#12672: Also changes auth.ini writing and the atomic file-write helper used by that path.

Suggested reviewers

  • zkochan
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/magical-shannon-cnmpl6

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.

@github-actions

github-actions Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
tarball/download_dependency    1.05      6.7±0.03ms   647.6 KB/sec    1.00      6.4±0.04ms   681.3 KB/sec

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

🧹 Nitpick comments (3)
pacquet/crates/auth-commands/src/logout/tests.rs (1)

97-498: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Add a regression test for WriteAuthIni propagation.

The suite covers read failures and logout-failed branches, but it does not force FsWrite::write to fail and assert LogoutError::WriteAuthIni. Adding that case would lock down the remaining filesystem error path.

As per coding guidelines, REVIEW_GUIDE.md requires regression coverage for logout behavior and error paths.

🤖 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 `@pacquet/crates/auth-commands/src/logout/tests.rs` around lines 97 - 498, Add
a regression test following the pattern of the existing
`propagates_non_non_not_found_read_errors` test that covers the `WriteAuthIni`
error path. Create a new test function that configures the sys_fake to fail when
writing to auth.ini (by making the write operation return an appropriate error),
calls the logout function with valid setup that would normally succeed but the
write fails, and asserts that the error returned is `LogoutError::WriteAuthIni`
with the expected error details included. This will complete the filesystem
error path coverage alongside the existing read error handling tests.

Source: Coding guidelines

pacquet/crates/cli/src/cli_args/logout.rs (1)

26-30: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Route this user-facing error through pacquet-diagnostics instead of an inline miette! diagnostic.

Line 27 creates a command-specific ad-hoc diagnostic in the CLI layer. Please define/use the error in pacquet-diagnostics and return that typed diagnostic here to keep user-facing error contracts centralized and consistent.
As per coding guidelines, "User-facing errors go through miette via the pacquet-diagnostics crate."

🤖 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 `@pacquet/crates/cli/src/cli_args/logout.rs` around lines 26 - 30, The inline
miette! diagnostic for the missing config directory case in the logout function
needs to be refactored to use the pacquet-diagnostics crate instead. Define a
new error type in pacquet-diagnostics that represents the ERR_PNPM_NO_CONFIG_DIR
error condition (or use an existing one if available), then replace the inline
miette! call in the logout.rs file with a return statement that constructs and
returns the typed diagnostic from pacquet-diagnostics, ensuring the error
handling is centralized and maintains consistency with the coding guidelines.

Source: Coding guidelines

pacquet/crates/auth-commands/src/lib.rs (1)

6-7: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Reorder module declarations to match pacquet style.

pub mod declarations should come before private mod declarations in this crate style.

Suggested change
-mod ini;
 pub mod logout;
+mod ini;

As per coding guidelines, pacquet/CODE_STYLE_GUIDE.md requires module declarations ordered as “pub mod declarations first, then pub use, then private imports.”

🤖 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 `@pacquet/crates/auth-commands/src/lib.rs` around lines 6 - 7, The module
declarations in the lib.rs file are in the wrong order. According to the pacquet
code style guide, public module declarations must appear before private module
declarations. Reorder the modules so that the pub mod logout declaration comes
before the private mod ini declaration. This ensures consistency with the
crate's coding standards where public exports are declared first, followed by
private modules.

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.

Nitpick comments:
In `@pacquet/crates/auth-commands/src/lib.rs`:
- Around line 6-7: The module declarations in the lib.rs file are in the wrong
order. According to the pacquet code style guide, public module declarations
must appear before private module declarations. Reorder the modules so that the
pub mod logout declaration comes before the private mod ini declaration. This
ensures consistency with the crate's coding standards where public exports are
declared first, followed by private modules.

In `@pacquet/crates/auth-commands/src/logout/tests.rs`:
- Around line 97-498: Add a regression test following the pattern of the
existing `propagates_non_non_not_found_read_errors` test that covers the
`WriteAuthIni` error path. Create a new test function that configures the
sys_fake to fail when writing to auth.ini (by making the write operation return
an appropriate error), calls the logout function with valid setup that would
normally succeed but the write fails, and asserts that the error returned is
`LogoutError::WriteAuthIni` with the expected error details included. This will
complete the filesystem error path coverage alongside the existing read error
handling tests.

In `@pacquet/crates/cli/src/cli_args/logout.rs`:
- Around line 26-30: The inline miette! diagnostic for the missing config
directory case in the logout function needs to be refactored to use the
pacquet-diagnostics crate instead. Define a new error type in
pacquet-diagnostics that represents the ERR_PNPM_NO_CONFIG_DIR error condition
(or use an existing one if available), then replace the inline miette! call in
the logout.rs file with a return statement that constructs and returns the typed
diagnostic from pacquet-diagnostics, ensuring the error handling is centralized
and maintains consistency with the coding guidelines.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 2721fc2e-b17a-43cc-a5c6-f4c3bd28b035

📥 Commits

Reviewing files that changed from the base of the PR and between e72b482 and 24ac291.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (14)
  • Cargo.toml
  • pacquet/crates/auth-commands/Cargo.toml
  • pacquet/crates/auth-commands/src/ini.rs
  • pacquet/crates/auth-commands/src/ini/tests.rs
  • pacquet/crates/auth-commands/src/lib.rs
  • pacquet/crates/auth-commands/src/logout.rs
  • pacquet/crates/auth-commands/src/logout/tests.rs
  • pacquet/crates/cli/Cargo.toml
  • pacquet/crates/cli/src/cli_args.rs
  • pacquet/crates/cli/src/cli_args/logout.rs
  • pacquet/crates/config/src/lib.rs
  • pacquet/crates/config/src/npmrc_auth.rs
  • pacquet/crates/package-manager/src/install_package_from_registry/tests.rs
  • pacquet/plans/TEST_PORTING.md

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jun 22, 2026
@codecov-commenter

codecov-commenter commented Jun 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.65471% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.48%. Comparing base (e96c2ef) to head (d119959).

Files with missing lines Patch % Lines
pacquet/crates/cli/src/cli_args/dispatch_query.rs 77.77% 2 Missing ⚠️
pacquet/crates/fs/src/write_atomic.rs 93.75% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #12568      +/-   ##
==========================================
+ Coverage   85.43%   85.48%   +0.05%     
==========================================
  Files         389      393       +4     
  Lines       59609    59808     +199     
==========================================
+ Hits        50926    51126     +200     
+ Misses       8683     8682       -1     

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

@github-actions

github-actions Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: b9ea70dc86df

Each scenario reports direct installs and pnpr installs. Bencher consumes pacquet@HEAD and pnpr@HEAD.

Scenario: Isolated linker: fresh restore, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.934 ± 0.202 4.696 5.227 1.67 ± 0.10
pacquet@main 4.822 ± 0.108 4.703 5.015 1.63 ± 0.08
pnpr@HEAD 2.978 ± 0.148 2.825 3.217 1.01 ± 0.07
pnpr@main 2.959 ± 0.134 2.843 3.239 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.93419951198,
      "stddev": 0.20215944347118048,
      "median": 4.93228464308,
      "user": 4.0254628199999996,
      "system": 3.4441065800000006,
      "min": 4.69561297758,
      "max": 5.22709868858,
      "times": [
        5.06717674758,
        5.21026869758,
        5.22709868858,
        5.04264677058,
        4.99254407858,
        4.87202520758,
        4.74178225958,
        4.69561297758,
        4.79452399058,
        4.69831570158
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.82165444318,
      "stddev": 0.10821570846252558,
      "median": 4.79288627608,
      "user": 4.01838242,
      "system": 3.4531013799999997,
      "min": 4.70316536858,
      "max": 5.01462754358,
      "times": [
        4.81781717258,
        4.73724851758,
        4.71076308458,
        4.94804117458,
        4.91256202758,
        4.74386497658,
        4.76795537958,
        4.86049918658,
        5.01462754358,
        4.70316536858
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.97760096688,
      "stddev": 0.14765604706646057,
      "median": 2.91367736458,
      "user": 2.8243810199999997,
      "system": 2.965850180000001,
      "min": 2.82540720058,
      "max": 3.21652359358,
      "times": [
        2.91861742358,
        2.90873730558,
        3.11978775458,
        2.88680786758,
        3.21652359358,
        3.20595128558,
        2.97064239758,
        2.82540720058,
        2.85025726158,
        2.87327757858
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 2.9591867933800002,
      "stddev": 0.13422576977379158,
      "median": 2.90645168258,
      "user": 2.81431732,
      "system": 2.9564990799999995,
      "min": 2.84271099058,
      "max": 3.23947680358,
      "times": [
        2.93619488658,
        3.04371701558,
        2.91004733558,
        2.84271099058,
        3.23947680358,
        2.86767434258,
        3.12775428358,
        2.87769457758,
        2.84374166858,
        2.90285602958
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, hot cache + hot store

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 657.8 ± 8.6 642.4 671.5 1.00
pacquet@main 662.8 ± 37.8 631.8 764.8 1.01 ± 0.06
pnpr@HEAD 722.4 ± 49.0 681.7 853.1 1.10 ± 0.08
pnpr@main 738.1 ± 64.2 693.0 875.6 1.12 ± 0.10
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.65778637332,
      "stddev": 0.008596813545181133,
      "median": 0.65802797682,
      "user": 0.39706357999999997,
      "system": 1.32985756,
      "min": 0.64242545732,
      "max": 0.67150799932,
      "times": [
        0.6562368603200001,
        0.66425899732,
        0.65096848632,
        0.65012631732,
        0.64242545732,
        0.67150799932,
        0.66432983032,
        0.66362715432,
        0.65456353732,
        0.65981909332
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.66275453802,
      "stddev": 0.037823005188098405,
      "median": 0.6548271933200001,
      "user": 0.38493787999999995,
      "system": 1.33576966,
      "min": 0.6318032583200001,
      "max": 0.76477722532,
      "times": [
        0.65323190532,
        0.64935972332,
        0.6318032583200001,
        0.64147603832,
        0.66679351032,
        0.63671026332,
        0.76477722532,
        0.65848799532,
        0.66848297932,
        0.65642248132
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.7223569788199999,
      "stddev": 0.04900157754412094,
      "median": 0.7123677418200001,
      "user": 0.42341858,
      "system": 1.3632205599999998,
      "min": 0.68168218432,
      "max": 0.85305253332,
      "times": [
        0.71973933632,
        0.68168218432,
        0.69645732132,
        0.6897226763200001,
        0.72322593832,
        0.73547469132,
        0.69671069832,
        0.72250826132,
        0.85305253332,
        0.70499614732
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.7380941039199999,
      "stddev": 0.06420900511204328,
      "median": 0.71367044782,
      "user": 0.40785007999999995,
      "system": 1.37508736,
      "min": 0.69296428932,
      "max": 0.8755518143200001,
      "times": [
        0.69782688632,
        0.72365555332,
        0.69377678732,
        0.71848087232,
        0.70886002332,
        0.8755518143200001,
        0.72601231032,
        0.70592103732,
        0.69296428932,
        0.83789146532
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.844 ± 0.059 4.767 4.937 1.51 ± 0.07
pacquet@main 4.733 ± 0.041 4.686 4.797 1.47 ± 0.07
pnpr@HEAD 3.218 ± 0.143 3.033 3.438 1.00
pnpr@main 3.231 ± 0.160 3.024 3.621 1.00 ± 0.07
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.844236959020001,
      "stddev": 0.05921390295455596,
      "median": 4.83892492162,
      "user": 3.9652902599999997,
      "system": 3.3687090999999993,
      "min": 4.76744550012,
      "max": 4.93710301912,
      "times": [
        4.93710301912,
        4.90115745012,
        4.79122889912,
        4.846605691120001,
        4.8053733671200005,
        4.83124415212,
        4.8578924721200005,
        4.78511872212,
        4.9192003171200005,
        4.76744550012
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.73315357862,
      "stddev": 0.04121377531381851,
      "median": 4.71904182812,
      "user": 3.90894766,
      "system": 3.3015186,
      "min": 4.68644046012,
      "max": 4.79727153512,
      "times": [
        4.79593588912,
        4.77618812312,
        4.68644046012,
        4.7197786741200005,
        4.72760319512,
        4.71830498212,
        4.69920286512,
        4.69917731912,
        4.79727153512,
        4.71163274312
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.2178253732199993,
      "stddev": 0.1425488871507281,
      "median": 3.18810807112,
      "user": 2.90043796,
      "system": 3.0833321999999996,
      "min": 3.03295803912,
      "max": 3.4383302361199997,
      "times": [
        3.1143536131199996,
        3.08891008812,
        3.08974030412,
        3.20380557212,
        3.03295803912,
        3.3539225021199996,
        3.2930451221199997,
        3.3907776851199998,
        3.4383302361199997,
        3.17241057012
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.23069325732,
      "stddev": 0.16038745458191497,
      "median": 3.21774973662,
      "user": 2.90246916,
      "system": 3.0965808999999997,
      "min": 3.02433864512,
      "max": 3.62110364212,
      "times": [
        3.2294062601199998,
        3.2306348471199997,
        3.3023252741199998,
        3.1746474381199996,
        3.62110364212,
        3.20609321312,
        3.06981194912,
        3.25318819512,
        3.02433864512,
        3.19538310912
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, hot cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.362 ± 0.010 1.343 1.377 1.00
pacquet@main 1.369 ± 0.017 1.349 1.408 1.00 ± 0.01
pnpr@HEAD 1.461 ± 0.072 1.422 1.664 1.07 ± 0.05
pnpr@main 1.437 ± 0.024 1.398 1.476 1.05 ± 0.02
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.3620381751,
      "stddev": 0.009994552628022128,
      "median": 1.3633336024,
      "user": 1.3007016399999998,
      "system": 1.70793844,
      "min": 1.3430128609,
      "max": 1.3768337259,
      "times": [
        1.3633813709,
        1.3585233539000001,
        1.3430128609,
        1.3675466119000002,
        1.3632858339,
        1.3685490939,
        1.3585716979,
        1.3768337259,
        1.3706319369,
        1.3500452649
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.3686609003,
      "stddev": 0.016831106973282366,
      "median": 1.3673465394000002,
      "user": 1.3222692399999998,
      "system": 1.70244134,
      "min": 1.3491973129000001,
      "max": 1.4082791449,
      "times": [
        1.3771206199000001,
        1.4082791449,
        1.3641810239,
        1.3726808789,
        1.3724916049,
        1.3661226469,
        1.3685704319,
        1.3491973129000001,
        1.3494375399,
        1.3585277989
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.4610220851,
      "stddev": 0.07216512991376386,
      "median": 1.4385797904,
      "user": 0.56362874,
      "system": 1.59192224,
      "min": 1.4221953069,
      "max": 1.6639496349,
      "times": [
        1.4509993059000001,
        1.6639496349,
        1.4282838639,
        1.4221953069,
        1.4352677049,
        1.4453398429,
        1.4314220629,
        1.4418918759,
        1.4591044769000001,
        1.4317667759000001
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.4366768639,
      "stddev": 0.024171778523134048,
      "median": 1.4438008369,
      "user": 0.5766929399999999,
      "system": 1.5504397399999998,
      "min": 1.3981837289,
      "max": 1.4761100129,
      "times": [
        1.4761100129,
        1.4208644189000001,
        1.4419398129,
        1.4498331279,
        1.4024666629,
        1.4288423389,
        1.3981837289,
        1.4456618609,
        1.4548248749000001,
        1.4480417999000001
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 3.049 ± 0.049 3.001 3.135 2.13 ± 0.08
pacquet@main 3.040 ± 0.047 2.989 3.139 2.13 ± 0.08
pnpr@HEAD 1.453 ± 0.027 1.425 1.507 1.02 ± 0.04
pnpr@main 1.429 ± 0.046 1.389 1.553 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 3.0494062026999997,
      "stddev": 0.04862003580951334,
      "median": 3.0371227259999998,
      "user": 1.7732939399999996,
      "system": 1.9704771399999998,
      "min": 3.001225081,
      "max": 3.134519496,
      "times": [
        3.006899649,
        3.040473009,
        3.112757655,
        3.047490391,
        3.033772443,
        3.097979085,
        3.001225081,
        3.134519496,
        3.011989423,
        3.006955795
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 3.0398382069,
      "stddev": 0.04740799736199791,
      "median": 3.0270353425,
      "user": 1.7674377399999996,
      "system": 1.97728084,
      "min": 2.98907327,
      "max": 3.138654822,
      "times": [
        3.030161526,
        3.032346975,
        3.015911154,
        3.023909159,
        2.996254473,
        3.0167363,
        3.049254505,
        3.138654822,
        2.98907327,
        3.106079885
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.4531124328999998,
      "stddev": 0.02650562326663806,
      "median": 1.4417822285000002,
      "user": 0.57517434,
      "system": 1.57055834,
      "min": 1.424611968,
      "max": 1.507418483,
      "times": [
        1.474254967,
        1.48475814,
        1.445018208,
        1.507418483,
        1.424611968,
        1.436925127,
        1.438546249,
        1.445387982,
        1.437798702,
        1.4364045029999999
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.4293075433999998,
      "stddev": 0.045762039460993095,
      "median": 1.414463779,
      "user": 0.5644218400000002,
      "system": 1.5392365399999999,
      "min": 1.3887011550000001,
      "max": 1.553228785,
      "times": [
        1.432027544,
        1.553228785,
        1.441889004,
        1.416248458,
        1.417353758,
        1.408681377,
        1.4126791,
        1.3887011550000001,
        1.411601326,
        1.410664927
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12568
Testbedpacquet
Click to view all benchmark results
BenchmarkLatencyBenchmark Result
milliseconds (ms)
(Result Δ%)
Upper Boundary
milliseconds (ms)
(Limit %)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
🚷 view threshold
4,844.24 ms
(+1.76%)Baseline: 4,760.61 ms
5,712.73 ms
(84.80%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
3,049.41 ms
(+0.10%)Baseline: 3,046.48 ms
3,655.78 ms
(83.41%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
1,362.04 ms
(+0.25%)Baseline: 1,358.63 ms
1,630.35 ms
(83.54%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
4,934.20 ms
(+1.96%)Baseline: 4,839.27 ms
5,807.13 ms
(84.97%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
657.79 ms
(+0.28%)Baseline: 655.96 ms
787.15 ms
(83.57%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12568
Testbedpnpr

⚠️ WARNING: No Threshold found!

Without a Threshold, no Alerts will ever be generated.

Click here to create a new Threshold
For more information, see the Threshold documentation.
To only post results if a Threshold exists, set the --ci-only-thresholds flag.

Click to view all benchmark results
BenchmarkLatencymilliseconds (ms)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
3,217.83 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,453.11 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,461.02 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
2,977.60 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
722.36 ms
🐰 View full continuous benchmarking report in Bencher

@KSXGitHub
KSXGitHub marked this pull request as ready for review June 27, 2026 11:44
@KSXGitHub
KSXGitHub requested a review from zkochan as a code owner June 27, 2026 11:44
@zkochan
zkochan force-pushed the claude/magical-shannon-cnmpl6 branch from 58c83dd to 1b0f9d8 Compare June 27, 2026 13:09
@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 (4) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Unsafe auth.ini rewrite ✓ Resolved 🐞 Bug ⛨ Security
Description
logout() rewrites auth.ini via std::fs::write semantics (truncate-then-write), which is
non-atomic and can leave auth.ini corrupted/empty on crash or I/O failure. Because the write
follows symlinks, a symlinked auth.ini can redirect the overwrite to an unintended target path
(dangerous if the process runs with elevated privileges).
Code

pacquet/crates/auth-commands/src/logout.rs[R180-182]

+    if settings.remove(&token_key) {
+        Sys::write(&config_path, settings.serialize().as_bytes())
+            .map_err(|error| LogoutError::WriteAuthIni { path: config_path.clone(), error })?;
Evidence
logout() writes the updated INI contents via Sys::write(...), and the production Host provider
implements that as std::fs::write, which is a non-atomic truncate+write and follows symlinks.
Elsewhere in the repo, INI files containing auth material are written with an atomic
temp-file+rename approach with explicit permission/symlink considerations, indicating this path
should be hardened similarly.

pacquet/crates/auth-commands/src/logout.rs[39-43]
pacquet/crates/auth-commands/src/logout.rs[79-83]
pacquet/crates/auth-commands/src/logout.rs[177-183]
pacquet/crates/cli/src/cli_args/config/ini.rs[41-80]

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 logout` rewrites `auth.ini` using `std::fs::write` semantics via the `FsWrite` capability. This is (1) non-atomic (truncate + write), risking credential-file corruption on partial write/crash, and (2) follows symlinks, allowing the write to be redirected if `auth.ini` is a symlink.
### Issue Context
This repo already treats INI files that may contain credentials as requiring an atomic temp-file + rename write and explicitly considers symlink + permissions behavior (see the existing `pnpm config` ini writer).
### Fix Focus Areas
- pacquet/crates/auth-commands/src/logout.rs[39-43]
- pacquet/crates/auth-commands/src/logout.rs[79-83]
- pacquet/crates/auth-commands/src/logout.rs[177-183]
- pacquet/crates/cli/src/cli_args/config/ini.rs[41-80]
### Suggested implementation approach
- Change the production `Host` implementation of `FsWrite::write` to perform an atomic write (write to a sibling temp file, `fsync` if desired, then rename over the target).
- Ensure the implementation is symlink-safe (do not follow a symlinked target; replace the symlink dirent rather than truncating its destination).
- Preserve existing file permissions when overwriting an existing regular file (so rewriting doesn’t accidentally tighten/loosen modes).
- Optionally: rename `FsWrite` to reflect stronger guarantees (e.g. `FsWriteAtomic`) to prevent future providers from reintroducing unsafe semantics.
(You can largely mirror the strategy already used in `pacquet/crates/cli/src/cli_args/config/ini.rs::write`.)

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


2. Registry URL not sanitized ✓ Resolved 🐞 Bug ⛨ Security
Description
logout() and LogoutError interpolate the raw registry URL into stdout, warnings, and error
messages without redacting inline user:pass@ credentials or stripping control characters, which
can leak credentials into CI logs and enable terminal escape injection from a repo-controlled
.npmrc. Other registry commands in this repo explicitly redact/sanitize for this reason, so
logout is a regression in log safety.
Code

pacquet/crates/auth-commands/src/logout.rs[R134-185]

+    let registry = normalize_registry_url(opts.registry.unwrap_or(DEFAULT_REGISTRY));
+    let registry_config_key = nerf_dart(&registry);
+    let token_key = format!("{registry_config_key}:_authToken");
+
+    let Some(token) = opts.auth_config.get(&token_key) else {
+        return Err(LogoutError::NotLoggedIn { registry });
+    };
+
+    let revoke_url = format!("{registry}-/user/token/{}", encode_uri_component(token));
+    let revoked = match Sys::revoke(http_client, &revoke_url, token, opts.retry).await {
+        RevokeOutcome::Revoked => true,
+        RevokeOutcome::Rejected { status } => {
+            global::<Reporter>(
+                opts.prefix,
+                LogLevel::Info,
+                format!("Registry returned HTTP {status} when revoking token"),
+            );
+            false
+        }
+        RevokeOutcome::Unreachable => {
+            global::<Reporter>(
+                opts.prefix,
+                LogLevel::Info,
+                "Could not reach the registry to revoke the token".to_string(),
+            );
+            false
+        }
+    };
+
+    let config_path = opts.config_dir.join("auth.ini");
+    let mut settings = safe_read_ini::<Sys>(&config_path)?;
+
+    if settings.remove(&token_key) {
+        Sys::write(&config_path, settings.serialize().as_bytes())
+            .map_err(|error| LogoutError::WriteAuthIni { path: config_path.clone(), error })?;
+    } else if revoked {
+        global::<Reporter>(
+            opts.prefix,
+            LogLevel::Warn,
+            format!(
+                "The auth token for {registry} was not found in {}. \
+                 It may be configured in .npmrc or another config file. \
+                 The token was revoked on the registry but must be removed manually from that config file.",
+                config_path.display(),
+            ),
+        );
+    } else {
+        return Err(LogoutError::LogoutFailed { registry, config_path });
+    }
+
+    Ok(format!("Logged out of {registry}"))
+}
Evidence
logout currently echoes the registry URL directly in success/warn/error paths, while other
commands in this repo treat registry URLs as untrusted output and redact/sanitize them to prevent
credential leaks and terminal injection.

pacquet/crates/auth-commands/src/logout.rs[134-185]
pacquet/crates/auth-commands/src/logout.rs[230-247]
pacquet/crates/cli/src/cli_args/logout.rs[73-88]
pacquet/crates/cli/src/cli_args/ping.rs[70-88]
pacquet/crates/cli/src/cli_args/whoami.rs[65-74]

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

## Issue description
`logout` prints the registry URL (from `--registry` or `Config.registry`) verbatim in:
- success output (`Logged out of {registry}`),
- warnings (`The auth token for {registry}...`),
- user-facing errors (`Not logged in to {registry}...`, `Failed to log out of {registry}...`).
Registry URLs are attacker-influenced via repo-controlled `.npmrc` and can include inline credentials (`https://user:pass@host/`) or control characters (escape sequences, `\r`, `\n`) that must not reach stderr/CI logs.
### Issue Context
The repo already has an established pattern for this: `ping` uses `redact_url_credentials` + strips control characters before printing; `whoami` avoids including the URL in diagnostic context specifically to avoid leaking inline credentials.
### Fix Focus Areas
- pacquet/crates/auth-commands/src/logout.rs[134-185]
- pacquet/crates/auth-commands/src/logout.rs[235-247]
### Suggested fix
1. Keep two forms of the registry string:
- `registry_raw`: used for `nerf_dart`, token lookup, and building the revoke request URL.
- `registry_display`: used **only** for messages/logs/errors.
2. Implement a small helper (either local to `logout.rs` or shared in a util module) equivalent to `ping`:
- redact inline URL credentials (`pacquet_network::redact_url_credentials`)
- strip control characters (`chars().filter(|c| !c.is_control())`)
3. Use `registry_display` everywhere user-visible:
- `Ok(format!("Logged out of {registry_display}"))`
- warnings via `global::<Reporter>(..., format!("... {registry_display} ..."))`
- store `registry_display` inside `LogoutError::{NotLoggedIn,LogoutFailed}` so `Display` never prints secrets/escapes.
(Do not change the request behavior; only change formatting/logging.)

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


3. Token leaked via retry logs ✓ Resolved 🐞 Bug ⛨ Security
Description
Host::revoke passes the full revoke URL (which includes the auth token in the path) into
send_with_retry; on retryable failures send_with_retry emits tracing::warn! logs containing
that URL, leaking the token into logs/traces. This can expose registry tokens whenever revocation
hits a transient transport error or retryable HTTP status and fetch_retries > 0.
Code

pacquet/crates/auth-commands/src/logout.rs[R90-93]

+        let authorization = format!("Bearer {token}");
+        match send_with_retry(http_client, revoke_url, retry, |client| {
+            client.delete(revoke_url).header(reqwest::header::AUTHORIZATION, authorization.as_str())
+        })
Evidence
Host::revoke passes revoke_url (token-in-path) as the url argument to send_with_retry.
send_with_retry logs url = %redact_url_credentials(url) on retryable responses/transport errors;
this redaction only strips URL credentials (userinfo) and leaves the path intact, so the token
remains in the logged URL.

pacquet/crates/auth-commands/src/logout.rs[83-101]
pacquet/crates/network/src/retry.rs[127-173]

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

## Issue description
`Host::revoke` calls `send_with_retry(http_client, revoke_url, ...)` where `revoke_url` is `.../-/user/token/<token>`. The shared retry helper logs the `url` parameter on retries, and its current redaction only removes URL userinfo, not path segments—so the token ends up in logs.
### Issue Context
This is specific to `logout` because the token is part of the URL path (by npm API design). The fix should ensure the value passed as `send_with_retry`'s `url` argument never contains the token, while still sending the request to the full revoke URL.
### Fix Focus Areas
- pacquet/crates/auth-commands/src/logout.rs[83-103]
- pacquet/crates/network/src/retry.rs[127-173]
### Suggested implementation direction
In `Host::revoke`, compute a log/routing URL that does not include the token (e.g. strip the final path segment from `revoke_url`, or pass the registry base URL), and pass *that* to `send_with_retry` as its `url` argument, while continuing to build the request with `client.delete(revoke_url)`.
Example sketch:
- `let safe_url = revoke_url.rsplit_once('/').map(|(base, _)| base).unwrap_or(revoke_url);`
- `send_with_retry(http_client, safe_url, retry, |client| client.delete(revoke_url).header(...))`
This keeps retries/routing behavior but prevents token disclosure in retry logs.

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



Remediation recommended

4. Atomic write missing rename-retry 🐞 Bug ☼ Reliability
Description
pacquet_fs::write_atomic persists via a single rename without the Windows transient-rename retry
loop that pacquet already uses to handle Defender/indexer locks, so writes to auth.ini and other
INI files can intermittently fail on Windows. This can break logout’s local token removal (or
other config writes) even though the operation is otherwise correct.
Code

pacquet/crates/fs/src/write_atomic.rs[R19-44]

+pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
+    let dir = path.parent().filter(|parent| !parent.as_os_str().is_empty());
+    if let Some(parent) = dir {
+        fs::create_dir_all(parent)?;
+    }
+    let mut tmp = tempfile::NamedTempFile::new_in(dir.unwrap_or_else(|| Path::new(".")))?;
+    tmp.write_all(bytes)?;
+    tmp.as_file().sync_all()?;
+    // `NamedTempFile` creates with mode 0600 on Unix; persisting it over an
+    // existing regular file would silently tighten that file's permissions, so
+    // carry the target's mode across the rename to preserve it.
+    //
+    // `symlink_metadata` (not `metadata`) so a symlinked target is detected
+    // rather than followed: the rename replaces the symlink with a fresh
+    // regular file, and copying the link target's (possibly 0644) mode would
+    // loosen permissions on freshly written credentials. A symlink keeps 0600.
+    #[cfg(unix)]
+    if let Ok(metadata) = fs::symlink_metadata(path)
+        && !metadata.file_type().is_symlink()
+    {
+        use std::os::unix::fs::PermissionsExt as _;
+        let mode = metadata.permissions().mode();
+        tmp.as_file().set_permissions(std::fs::Permissions::from_mode(mode))?;
+    }
+    tmp.persist(path).map_err(|err| err.error)?;
+    Ok(())
Evidence
The new shared atomic writer performs a single persist/rename with no retry logic, while existing
pacquet atomic writers explicitly implement rename retries because Windows Defender/indexers cause
transient rename failures in practice; logout relies on this new helper to rewrite auth.ini, so
it inherits the non-retrying behavior.

pacquet/crates/fs/src/write_atomic.rs[19-44]
pacquet/crates/fs/src/ensure_file.rs[456-498]
pacquet/crates/fs/src/ensure_file.rs[420-427]
pacquet/crates/auth-commands/src/logout.rs[80-83]

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_fs::write_atomic()` uses `NamedTempFile::persist()` (single rename) but does not implement the Windows transient rename retry behavior that pacquet already codifies elsewhere to handle Windows Defender / indexer interference. This can cause intermittent failures when rewriting credential/config files (notably `auth.ini` during `logout`).
## Issue Context
The repo already has a dedicated `rename_with_retry()` implementation (with explicit rationale) used by other atomic writers to tolerate transient `PermissionDenied`/`ResourceBusy` errors on Windows.
## Fix Focus Areas
- pacquet/crates/fs/src/write_atomic.rs[19-44]
- pacquet/crates/fs/src/ensure_file.rs[456-498]
- pacquet/crates/auth-commands/src/logout.rs[80-83]
## What to change
- Rework `pacquet_fs::write_atomic()` to perform the rename step via a retry loop on Windows similar to `ensure_file::rename_with_retry`.
- Option A (preferred for consistency): factor a shared `rename_with_retry` helper into `pacquet-fs` (e.g., a small internal module) and reuse it from both `ensure_file` and `write_atomic`.
- Option B: duplicate the minimal retry loop inside `write_atomic.rs` (guarded by `cfg(windows)`), mirroring the same retry budget/backoff policy.
- Ensure the final rename is performed by your retrying rename function (not by `NamedTempFile::persist()` directly), so the retry loop actually applies to the destination replacement.
## Acceptance criteria
- On Windows, transient rename failures during atomic writes are retried with bounded backoff/budget, matching the behavior documented in `ensure_file.rs`.
- `logout`’s `auth.ini` rewrite continues to be atomic and symlink-safe, but is now resilient to Windows AV/indexer rename races.

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


5. Query breaks revoke URL 🐞 Bug ≡ Correctness
Description
logout() builds the revoke endpoint via string concatenation ("{registry}-/user/token/...")
after only appending a trailing slash. If the registry string contains a ?query or #fragment
(possible via .npmrc/--registry), the constructed URL won’t target /-/user/token/, so the
token may not be revoked even though auth.ini is updated.
Code

pacquet/crates/auth-commands/src/logout.rs[R142-158]

+    let registry = normalize_registry_url(opts.registry.unwrap_or(DEFAULT_REGISTRY));
+    let registry_config_key = nerf_dart(&registry);
+    let token_key = format!("{registry_config_key}:_authToken");
+
+    // `registry` (raw) is used for the token-key lookup and the revoke URL;
+    // `registry_display` is the only form that reaches stdout, warnings, and
+    // errors. A registry from an untrusted `.npmrc` / `--registry` can embed
+    // `user:pass@` credentials or terminal escape sequences, so redact and
+    // sanitize before it is ever shown. Mirrors `pacquet ping`.
+    let registry_display = redact_and_sanitize(&registry);
+
+    let Some(token) = opts.auth_config.get(&token_key) else {
+        return Err(LogoutError::NotLoggedIn { registry: registry_display });
+    };
+
+    let revoke_url = format!("{registry}-/user/token/{}", encode_uri_component(token));
+    let revoked = match Sys::revoke(http_client, &revoke_url, token, opts.retry).await {
Evidence
The revoke URL is built by concatenating registry and - /user/token/..., and
normalize_registry_url only appends a trailing slash; this makes the revoke URL sensitive to
?/# in the registry string. The test suite itself passes a registry containing a query string,
demonstrating such input is considered plausible and should behave correctly.

pacquet/crates/auth-commands/src/logout.rs[142-158]
pacquet/crates/auth-commands/src/logout.rs[216-220]
pacquet/crates/auth-commands/src/logout/tests.rs[711-728]

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

## Issue description
`logout()` constructs `revoke_url` by concatenating a raw `registry` string with `- /user/token/...`. If `registry` includes a query (`?…`) or fragment (`#…`), the revoke path is appended after those components, producing a URL that does not address the intended npm revocation endpoint.
### Issue Context
This is especially relevant because registry values are treated as attacker-influenced in this PR (sanitization/redaction tests explicitly cover a registry containing a query string).
### Fix Focus Areas
- Update registry normalization to drop `?query` and `#fragment` before both `nerf_dart()` and `revoke_url` construction.
- pacquet/crates/auth-commands/src/logout.rs[142-158]
- pacquet/crates/auth-commands/src/logout.rs[216-220]
Suggested implementation approach:
- In `normalize_registry_url`, strip any `?…` / `#…` suffix (e.g., split on `['?', '#']` and keep the first part), then ensure exactly one trailing `/`.
- Keep the existing `redact_and_sanitize` for display output; the key change is ensuring the request URL is built from a registry base without query/fragment.

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


6. Retry logs allow escapes 🐞 Bug ⛨ Security
Description
send_with_retry() logs url and error using redact_url_credentials(), which does not strip
control characters, so an attacker-controlled registry URL (from .npmrc/--registry) can inject
newlines/terminal escapes into tracing retry logs. This undermines the PR’s new sanitization
guarantees and can corrupt CI logs or terminal output when retries occur.
Code

pacquet/crates/network/src/retry.rs[R160-168]

+                // reqwest embeds the full request URL in its error, which can
+                // carry a secret in the path (e.g. `logout`'s revoke token).
+                // The `url=` field already logs the URL the caller handed us
+                // (token-free for such callers), so drop the URL from the
+                // error to keep it out of the log.
+                let error = error.without_url();
        tracing::warn!(
            target: "pacquet_network::retry",
            url = %redact_url_credentials(url),
Evidence
send_with_retry() logs the retry URL/error without stripping control characters, while the repo
explicitly documents that registry URLs may include terminal escape sequences from untrusted
.npmrc/--registry and introduces redact_and_sanitize() to mitigate that exact class of issue.

pacquet/crates/network/src/retry.rs[144-174]
pacquet/crates/network/src/auth.rs[483-493]
pacquet/crates/auth-commands/src/logout.rs[145-149]

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

## Issue description
`send_with_retry()`’s retry `tracing::warn!` logs still emit attacker-controlled control characters because they format/log the URL and error using `redact_url_credentials()` (credentials-only redaction). This enables log forging / terminal escape injection if an untrusted `.npmrc` or `--registry` includes `\r`, `\n`, or ANSI escapes, and a retry path is hit.
### Issue Context
A new helper `pacquet_network::redact_and_sanitize()` was added specifically to strip control characters (and is already used in `logout` for user-visible output). The retry logger should apply the same policy.
### Fix Focus Areas
- pacquet/crates/network/src/retry.rs[140-174]
- Replace `redact_url_credentials(url)` with `redact_and_sanitize(url)` in both retry warn branches (status-retry and error-retry).
- Also sanitize the formatted error string (`format!("{error:?}")`) with `redact_and_sanitize(...)` before logging.
- Prefer precomputing `let url_display = redact_and_sanitize(url);` etc. to keep the macro call readable.

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


View more (1)
7. LogoutFailed hides failure reason 🐞 Bug ◔ Observability
Description
On the path where token revocation is unreachable/rejected and the token is not present in
auth.ini, logout() returns LogoutError::LogoutFailed whose message hard-codes “registry
rejected the token revocation request” even when the actual outcome was “could not reach the
registry”. This yields misleading error output and complicates debugging/automation.
Code

pacquet/crates/auth-commands/src/logout.rs[R239-247]

+    #[display(
+        "Failed to log out of {registry}. The registry rejected the token revocation request, \
+         and the token was not found in {}. \
+         The token may be configured in .npmrc or another config file \
+         and must be removed manually, and may still need to be revoked on the registry.",
+        config_path.display()
+    )]
+    #[diagnostic(code(ERR_PNPM_LOGOUT_FAILED))]
+    LogoutFailed { registry: String, config_path: PathBuf },
Evidence
logout() logs an explicit unreachable message but still funnels the error into LogoutFailed,
whose Display text always says “rejected”, regardless of whether the failure was transport-level
or HTTP-level.

pacquet/crates/auth-commands/src/logout.rs[142-182]
pacquet/crates/auth-commands/src/logout.rs[239-247]

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

## Issue description
`LogoutError::LogoutFailed`’s `Display` claims the registry rejected the token revocation request, but the code can reach this error after logging an unreachable/transport failure.
This happens specifically when:
- `Sys::revoke(...)` returns `RevokeOutcome::Unreachable` (or `Rejected`), and
- the token key is not found in `auth.ini` (so there is no local token to remove).
### Issue Context
In this scenario, the current output can contain both:
- an Info log: "Could not reach the registry to revoke the token"
- an error: "The registry rejected the token revocation request"
### Fix Focus Areas
- pacquet/crates/auth-commands/src/logout.rs[142-182]
- pacquet/crates/auth-commands/src/logout.rs[239-247]
### Suggested fix
Option A (minimal): reword `LogoutFailed` to not assert rejection (e.g. "Failed to revoke the token on the registry...") and avoid contradicting the earlier log.
Option B (better): include the revocation failure reason in the error variant:
- Add a small enum like `RevocationFailure { Rejected(u16), Unreachable }`
- Store it in `LogoutFailed { ..., failure: RevocationFailure }`
- Format the message accordingly (include status for rejected; say unreachable for transport).
Keep the existing error code `ERR_PNPM_LOGOUT_FAILED`.

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


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 1b0f9d8

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

Copy link
Copy Markdown

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

@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/auth-commands/src/logout/tests.rs`:
- Around line 713-729: The logout success/warn test only checks credential
redaction, so it misses control-character sanitization regressions. Update the
test around logout::<Sys, Rep> to include a registry string with terminal
escape/control characters and assert the returned success message and
warns(&EVENTS) output strip them while still preserving the host, using the
existing logout flow and warning capture logic.
- Around line 739-762: The unreachable-endpoint test in Host::revoke is flaky
because it relies on 127.0.0.1:1 being closed; replace that assumption with a
deterministic setup by binding a TcpListener on localhost to reserve an
ephemeral port, dropping it, then building revoke_url from that released port so
the retry path always hits ECONNREFUSED. Keep the existing assertions around
RevokeOutcome::Unreachable and the warning log/token redaction in the same test.
🪄 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: dc957ac9-b29e-44cb-85ec-1194bf1b8826

📥 Commits

Reviewing files that changed from the base of the PR and between 1b0f9d8 and b9ea70d.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (8)
  • pacquet/crates/auth-commands/Cargo.toml
  • pacquet/crates/auth-commands/src/logout.rs
  • pacquet/crates/auth-commands/src/logout/tests.rs
  • pacquet/crates/cli/src/cli_args/ping.rs
  • pacquet/crates/network/src/auth.rs
  • pacquet/crates/network/src/auth/tests.rs
  • pacquet/crates/network/src/lib.rs
  • pacquet/crates/network/src/retry.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • pacquet/crates/auth-commands/Cargo.toml
  • pacquet/crates/auth-commands/src/logout.rs

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

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 076e2c9

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 076e2c9

claude added 4 commits June 27, 2026 17:18
Port the `pnpm logout` command (`@pnpm/auth.commands`,
`pnpm11/auth/commands/src/logout.ts`) into a new `pacquet-auth-commands`
crate, wired into the CLI as `pacquet logout`.

The command revokes the registry auth token on the server and removes it
from `auth.ini`, warning when the token lives in `.npmrc` (which pnpm does
not own) and failing only when the revocation is rejected and there is no
local token left to remove.

Upstream injects its side effects (`fetch`, `readIniFile`, `writeIniFile`,
`globalInfo`, `globalWarn`) through a `LogoutContext` object of functions.
This port uses pacquet's capability-trait seam instead: `FsReadToString`,
`FsWrite`, and `RevokeToken` are `Sys`-bound capabilities with no `&self`
receiver (production provider `Host`, test fakes are unit structs), and the
two `global*` channels are emitted through the `R: Reporter` seam. All 13
upstream tests translate to unit tests of the ported function.

`Config` previously baked auth credentials into ready-to-send
`Authorization` headers and discarded the raw token. Expose
`Config::auth_tokens_by_uri` (raw `_authToken` per nerf-darted registry URI)
and `Config::config_dir` so the command can read the token back to revoke it
and locate `auth.ini`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TkqTxuagHe8nJrJveucDpy
…rror path

The Dylint CI job (perfectionist) rejected the logout port:

- `single-letter-generic`: rename the `R` reporter generic to `Reporter`
  (bound `self::Reporter`) in `logout`, the `global` helper, and
  `LogoutArgs::run`, matching the existing `<Reporter: self::Reporter>`
  convention used across the cli, package-manager, and env-installer crates.
- `macro-trailing-comma`: add the missing trailing comma to the multi-line
  `format!` and to the two multi-line `sys_fake!` invocations.

Also address review feedback:

- Order module declarations `pub mod` before private `mod` per
  `CODE_STYLE_GUIDE.md`.
- Add `propagates_auth_ini_write_errors`, locking down the `WriteAuthIni`
  branch (a hand-written fake whose `FsWrite::write` fails, since
  `sys_fake!`'s write always succeeds).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TkqTxuagHe8nJrJveucDpy
The unit suite exercises `logout` through the `Sys`/`Reporter` DI seam,
which swaps in fakes for the filesystem and network — so the production
`Host` provider and the CLI adapter had no test coverage. Add real-fixture
tests for those paths, per the "prefer real fixtures" rule in the pacquet
guide:

- `auth-commands` `logout/tests.rs`: three `Host` tests driving the real
  filesystem (`tempfile::TempDir`) and a real `DELETE` over the HTTP stack
  (`mockito`) — revoke-success, registry-rejects, and unreachable.
- `cli/tests/logout.rs`: spawn the `pacquet logout` binary against a
  `mockito` registry with a temp `XDG_CONFIG_HOME`/`auth.ini`, covering
  `LogoutArgs::run` and the reporter dispatch end-to-end, plus the
  not-logged-in error exit.
- `config` `npmrc_auth` test: assert the default-registry `_authToken`
  lands in `Config::auth_tokens_by_uri`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TkqTxuagHe8nJrJveucDpy
Two defensive branches stayed uncovered after the integration tests
because the full pipelines never reach them:

- `NpmrcAuth::build_auth_headers`'s default-credentials branch keys an
  unrescoped default token to the registry URI, but `Config::current`
  (and the `apply_to` test helper) rescope default creds onto a per-URI
  key first. Add a direct `build_auth_headers` unit test that exercises
  the branch.
- `LogoutArgs::run`'s missing-config-dir guard can't be hit through the
  binary (a home dir always resolves), so add a unit test that calls
  `run` with a `Config` whose `config_dir` is `None` and asserts the
  error.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TkqTxuagHe8nJrJveucDpy
claude and others added 6 commits June 27, 2026 17:18
The logout doc comments linked upstream `@pnpm/auth.commands` via branch
URLs (blob/main, tree/main), which drift as main moves. Pin them to the
commit that currently holds pnpm11/auth/commands, per the pacquet AGENTS
rule requiring commit-SHA permalinks over branch links.
Replace the ad-hoc `miette::miette!(code = ...)` in the logout CLI
adapter with a `LogoutCliError::NoConfigDir` typed diagnostic, matching
the codebase convention of a local `#[derive(Diagnostic)]` enum carrying
the `ERR_PNPM_NO_CONFIG_DIR` code (as in completion.rs / config.rs)
rather than a string-coded inline error.
Fix a broken sentence in the logout module doc, and drop three host_*
test doc comments that only restated the test name, per the comment
styleguide (a test doc comment should add the non-obvious why, not
re-narrate what the name and assertions already say).
…tials

Two security fixes for `pacquet logout`, both flagged on the PR.

The revoke URL carries the auth token in its path (npm's
DELETE -/user/token/<token> API). `send_with_retry` logs the URL it is
handed and the reqwest error (which embeds the request URL), so a
retryable failure with fetch-retries > 0 wrote the token to the retry
logs. `Host::revoke` now passes the token-free URL prefix for
routing/logging, and `send_with_retry` strips the URL from the logged
error via `Error::without_url`.

`logout` also printed the registry URL verbatim in its success line,
warnings, and errors. A registry from an untrusted `.npmrc` /
`--registry` can embed `user:pass@` credentials or terminal escape
sequences, so it is now redacted and control-stripped before display,
matching `pacquet ping`. The shared `redact_and_sanitize` helper moves
to `pacquet-network` so `ping` and `logout` share one implementation.

Adds regression tests, including a tracing-capture test asserting the
token never reaches the retry logs.
`pnpm logout` rewrote auth.ini with `std::fs::write` (truncate-then-write):
non-atomic, so a crash or I/O error mid-write could corrupt the credential
file and drop other tokens, and symlink-following, so a symlinked auth.ini
could redirect the overwrite to another path.

Extract the atomic, symlink-safe, mode-preserving write the `pnpm config`
ini writer already performed into a shared `pacquet_fs::write_atomic`, and
use it from both that writer and logout's `Host::write`. Mirrors pnpm's
write-ini-file.
Cover control-character sanitization on logout's success/warning output
(not only credential redaction), and make the connection-refused tests
deterministic by binding then dropping an ephemeral local port instead of
assuming a fixed low port is closed.
@zkochan
zkochan force-pushed the claude/magical-shannon-cnmpl6 branch from 076e2c9 to d119959 Compare June 27, 2026 15:25
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown

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

@zkochan
zkochan merged commit 66c531e into main Jun 27, 2026
30 checks passed
@zkochan
zkochan deleted the claude/magical-shannon-cnmpl6 branch June 27, 2026 15:46
@coderabbitai coderabbitai Bot mentioned this pull request Jun 29, 2026
4 tasks done
@coderabbitai coderabbitai Bot mentioned this pull request Jul 10, 2026
3 tasks done
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 state: automerge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants