Skip to content

feat(pacquet): pack - #12567

Merged
zkochan merged 18 commits into
mainfrom
claude/friendly-galileo-aotu46
Jun 25, 2026
Merged

zkochan merged 18 commits into
mainfrom
claude/friendly-galileo-aotu46

Conversation

@KSXGitHub

@KSXGitHub KSXGitHub commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features
    • Added a pack command to generate publishable tarballs from a project, including recursive workspace packing.
    • Added dry-run, JSON output, output-path templating, gzip level selection, and optional README embedding.
    • Introduced exportable/publish-ready manifest creation (obfuscation, workspace/catalog/jsr spec rewriting, and publishConfig hoisting).
  • Bug Fixes
    • Improved manifest normalization/validation and deterministic tarball generation/unpacked-size reporting.
    • Hardened main/bin handling to prevent path traversal and tightened file/symlink inclusion behavior.
    • Refined lifecycle/script execution and publishConfig.directory behavior.
  • Documentation
    • Expanded pack CLI documentation and options.
  • Tests
    • Added coverage for packing, manifest creation/transformation, output formatting, and traversal/symlink edge cases.

@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 pacquet pack, manifest rewrite logic, tarball generation, and CLI wiring. It also extracts packlist handling into pacquet_fs_packlist and updates git-fetcher to use the shared crate.

Changes

Packlist extraction

Layer / File(s) Summary
Standalone packlist crate
Cargo.toml, pacquet/crates/fs-packlist/Cargo.toml, pacquet/crates/fs-packlist/src/lib.rs
pacquet_fs_packlist defines the packlist crate metadata, local error type, path-containment checks, and updated tracing targets.
Git-fetcher rewire
pacquet/crates/git-fetcher/Cargo.toml, pacquet/crates/git-fetcher/src/error.rs, pacquet/crates/git-fetcher/src/fetcher.rs, pacquet/crates/git-fetcher/src/lib.rs, pacquet/crates/git-fetcher/src/tarball_fetcher.rs
git-fetcher now depends on pacquet_fs_packlist for packlist access and error propagation, with module exports and imports updated.

Packaging flow

Layer / File(s) Summary
Manifest rewrite pipeline
pacquet/crates/exportable-manifest/Cargo.toml, pacquet/crates/exportable-manifest/src/lib.rs, pacquet/crates/exportable-manifest/src/create.rs, pacquet/crates/exportable-manifest/src/create/tests.rs, pacquet/crates/exportable-manifest/src/transform.rs, pacquet/crates/exportable-manifest/src/transform/tests.rs
create_exportable_manifest rewrites dependency specifiers, hoists publishConfig keys, embeds README.md when requested, and finishes with manifest normalization.
Pack API and archive writer
pacquet/crates/pack/Cargo.toml, pacquet/crates/pack/src/capabilities.rs, pacquet/crates/pack/src/lib.rs, pacquet/crates/pack/src/manifest_entry.rs, pacquet/crates/pack/src/tarball.rs
pacquet-pack defines pack options, tarball generation, packlist handling, size calculation, output formatting, and supporting helpers.
Pack API tests
pacquet/crates/pack/src/tests.rs
The pack tests cover packing output, validation, dry-run behavior, bundling, lifecycle scripts, workspace LICENSE injection, and formatting.
Recursive pack command
pacquet/crates/cli/src/cli_args/pack.rs, pacquet/crates/cli/src/cli_args.rs
PackArgs runs single-package and recursive workspace packing, resolves output destinations, and bridges CLI/config values into pacquet_pack.
CLI surface and docs
pacquet/crates/cli/Cargo.toml, pacquet/crates/cli/README.md, pacquet/crates/cli/src/cli_args.rs
The CLI adds the pack subcommand, dependencies, and user-facing documentation for the new flags and recursive behavior.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~90+ minutes

Possibly related PRs

  • pnpm/pnpm#11708: Both PRs touch pacquet/crates/cli/src/cli_args.rs, with the main PR adding the CliCommand::Pack dispatch in CliArgs::run while the retrieved PR refactors CliArgs::run’s config/DI wiring to use Host/Sys, so they’re connected at the same CLI run/config code level.

Suggested reviewers

  • zkochan
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/friendly-galileo-aotu46

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.01      6.9±0.24ms   629.7 KB/sec    1.00      6.8±0.22ms   637.8 KB/sec

@codecov-commenter

codecov-commenter commented Jun 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 78.64865% with 158 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.91%. Comparing base (32d4d3f) to head (a5fce12).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
pacquet/crates/cli/src/cli_args/pack.rs 0.00% 107 Missing ⚠️
pacquet/crates/pack/src/lib.rs 92.02% 28 Missing ⚠️
pacquet/crates/cli/src/cli_args.rs 0.00% 9 Missing ⚠️
pacquet/crates/exportable-manifest/src/create.rs 93.43% 9 Missing ⚠️
...acquet/crates/exportable-manifest/src/transform.rs 93.75% 4 Missing ⚠️
pacquet/crates/fs-packlist/src/lib.rs 94.11% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #12567      +/-   ##
==========================================
- Coverage   88.01%   87.91%   -0.11%     
==========================================
  Files         354      363       +9     
  Lines       52699    53909    +1210     
==========================================
+ Hits        46382    47393    +1011     
- Misses       6317     6516     +199     

☔ 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: e8ffde691823

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.818 ± 0.252 4.560 5.431 1.57 ± 0.10
pacquet@main 4.722 ± 0.175 4.577 5.104 1.54 ± 0.08
pnpr@HEAD 3.069 ± 0.100 2.971 3.249 1.00
pnpr@main 3.090 ± 0.151 2.916 3.282 1.01 ± 0.06
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.818283289759998,
      "stddev": 0.2524710998210471,
      "median": 4.76579017966,
      "user": 3.7977214399999992,
      "system": 3.5568199,
      "min": 4.559745267159999,
      "max": 5.43050208916,
      "times": [
        4.91031298416,
        5.43050208916,
        4.80255300516,
        4.85582813916,
        4.729027354159999,
        4.58724687616,
        4.9552739911599994,
        4.702555782159999,
        4.64978740916,
        4.559745267159999
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.721725602459999,
      "stddev": 0.1745581142928822,
      "median": 4.64299306266,
      "user": 3.8514385399999993,
      "system": 3.5460103000000003,
      "min": 4.57734702616,
      "max": 5.104182864159999,
      "times": [
        4.95595931116,
        4.59963846516,
        4.6588029961599995,
        4.6115044761599995,
        5.104182864159999,
        4.761759813159999,
        4.57734702616,
        4.62718312916,
        4.700340833159999,
        4.62053711016
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.0687110876600006,
      "stddev": 0.09998086385900747,
      "median": 3.03589146716,
      "user": 2.7258462399999996,
      "system": 3.083205,
      "min": 2.9705051831600002,
      "max": 3.24902882816,
      "times": [
        3.07206685016,
        3.23660530516,
        2.9705051831600002,
        3.0507673411600003,
        2.97169493616,
        3.0027161701600003,
        3.0946783781600002,
        3.24902882816,
        3.01803229116,
        3.02101559316
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.09028119006,
      "stddev": 0.15054331352460024,
      "median": 3.07037035416,
      "user": 2.76708944,
      "system": 3.0601330000000004,
      "min": 2.91587294816,
      "max": 3.28203773416,
      "times": [
        2.96203204516,
        3.28203773416,
        3.2668895511600002,
        2.91587294816,
        3.17320544016,
        2.92831813316,
        3.15773881916,
        2.98300188916,
        3.25571367116,
        2.97800166916
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 664.9 ± 18.2 640.8 694.6 1.00
pacquet@main 670.9 ± 45.4 638.6 793.0 1.01 ± 0.07
pnpr@HEAD 751.1 ± 69.0 681.9 938.0 1.13 ± 0.11
pnpr@main 732.9 ± 70.1 683.8 925.0 1.10 ± 0.11
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.66487958674,
      "stddev": 0.018152349959152877,
      "median": 0.66588089214,
      "user": 0.3833767,
      "system": 1.36246278,
      "min": 0.64081307964,
      "max": 0.69464667764,
      "times": [
        0.69464667764,
        0.66800607164,
        0.64651808464,
        0.64520700164,
        0.65725999364,
        0.66375571264,
        0.67039925164,
        0.68977533364,
        0.64081307964,
        0.67241466064
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.6708993666399998,
      "stddev": 0.04539854405966071,
      "median": 0.65373158514,
      "user": 0.38940830000000004,
      "system": 1.3524408799999998,
      "min": 0.63862211464,
      "max": 0.79303685764,
      "times": [
        0.64370856164,
        0.66803315564,
        0.64427693764,
        0.65301240664,
        0.63862211464,
        0.65413807064,
        0.68503113064,
        0.67580933164,
        0.65332509964,
        0.79303685764
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.7511101786400001,
      "stddev": 0.06896352521801143,
      "median": 0.73669386414,
      "user": 0.3974447,
      "system": 1.3879250799999996,
      "min": 0.68188245164,
      "max": 0.93801100864,
      "times": [
        0.68188245164,
        0.74271064464,
        0.74569452764,
        0.74532293364,
        0.71475241364,
        0.72874345164,
        0.72541453364,
        0.93801100864,
        0.75789273764,
        0.73067708364
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.7328957081399999,
      "stddev": 0.07013901672800892,
      "median": 0.7174527151400001,
      "user": 0.3950961,
      "system": 1.3791165799999998,
      "min": 0.68381628464,
      "max": 0.92500460364,
      "times": [
        0.68764707064,
        0.69631072764,
        0.72123697564,
        0.72095251364,
        0.70958695364,
        0.68381628464,
        0.71700862964,
        0.74949652164,
        0.71789680064,
        0.92500460364
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.780 ± 0.039 4.704 4.846 1.48 ± 0.04
pacquet@main 4.802 ± 0.038 4.757 4.892 1.49 ± 0.04
pnpr@HEAD 3.241 ± 0.130 3.119 3.568 1.00 ± 0.05
pnpr@main 3.232 ± 0.089 3.121 3.343 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.78044431292,
      "stddev": 0.039201069502306625,
      "median": 4.78254198392,
      "user": 3.8458849199999996,
      "system": 3.42796408,
      "min": 4.70414921442,
      "max": 4.84602145642,
      "times": [
        4.79985075142,
        4.81205634142,
        4.7499805974200004,
        4.76054995342,
        4.76203315542,
        4.70414921442,
        4.8047176914200005,
        4.78856232742,
        4.84602145642,
        4.77652164042
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.80207257792,
      "stddev": 0.037656878914231764,
      "median": 4.80427335192,
      "user": 3.8795756199999993,
      "system": 3.4531103799999996,
      "min": 4.7570559804200006,
      "max": 4.892432863420001,
      "times": [
        4.892432863420001,
        4.80402979742,
        4.78023500942,
        4.80499538142,
        4.80903769942,
        4.81319872542,
        4.7588142414200005,
        4.7570559804200006,
        4.79640917442,
        4.80451690642
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.2410603697200004,
      "stddev": 0.12954404801358707,
      "median": 3.2025156689200003,
      "user": 2.79017802,
      "system": 3.25479228,
      "min": 3.11870266842,
      "max": 3.56827472442,
      "times": [
        3.1723279104200004,
        3.28939335642,
        3.56827472442,
        3.26988702042,
        3.28158709342,
        3.2111211194200004,
        3.11870266842,
        3.19391021842,
        3.1717524064200004,
        3.13364717942
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.23196099292,
      "stddev": 0.08929612716736715,
      "median": 3.1986339919200004,
      "user": 2.8264762199999995,
      "system": 3.21722178,
      "min": 3.1214203144200003,
      "max": 3.3432513794200003,
      "times": [
        3.17675061742,
        3.3391513444200003,
        3.1214203144200003,
        3.3388743394200002,
        3.2104142934200004,
        3.2977154424200004,
        3.1228516514200004,
        3.18232685642,
        3.3432513794200003,
        3.1868536904200004
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.367 ± 0.017 1.328 1.385 1.02 ± 0.02
pacquet@main 1.344 ± 0.018 1.326 1.384 1.00
pnpr@HEAD 1.424 ± 0.039 1.395 1.522 1.06 ± 0.03
pnpr@main 1.447 ± 0.053 1.407 1.581 1.08 ± 0.04
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.3673306006999997,
      "stddev": 0.016687573512783962,
      "median": 1.3702102098,
      "user": 1.3235422399999999,
      "system": 1.7443512399999996,
      "min": 1.3284046903,
      "max": 1.3854058853,
      "times": [
        1.3630267573,
        1.3774155363,
        1.3592933723,
        1.3841557153,
        1.3770242073,
        1.3711488942999999,
        1.3284046903,
        1.3692715253,
        1.3581594232999998,
        1.3854058853
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.3444437686,
      "stddev": 0.018001705824036013,
      "median": 1.3383604808,
      "user": 1.31457064,
      "system": 1.7032926400000001,
      "min": 1.3259565673,
      "max": 1.3838776973,
      "times": [
        1.3317221822999998,
        1.3657705702999998,
        1.3525887303,
        1.3374840403,
        1.3838776973,
        1.3259565673,
        1.3392369213,
        1.3413146603,
        1.3337340763,
        1.3327522402999998
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.4237813761,
      "stddev": 0.03905546746864626,
      "median": 1.4072800138,
      "user": 0.58439804,
      "system": 1.57617684,
      "min": 1.3950719542999999,
      "max": 1.5221062313,
      "times": [
        1.4401856723,
        1.5221062313,
        1.4177940713,
        1.4489392803,
        1.3998193292999999,
        1.4051069913,
        1.3977946913,
        1.3950719542999999,
        1.4015425033,
        1.4094530363
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.4473329338999998,
      "stddev": 0.0525165297882918,
      "median": 1.4281290398,
      "user": 0.58107434,
      "system": 1.5884936399999998,
      "min": 1.4072186553,
      "max": 1.5812149413,
      "times": [
        1.4229593133,
        1.4914054023,
        1.5812149413,
        1.4293515093,
        1.4449258862999999,
        1.4210732573,
        1.4350873753,
        1.4072186553,
        1.4269065703,
        1.4131864283
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 3.027 ± 0.025 2.988 3.060 2.13 ± 0.03
pacquet@main 3.010 ± 0.038 2.939 3.067 2.12 ± 0.04
pnpr@HEAD 1.423 ± 0.016 1.392 1.448 1.00
pnpr@main 1.424 ± 0.028 1.390 1.484 1.00 ± 0.02
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 3.0265392595800003,
      "stddev": 0.02504284558838877,
      "median": 3.02931996258,
      "user": 1.7969002399999998,
      "system": 1.9848798200000002,
      "min": 2.9884146560800002,
      "max": 3.05980538708,
      "times": [
        3.04288609708,
        3.0186283020799998,
        3.01522180208,
        2.99882020208,
        2.9884146560800002,
        3.04001162308,
        3.00361339708,
        3.04056134708,
        3.05980538708,
        3.05742978208
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 3.01013986818,
      "stddev": 0.038063025007062094,
      "median": 3.01725657058,
      "user": 1.79160304,
      "system": 1.9671561199999998,
      "min": 2.93933305408,
      "max": 3.06708910008,
      "times": [
        2.95779121708,
        3.01595423508,
        2.93933305408,
        2.99352051808,
        3.01922775908,
        3.03730772808,
        3.01370750408,
        3.06708910008,
        3.03890866008,
        3.01855890608
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.4226467681800001,
      "stddev": 0.01573521376561741,
      "median": 1.42100941358,
      "user": 0.5879443400000001,
      "system": 1.58571612,
      "min": 1.3921263020799999,
      "max": 1.44770786408,
      "times": [
        1.42274855808,
        1.43792499508,
        1.43299457608,
        1.44770786408,
        1.41010457808,
        1.41391287708,
        1.4187682020799999,
        1.43090946008,
        1.3921263020799999,
        1.41927026908
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.42439205648,
      "stddev": 0.028294427991169973,
      "median": 1.4245638330800001,
      "user": 0.58476824,
      "system": 1.57771352,
      "min": 1.39049332208,
      "max": 1.48362891308,
      "times": [
        1.42531991208,
        1.42380775408,
        1.44538664608,
        1.48362891308,
        1.44414795808,
        1.3915038230799999,
        1.40723533008,
        1.39049332208,
        1.4263106320799999,
        1.40608627408
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12567
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,780.44 ms
(+0.73%)Baseline: 4,745.69 ms
5,694.82 ms
(83.94%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
3,026.54 ms
(+0.12%)Baseline: 3,022.92 ms
3,627.50 ms
(83.43%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
1,367.33 ms
(+1.61%)Baseline: 1,345.73 ms
1,614.87 ms
(84.67%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
4,818.28 ms
(+2.66%)Baseline: 4,693.56 ms
5,632.27 ms
(85.55%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
664.88 ms
(+4.15%)Baseline: 638.38 ms
766.05 ms
(86.79%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12567
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,241.06 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,422.65 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,423.78 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
3,068.71 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
751.11 ms
🐰 View full continuous benchmarking report in Bencher

@KSXGitHub
KSXGitHub marked this pull request as ready for review June 25, 2026 15:16
@KSXGitHub
KSXGitHub requested a review from zkochan as a code owner June 25, 2026 15:16

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

🤖 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/pack.rs`:
- Around line 111-145: The recursive packing loop in CliArgs::run ignores the
global project selectors, so --filter and --filter-prod are not applied before
packing. Update the workspace project iteration path around
find_workspace_projects, create_projects_graph, and the for chunk/root loop to
skip any project that does not match the active selectors from Config before
calling pack_options/api. Ensure the filtering logic is applied consistently for
recursive targets so pack -r respects the same selection rules as non-recursive
runs.
- Around line 57-59: The `pack_gzip_level` CLI argument is documented as
supporting only `0`–`9`, but the `Pack` args field currently accepts any `u32`.
Update the `pack_gzip_level` definition in the `Pack` CLI args to add a
`value_parser` range constraint so invalid values fail at argument parsing time,
keeping the validation at the CLI boundary.
- Around line 128-133: The manifest filter in the pack recursion currently
treats any string as valid because it only checks `as_str().is_some()`, which
lets empty `name` and `version` values slip through. Update the `has_name` and
`has_version` checks in the `pack` logic to require non-empty strings so they
match the `pacquet_pack::api` precondition before calling `api`, and keep
skipping manifests that fail this stricter validation.

In `@pacquet/crates/exportable-manifest/src/create.rs`:
- Around line 153-156: The `create` flow in `exportable-manifest/src/create.rs`
is coercing present-but-non-object `peerDependencies` into an empty object via
`make_publish_dependencies()` and `unwrap_or_else`, unlike the other dependency
fields. Update the `peerDependencies` handling in `create` so it preserves any
non-object input as-is and only rewrites when the value is actually a dependency
object, using the existing `make_publish_dependencies`/`publish.insert` path
without defaulting `None` to `{}`.

In `@pacquet/crates/exportable-manifest/src/transform.rs`:
- Around line 46-55: `transform_required_fields` is too strict compared to
pnpm’s `if (!manifest.name)` behavior: it currently only accepts non-empty
strings via `Value::as_str()`. Update the validation to match upstream
truthiness semantics by treating any present, non-null value as valid unless it
is an empty string, and keep `TransformError::MissingRequiredField` only for
truly missing/falsy values. Use the existing `transform_required_fields` and
`MissingRequiredField` logic to make the check type-agnostic and preserve pnpm
parity.

In `@pacquet/crates/pack/src/lib.rs`:
- Around line 379-384: The bundled-dependencies guard in the manifest handling
logic is too broad because the check in the loop over bundledDependencies and
bundleDependencies treats false as enabled; update the validation in lib.rs to
only reject the enabled forms (true or an array) before raising
PackError::BundledDependenciesWithoutHoisted, and add a regression test covering
bundleDependencies: false so it passes under the default non-hoisted node
linker.
- Around line 546-551: The workspace LICENSE injection logic in the code that
iterates `read_dir(workspace_dir)` should only add regular files, not
directories or symlinks. Update the `entries.flatten()` loop in the workspace
license handling path to check the `DirEntry` metadata or file type before
calling `is_license_filename(&name)` and inserting into `files_map`, so the
extra `package/{name}` entry is only created for actual files.
🪄 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: 2a99c5aa-66b1-492f-83b2-3f3f5f17615c

📥 Commits

Reviewing files that changed from the base of the PR and between dd8ea85 and e8ffde6.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (25)
  • Cargo.toml
  • pacquet/crates/cli/Cargo.toml
  • pacquet/crates/cli/README.md
  • pacquet/crates/cli/src/cli_args.rs
  • pacquet/crates/cli/src/cli_args/pack.rs
  • pacquet/crates/exportable-manifest/Cargo.toml
  • pacquet/crates/exportable-manifest/src/create.rs
  • pacquet/crates/exportable-manifest/src/create/tests.rs
  • pacquet/crates/exportable-manifest/src/lib.rs
  • pacquet/crates/exportable-manifest/src/transform.rs
  • pacquet/crates/exportable-manifest/src/transform/tests.rs
  • pacquet/crates/fs-packlist/Cargo.toml
  • pacquet/crates/fs-packlist/src/lib.rs
  • pacquet/crates/fs-packlist/src/tests.rs
  • pacquet/crates/git-fetcher/Cargo.toml
  • pacquet/crates/git-fetcher/src/error.rs
  • pacquet/crates/git-fetcher/src/fetcher.rs
  • pacquet/crates/git-fetcher/src/lib.rs
  • pacquet/crates/git-fetcher/src/tarball_fetcher.rs
  • pacquet/crates/pack/Cargo.toml
  • pacquet/crates/pack/src/capabilities.rs
  • pacquet/crates/pack/src/lib.rs
  • pacquet/crates/pack/src/manifest_entry.rs
  • pacquet/crates/pack/src/tarball.rs
  • pacquet/crates/pack/src/tests.rs

Comment thread pacquet/crates/cli/src/cli_args/pack.rs Resolved
Comment thread pacquet/crates/cli/src/cli_args/pack.rs Resolved
Comment thread pacquet/crates/cli/src/cli_args/pack.rs Resolved
Comment thread pacquet/crates/pack/src/lib.rs Resolved
Comment thread pacquet/crates/pack/src/lib.rs Resolved
claude and others added 11 commits June 25, 2026 18:15
Port `pnpm pack` to Rust: create a reproducible gzipped tarball from a
project, running the prepack / prepare / postpack lifecycle scripts,
building the publish manifest, computing the file list, and writing the
archive.

- Extract npm-packlist into a shared `pacquet-fs-packlist` crate so the
  git and directory fetchers and the new pack command share one copy,
  matching pnpm's standalone `@pnpm/fs.packlist` package.
- Extend `pacquet-exportable-manifest` with the full
  createExportableManifest: manifest obfuscation, workspace / catalog /
  jsr specifier rewriting, publishConfig hoisting, README embedding, and
  the bin / peerDependenciesMeta / repository transform.
- Add the `pacquet-pack` crate (single-project api plus JSON / text
  output) and wire `pacquet pack` into the CLI, including the recursive
  (-r) workspace sweep in topological order.

The dependency-converter composition is a straight function sequence
rather than upstream's higher-order combineConverters, and the tarball
write phase uses the capability-trait DI seam (a Host provider plus Fs*
traits) so its filesystem error branches stay testable without
process-global mutation.

Ported from
https://github.com/pnpm/pnpm/blob/cab1c11c69/releasing/commands/src/publish/pack.ts
https://github.com/pnpm/pnpm/blob/ef87f3ccff/releasing/exportable-manifest/src/index.ts

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01G4k3hPXaosUkKBPbnChg4q
Apply `cargo fmt` to the `fixture` helper's `package.json` write, which
drifted after a manual edit. No behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01G4k3hPXaosUkKBPbnChg4q
- Add trailing commas to two multi-line macro invocations in the
  transform tests (perfectionist::macro_trailing_comma).
- Replace a Unicode ellipsis with ASCII "..." in a create.rs doc
  comment (perfectionist::unicode_ellipsis_in_docs).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01G4k3hPXaosUkKBPbnChg4q
- Rename the reporter generic `R` to `Reporter` (bounded `self::Reporter`)
  in pack's `api` / `run_scripts_if_present` and the CLI `pack` command,
  matching the convention already used in executor, git-fetcher, and
  package-manager (perfectionist::single_letter_generic).
- Rename `locale_compare_en`'s `a` / `b` parameters to `left` / `right`
  (perfectionist::single_letter_function_param).
- Move the inline `transform` test module into an external
  `transform/tests.rs` (perfectionist::unit_test_file_layout).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01G4k3hPXaosUkKBPbnChg4q
Port pnpm's `pack: runs prepack, prepare, and postpack`
(releasing/commands/test/publish/pack.ts) so `run_scripts_if_present`
and `script_body` are exercised. The existing pack tests all pass
`ignore_scripts: true`, so that branch was never entered.

- runs_prepack_prepare_and_postpack (Unix-gated, like the executor's
  other script-running tests): with scripts enabled, each of prepack /
  prepare / postpack runs and leaves a marker file.
- pack_succeeds_when_scripts_enabled_but_absent: an empty `prepack`
  makes `script_body` yield `None` and `run_scripts_if_present` return
  early, so packing still succeeds without shelling out.

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

Port the in-scope pnpm pack / createExportableManifest tests that close
coverage holes in this PR's new code:

- pack: bundleDependencies (array) and bundleDependencies: true cover the
  fs-packlist bundle recursion and the node_linker: hoisted allow-path.
- pack: publishConfig.directory covers reading the manifest from the
  build-output dir while resolving workspace: deps against the project
  root's node_modules.
- createExportableManifest: a peerDependencies workspace: rewrite and a
  jsr: specifier without a version selector.

Ported from releasing/commands/test/publish/pack.ts and
releasing/exportable-manifest/test/index.test.ts.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01G4k3hPXaosUkKBPbnChg4q
The `cab1c11c69` SHA the crate docs referenced does not exist upstream.
Repoint every `pack.ts` source link in `pack`'s module docs to
`54c5c0e028`, where pnpm's releasing command now lives under
`pnpm11/releasing/commands/...`, so the citations resolve.
Port pnpm's `pack: bundles transitive dependencies of bundled
dependencies (hoisted)` test. `top` is the only directly-bundled
package, but it depends on `nested`, which is hoisted to the root
`node_modules`; both must end up in the tarball. This exercises
`fs-packlist`'s transitive bundled-closure walk that landed via
#12620 (resolving #12602) and arrived on this branch
through the latest merge from `main`.

Also repoint the existing pack-test citations to the valid
`54c5c0e028` SHA, matching the docs fix in the surrounding crate.
Add a `pacquet pack` section to the CLI README listing its flag support
(`--dry-run`, `--pack-destination`, `--json`, `--out`,
`--pack-gzip-level`, `--skip-manifest-obfuscation`, recursive mode), so
the new command ships with the same flag-status table the other
commands carry. Also pin the last `pack.ts` citation in `cli_args/pack`
to the valid `54c5c0e028` SHA, matching the rest of the crate.
Mutation-testing the pack tests surfaced that
`pack_succeeds_when_scripts_enabled_but_absent` did not actually guard
the behavior its name and doc claim. It asserted only that packing
succeeds with an empty `prepack` script — but an empty lifecycle script
runs as a successful no-op, so removing `script_body`'s
`.filter(|s| !s.is_empty())` left the test green while the empty script
was now executed.

Record the emitted log events with the crate's `RecordingReporter`
idiom and assert no `pnpm:lifecycle` event fires, pinning the "returns
early without shelling out" half of the contract. With the empty-string
filter removed the empty `prepack` shells out and emits a lifecycle
event, so the test now fails — making it a real regression guard for
`script_body`.
…ection

Address review feedback on the pack port:

- Validate `--pack-gzip-level` against 0-9 at the CLI boundary.
- Skip recursive-pack targets whose name/version are empty strings, so
  they match the pacquet_pack::api precondition.
- Stop coercing a non-object peerDependencies into an empty object in
  create_exportable_manifest; leave it in place like the other dep
  fields.
- Gate transform_required_fields on JavaScript truthiness to match
  upstream's `if (!manifest.name)` check instead of requiring a
  non-empty string.
- Gate the bundledDependencies guard on JS truthiness so an explicit
  `false` packs cleanly under the default non-hoisted linker.
- Only inject a workspace LICENSE when the entry resolves to a regular
  file, mirroring fast-glob's onlyFiles default and avoiding an "Is a
  directory" failure in the later read/size pass.
@zkochan
zkochan force-pushed the claude/friendly-galileo-aotu46 branch from e8ffde6 to f81941b Compare June 25, 2026 16:49
@qodo-free-for-open-source-projects

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (8) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Symlinked manifest read 🐞 Bug ⛨ Security
Description
pacquet_pack::read_manifest() reads /package.json via safe_read_package_json_from_dir(), which
uses fs::read_to_string and follows symlinks. An attacker-controlled repo can replace
package.json with a symlink to an out-of-tree JSON file, causing pack to publish attacker-chosen
manifest contents (and potentially leak local JSON data) despite other symlink-hardening in this PR.
Code

pacquet/crates/pack/src/lib.rs[R403-409]

+/// Read the raw manifest under `dir`, erroring when it is absent.
+fn read_manifest(dir: &Path) -> Result<Value, PackError> {
+    match safe_read_package_json_from_dir(dir) {
+        Ok(Some(manifest)) => Ok(manifest),
+        Ok(None) => Err(PackError::ManifestNotFound { dir: dir.display().to_string() }),
+        Err(source) => Err(PackError::ReadManifest(source)),
+    }
Evidence
The new pack code delegates manifest loading to a helper that reads package.json with
fs::read_to_string (symlinks followed). Elsewhere in this PR, README embedding and workspace
LICENSE injection explicitly require a regular file to prevent symlink-based out-of-tree content
inclusion, demonstrating that symlink avoidance is an intended security property for packing.

pacquet/crates/pack/src/lib.rs[403-409]
pacquet/crates/package-manifest/src/lib.rs[561-569]
pacquet/crates/exportable-manifest/src/create.rs[305-318]
pacquet/crates/pack/src/lib.rs[621-629]

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_pack::read_manifest()` accepts a symlinked `package.json` because `safe_read_package_json_from_dir()` reads it via `fs::read_to_string` (symlinks followed). This allows an untrusted repo to point `package.json` outside the project and have `pack` embed attacker-chosen manifest JSON into the produced tarball.
## Issue Context
This PR already explicitly avoids symlink reads for other embedded files (README/license), so `package.json` should follow the same rule.
## Fix Focus Areas
- pacquet/crates/pack/src/lib.rs[403-409]
- pacquet/crates/package-manifest/src/lib.rs[561-569]
## Suggested fix
- Add a non-following check before reading `package.json`:
- Use `std::fs::symlink_metadata(dir.join("package.json"))` and require `file_type().is_file()` **and** `!file_type().is_symlink()` (or equivalently, reject when `is_symlink()`), returning `Ok(None)`/a typed error if it’s not a regular file.
- Prefer fixing this in `safe_read_package_json_from_dir()` so all call sites (including `pack`) get the same protection, and adjust any tests accordingly.

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


2. unsafe_perm hardcoded true ✓ Resolved 🐞 Bug ⛨ Security
Description
pacquet_pack::run_scripts_if_present always sets RunPostinstallHooks.unsafe_perm = true, and
PackOptions has no way to carry Config.unsafe_perm, so pacquet pack lifecycle scripts cannot
honor the workspace unsafePerm policy. This disables the executor’s TMPDIR isolation behavior when
unsafePerm would be false (notably: POSIX root default), diverging from the rest of pacquet’s
lifecycle execution semantics.
Code

pacquet/crates/pack/src/lib.rs[R425-444]

+    let dep_path = opts.dir.to_string_lossy().into_owned();
+    let root_modules_dir = realpath_missing(&opts.dir.join("node_modules"));
+    let run_opts = RunPostinstallHooks {
+        dep_path: &dep_path,
+        pkg_root: &opts.dir,
+        root_modules_dir: &root_modules_dir,
+        init_cwd: &opts.dir,
+        extra_bin_paths: &opts.extra_bin_paths,
+        extra_env: &opts.extra_env,
+        node_execpath: None,
+        npm_execpath: None,
+        node_gyp_path: None,
+        user_agent: Some(&opts.user_agent),
+        // Running scripts explicitly assumes they're trusted.
+        unsafe_perm: true,
+        node_gyp_bin: None,
+        scripts_prepend_node_path: ScriptsPrependNodePath::default(),
+        script_shell: None,
+        optional: false,
+    };
Evidence
The pack implementation hardcodes unsafe_perm: true for lifecycle scripts, while Config
explicitly models unsafe_perm and the executor uses it to decide TMPDIR isolation; therefore
pack cannot respect the configured policy.

pacquet/crates/pack/src/lib.rs[415-444]
pacquet/crates/pack/src/lib.rs[61-93]
pacquet/crates/config/src/lib.rs[1148-1167]
pacquet/crates/executor/src/make_env.rs[112-121]

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 pack` lifecycle scripts are always executed with `unsafe_perm: true` because `pacquet_pack::run_scripts_if_present` hardcodes it and `PackOptions` lacks an `unsafe_perm` field. This prevents `pack` from honoring `Config.unsafe_perm` (which affects executor TMPDIR isolation).
## Issue Context
Other lifecycle-script runners in the repo already thread `config.unsafe_perm` into `pacquet_executor` options. `pack` should do the same so running `pack` as root (or with `unsafePerm: false`) doesn’t silently change script isolation semantics.
## Fix Focus Areas
- pacquet/crates/pack/src/lib.rs[61-93]
- pacquet/crates/pack/src/lib.rs[415-444]
- pacquet/crates/cli/src/cli_args/pack.rs[176-200]
## Expected change
- Add `unsafe_perm: bool` to `pacquet_pack::PackOptions`.
- In CLI `PackArgs::pack_options`, set `unsafe_perm: config.unsafe_perm`.
- In `run_scripts_if_present`, set `unsafe_perm: opts.unsafe_perm` instead of `true`.
- (Optional) Add a focused unit test that constructs `RunPostinstallHooks` via a helper (or refactor to make the value observable) to ensure the flag is threaded correctly.

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


3. Version path traversal write ✓ Resolved 🐞 Bug ⛨ Security
Description
pacquet_pack::resolve_output() interpolates the manifest version into the default tarball
filename without validating it as a safe single filename component. If version contains path
separators or .. segments, dest_dir.join(tarball_name) can write the tarball outside the
intended directory (arbitrary file write) when packing an untrusted repo.
Code

pacquet/crates/pack/src/lib.rs[R470-477]

+fn resolve_output(
+    opts: &PackOptions,
+    normalized_name: &str,
+    version: &str,
+) -> Result<(String, Option<String>), PackError> {
+    let Some(out) = &opts.out else {
+        return Ok((format!("{normalized_name}-{version}.tgz"), opts.pack_destination.clone()));
+    };
Evidence
The code only verifies version is a non-empty string, then directly uses it in the default tarball
filename and writes that path to disk via dest_dir.join(&tarball_name); no sanitization prevents
path separators/traversal.

pacquet/crates/pack/src/lib.rs[235-239]
pacquet/crates/pack/src/lib.rs[475-476]
pacquet/crates/pack/src/lib.rs[290-294]

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

## Issue description
`resolve_output()` uses `format!("{normalized_name}-{version}.tgz")` for the default tarball name, but `version` is only checked for non-empty. A malicious `package.json` can set `version` to something like `../../.ssh/authorized_keys` (or include path separators), which then gets joined and written, escaping `dest_dir`.
### Issue Context
This is a security boundary: manifests are attacker-controlled per REVIEW_GUIDE.md, and `pack` writes to the local filesystem.
### Fix Focus Areas
- pacquet/crates/pack/src/lib.rs[235-239]
- pacquet/crates/pack/src/lib.rs[470-492]
- pacquet/crates/pack/src/lib.rs[290-294]
### What to change
- Introduce validation before using `version` in a filesystem path:
- Reject versions containing `/` or `\\`.
- Reject any value where `Path::new(version).components()` contains `ParentDir`, `RootDir`, or `Prefix(_)`.
- Consider parsing with `node_semver::Version::parse` (if pack is intended to create publishable artifacts) and fail with a clear `PackError` if invalid.
- Additionally (defense-in-depth), validate `tarball_name` is a single safe filename component before `dest_dir.join(&tarball_name)` (reject empty/`.`/`..` and any separators).

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


View more (4)
4. Packlist path escape read ✓ Resolved 🐞 Bug ⛨ Security
Description
pacquet_fs_packlist force-includes main/bin paths after only stripping leading ./ and /,
allowing values like ../secret or Windows absolute/UNC paths to escape the package root.
pacquet_pack then trusts packlist output and reads those paths into the tarball, enabling
arbitrary local file exfiltration when packing an untrusted repo.
Code

pacquet/crates/pack/src/lib.rs[R494-498]

+/// Map each packed path to `package/<path>` → absolute source, in
+/// packlist order.
+fn build_files_map(dir: &Path, files: &[String]) -> indexmap::IndexMap<String, PathBuf> {
+    files.iter().map(|file| (format!("package/{file}"), dir.join(file))).collect()
+}
Evidence
fs-packlist includes main/bin based on pkg_dir.join(...).is_file() after a normalization
that only strips ./ and leading /, so .. or Windows absolute prefixes can survive. pack then
joins these strings onto dir and build_tarball() reads the resulting filesystem paths into the
archive.

pacquet/crates/fs-packlist/src/lib.rs[373-389]
pacquet/crates/fs-packlist/src/lib.rs[573-579]
pacquet/crates/pack/src/lib.rs[268-270]
pacquet/crates/pack/src/lib.rs[496-498]
pacquet/crates/pack/src/tarball.rs[47-52]

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

## Issue description
`fs-packlist` will include `main`/`bin` files by checking `pkg_dir.join(normalize_field_path(x)).is_file()`, but `normalize_field_path()` does not reject `..` or Windows absolute prefixes (and `is_file()` follows symlinks). This can cause `packlist()` to return paths that escape `pkg_dir`. `pacquet_pack` then constructs sources with `dir.join(file)` and `build_tarball()` reads them, embedding arbitrary host files into the tarball.
### Issue Context
- Manifests are attacker-controlled inputs.
- `pack` reads arbitrary files and writes publishable archives.
- There is already a safe component-based join pattern in the repo (`join_checked`).
### Fix Focus Areas
- pacquet/crates/fs-packlist/src/lib.rs[367-389]
- pacquet/crates/fs-packlist/src/lib.rs[573-579]
- pacquet/crates/pack/src/lib.rs[268-270]
- pacquet/crates/pack/src/lib.rs[494-498]
- pacquet/crates/pack/src/tarball.rs[47-52]
### What to change
1. In `pacquet-fs-packlist`, harden the forced-includes for `main` and `bin`:
- Validate the normalized path with `Path::components()` (reject `ParentDir`, `RootDir`, `Prefix(_)`).
- Treat backslashes as separators on Windows (or reject them in these manifest fields) to avoid drive/UNC escapes.
- Use `symlink_metadata` and require a regular file (do not follow symlinks) before inserting.
2. In `pacquet-pack` (defense-in-depth), validate every `files` entry from `packlist()` before `dir.join(file)`:
- Reuse the same component-based checks (similar to `git-fetcher`’s `join_checked`) and fail closed if any entry is unsafe.
3. Add tests covering:
- `main: "../secret.txt"` and `bin: "../secret.txt"` should be rejected / not included.
- On Windows, `main: "C:\\secret.txt"` / UNC paths should be rejected.
- A symlinked `main`/`bin` should not cause target bytes outside the package to be read.

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


5. Symlink-following tarball write ✓ Resolved 🐞 Bug ⛨ Security
Description
pacquet-pack persists the tarball with std::fs::write, which is non-atomic and follows symlinks;
a repo-controlled symlink at the output path can redirect the write and overwrite an arbitrary file
accessible to the process. A crash mid-write can also leave a truncated .tgz, which contradicts
the repo’s existing atomic-write hardening in other file write paths.
Code

pacquet/crates/pack/src/capabilities.rs[R71-74]

+impl FsWrite for Host {
+    fn write(path: &Path, bytes: &[u8]) -> io::Result<()> {
+        std::fs::write(path, bytes)
+    }
Evidence
The tarball write is delegated to std::fs::write, which is non-atomic and follows symlinks. The
pack pipeline calls this write for the final tarball path. Elsewhere in the repo, atomic writes
deliberately use symlink_metadata and temp-file+rename to avoid symlink and torn-write issues,
demonstrating the expected security posture.

pacquet/crates/pack/src/capabilities.rs[40-75]
pacquet/crates/pack/src/lib.rs[276-294]
pacquet/crates/fs/src/ensure_file.rs[254-266]
pacquet/crates/fs/src/ensure_file.rs[355-368]

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

## Issue description
`FsWrite for Host` uses `std::fs::write`, which truncates in place and follows symlinks. When `pacquet pack` runs in a repo/CI context where an attacker can commit a symlink at the expected tarball path (or influence `--out`), the tarball write can overwrite arbitrary files. It’s also non-atomic, so partial archives can be observed if the process is interrupted.
## Issue Context
Other pacquet write paths already implement atomic temp-file + rename and explicitly avoid symlink pitfalls.
## Fix Focus Areas
- pacquet/crates/pack/src/capabilities.rs[40-75]
- pacquet/crates/pack/src/lib.rs[276-294]
## Suggested fix
- Replace `Host::write` with an atomic write implementation (create temp file in destination dir with `create_new(true)`, write+fsync, then rename to final path).
- Add a symlink defense:
- If the destination exists and `symlink_metadata` indicates it’s not a regular file, fail; OR
- On Unix, open temp with `O_NOFOLLOW` (where feasible) and ensure final rename overwrites safely.
- Keep the DI seam (so tests can still inject write failures), but make the production `Host` safe by default.

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


6. publishConfig.directory path escape 🐞 Bug ⛨ Security
Description
pacquet_pack::api uses publishConfig.directory from package.json to form the publish directory
via opts.dir.join(relative) without validating containment, so ../ segments can escape the
project root. This can make pack read/pack files outside the package boundary and write the
tarball outside the intended directory.
Code

pacquet/crates/pack/src/lib.rs[R215-220]

+    // The publish directory may differ from the project root when
+    // `publishConfig.directory` redirects packing at a build output.
+    let dir = match publish_config_directory(&entry_manifest) {
+        Some(relative) => opts.dir.join(relative),
+        None => opts.dir.clone(),
+    };
Evidence
The publish directory is derived directly from publishConfig.directory and then used to re-read
the manifest and compute the packlist, so escaping the root changes what files are read/packed. The
repo already demonstrates the expected mitigation pattern (subdirectory containment checks) for
manifest-controlled relative paths.

pacquet/crates/pack/src/lib.rs[215-270]
pacquet/crates/cmd-shim/src/bin_resolver.rs[76-79]
pacquet/crates/cmd-shim/src/bin_resolver.rs[136-139]

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

## Issue description
`publishConfig.directory` is treated as a trusted relative path and joined onto `opts.dir` without checking for traversal/root-escape. A malicious manifest can set `publishConfig.directory` to values like `../..` to make packing operate on arbitrary filesystem locations.
### Issue Context
`pack` treats the manifest as attacker-controlled input (per repo security rules). The codebase already uses containment guards (`pacquet_fs::is_subdir`) for manifest-controlled paths in other areas (e.g., bin resolution).
### Fix Focus Areas
- pacquet/crates/pack/src/lib.rs[215-220]
- Reject absolute `publishConfig.directory`.
- Normalize/resolve the joined path and enforce it stays under `opts.dir` (e.g., `pacquet_fs::is_subdir(opts.dir, candidate)`; if you canonicalize, do it safely and fail closed on errors).
- If validation fails, return a new `PackError` explaining the invalid `publishConfig.directory`.
- pacquet/crates/pack/src/lib.rs[222-268]
- Ensure subsequent reads/packlist use only the validated publish directory.
- (add test)
- Add a unit test in `pacquet/crates/pack/src/tests.rs` that sets `publishConfig.directory` to `..`/`../..` and asserts packing is rejected.

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


7. Symlink LICENSE exfiltration ✓ Resolved 🐞 Bug ⛨ Security
Description
inject_workspace_license uses fs::metadata (follows symlinks) to decide whether to inject a
workspace-root LICENSE, so a symlinked LICENSE can cause arbitrary host file contents to be included
in the packed tarball. This enables local file exfiltration when packing/publishing from an
untrusted workspace.
Code

pacquet/crates/pack/src/lib.rs[R560-574]

+    let Ok(entries) = std::fs::read_dir(workspace_dir) else { return };
+    for entry in entries.flatten() {
+        let name = entry.file_name().to_string_lossy().into_owned();
+        if !is_license_filename(&name) {
+            continue;
+        }
+        // Upstream globs the license with `onlyFiles` (fast-glob's
+        // default), so a directory named `LICENSE` is not a match.
+        // `fs::metadata` follows symlinks, mirroring fast-glob's default
+        // symlink resolution, so a symlinked license still counts while a
+        // directory (or a symlink to one) is skipped — the latter would
+        // otherwise fail the later read/size pass with "Is a directory".
+        if std::fs::metadata(entry.path()).is_ok_and(|metadata| metadata.is_file()) {
+            files_map.insert(format!("package/{name}"), workspace_dir.join(&name));
+        }
Evidence
inject_workspace_license explicitly uses fs::metadata, which follows symlinks; the selected path
is then used as a tarball source, so the symlink target’s bytes are what gets packed. The README
embedding implementation in this PR shows the intended mitigation: skip symlinks to prevent leaking
outside-project file contents.

pacquet/crates/pack/src/lib.rs[560-574]
pacquet/crates/exportable-manifest/src/create.rs[305-318]

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

## Issue description
Workspace license injection follows symlinks, so `LICENSE -> /path/outside/workspace` will be treated as an injectable file and later read into the tarball. This violates the expected package boundary and can leak sensitive host files.
### Issue Context
The exportable-manifest README embedding code explicitly avoids symlinks to prevent the same class of leak.
### Fix Focus Areas
- pacquet/crates/pack/src/lib.rs[560-574]
- Replace `std::fs::metadata(...)` with `std::fs::symlink_metadata(...)` and require `file_type.is_file()` **and** `!file_type.is_symlink()`.
- (Optional stronger hardening) If you want to allow symlinks only when they still point within `workspace_dir`, canonicalize both and enforce `target.strip_prefix(workspace_dir_canonical)`.
- (add test)
- Add a unit test in `pacquet/crates/pack/src/tests.rs` that creates a symlinked `LICENSE` and asserts it is not injected (or that packing fails closed, depending on intended behavior).

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



Remediation recommended

8. Manifest rewrite name collision 🐞 Bug ≡ Correctness
Description
pack treats package/package.json5 and package/package.yaml as manifest entries and rewrites
them to package/package.json, so packages that legitimately include those files will have their
on-disk contents replaced by the publish manifest in the tarball and the contents listing will
collapse them to package.json. This is observable whenever fs-packlist includes those filenames
(it walks all regular files) and can lead to archives that do not actually contain the original
package.json5/package.yaml data under their names.
Code

pacquet/crates/pack/src/manifest_entry.rs[R1-10]

+/// True when a `package/<path>` tar key names the package manifest.
+///
+/// `pack` rewrites every `package.json` / `package.json5` /
+/// `package.yaml` entry into a single serialized `package/package.json`,
+/// and reports all of them as `package.json` in the contents listing.
+/// Mirrors the `/^package\/package\.(?:json|json5|yaml)$/` test pnpm
+/// applies in three places (tar entry rewrite, size, and contents).
+#[must_use]
+pub fn is_manifest_entry(name: &str) -> bool {
+    matches!(name, "package/package.json" | "package/package.json5" | "package/package.yaml")
Evidence
The rewrite decision is driven by is_manifest_entry() matching json5/yaml, and the tarball builder
unconditionally maps those to package/package.json. fs-packlist walks and includes regular
files, so package.json5/package.yaml can naturally appear in files_map and therefore be
rewritten/collapsed in the archive and output listing.

pacquet/crates/pack/src/manifest_entry.rs[1-11]
pacquet/crates/pack/src/tarball.rs[58-72]
pacquet/crates/pack/src/lib.rs[654-667]
pacquet/crates/fs-packlist/src/lib.rs[287-343]

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

## Issue description
`pack` rewrites tar entries whose name matches `package/package.(json|json5|yaml)` into a single `package/package.json`. Because `fs-packlist` may include regular files named `package.json5` or `package.yaml`, those files can be unintentionally rewritten/collapsed, changing the tarball’s payload.
### Issue Context
Pacquet currently only reads `package.json` as the manifest input, but the tarball rewrite logic reserves additional basenames (`package.json5`, `package.yaml`). If these are present as ordinary files, the tar writer will emit `package/package.json` for them.
### Fix Focus Areas
- pacquet/crates/pack/src/manifest_entry.rs[1-11]
- pacquet/crates/pack/src/tarball.rs[58-72]
- pacquet/crates/pack/src/lib.rs[657-666]
### Suggested fix
Choose one of:
1) Narrow `is_manifest_entry()` to only match `package/package.json` (since pacquet doesn’t ingest json5/yaml manifests today), OR
2) Keep matching json5/yaml but ensure only one rewritten manifest entry is emitted (e.g., write `package/package.json` once and skip additional manifest-like entries, while preserving the original files under their original names if you intend to ship them).
Add/adjust a unit test: create a fixture with a real `package.yaml` file and assert the tarball contains `package/package.yaml` with its original bytes (or explicitly assert it is excluded if that’s the intended contract).

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


9. JSON output panics empty 🐞 Bug ☼ Reliability
Description
format_pack_output() panics in JSON mode when called with an empty results slice because it
indexes results[0] for the single-item case. This is a public helper in pacquet-pack, so any
future caller (or refactor) that passes an empty slice will crash.
Code

pacquet/crates/pack/src/lib.rs[R347-354]

+pub fn format_pack_output(results: &[PackResultJson], json: bool, unicode: bool) -> String {
+    if json {
+        return if results.len() > 1 {
+            serde_json::to_string_pretty(&results)
+        } else {
+            serde_json::to_string_pretty(&results[0])
+        }
+        .expect("pack result serializes to JSON");
Evidence
The JSON branch selects the single-result serialization path whenever results.len() <= 1 and
directly indexes results[0], which will panic for an empty slice.

pacquet/crates/pack/src/lib.rs[342-355]

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

## Issue description
`format_pack_output(results, json=true, ...)` indexes `results[0]` when `results.len() <= 1`, which panics if `results` is empty.
### Issue Context
Current CLI call paths generally avoid passing an empty slice, but this is a `pub fn` and is easy to misuse in future call sites.
### Fix Focus Areas
- pacquet/crates/pack/src/lib.rs[342-355]
### Suggested fix
Add an explicit empty guard in the `json` branch:
- If `results.is_empty()`, return `"[]"` (or `"null"`/`"{}"` depending on intended contract; `[]` is typically safest for JSON output).
- Keep current behavior for 1 result vs >1 results.
Add a unit test that calls `format_pack_output(&[], true, false)` and asserts it returns valid JSON and does not panic.

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


10. Terminal output spoofing 🐞 Bug ⛨ Security
Description
format_pack_output() prints filesystem-derived paths, but sanitize_for_terminal() preserves
\n/\t and even returns the original string when those are the only control characters, so a
packed filename containing a newline can inject extra lines and spoof the human-readable summary.
This can mislead users/CI logs by hiding or forging entries in the non-JSON output mode.
Code

pacquet/crates/pack/src/lib.rs[R357-400]

+    let prefix = if unicode { "📦 " } else { "package:" };
+    results
+        .iter()
+        .map(|result| {
+            // `name` / `version` / `filename` and the file paths are
+            // manifest- and filesystem-derived, so strip control
+            // characters before they reach the terminal — a file named
+            // with raw ANSI escapes would otherwise spoof the output.
+            let files = result
+                .files
+                .iter()
+                .map(|file| sanitize_for_terminal(&file.path))
+                .collect::<Vec<_>>()
+                .join("\n");
+            format!(
+                "{prefix} {name}@{version}\nTarball Contents\n{files}\nTarball Details\n{filename}",
+                name = sanitize_for_terminal(&result.name),
+                version = sanitize_for_terminal(&result.version),
+                filename = sanitize_for_terminal(&result.filename),
+            )
+        })
+        .collect::<Vec<_>>()
+        .join("\n\n")
+}
+
+/// Strip control characters (keeping `\n` / `\t`) from text headed for the
+/// terminal, so a manifest- or filesystem-derived value can't emit raw
+/// escape sequences. JSON output is left untouched — it is data, not a
+/// terminal rendering.
+fn sanitize_for_terminal(text: &str) -> std::borrow::Cow<'_, str> {
+    if text
+        .chars()
+        .any(|character| character.is_control() && character != '\n' && character != '\t')
+    {
+        std::borrow::Cow::Owned(
+            text.chars()
+                .filter(|character| {
+                    !character.is_control() || *character == '\n' || *character == '\t'
+                })
+                .collect(),
+        )
+    } else {
+        std::borrow::Cow::Borrowed(text)
+    }
Evidence
The text output path joins file paths with newlines and relies on sanitize_for_terminal() to
neutralize unsafe characters, but that sanitizer explicitly allows \n/\t and can return the
unmodified string. Since packed paths are filesystem-derived, a newline in a filename will be
emitted as an actual line break and can alter the perceived structure of the output.

pacquet/crates/pack/src/lib.rs[357-401]
pacquet/crates/fs-packlist/src/lib.rs[115-124]

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

## Issue description
`sanitize_for_terminal()` currently allows `\n` and `\t` to pass through into the human-readable output. Since `format_pack_output()` joins file paths with `\n`, a filename containing an embedded newline can inject extra lines and spoof the printed summary.
### Issue Context
This affects only the **text** output path (non-JSON). The inputs (`result.files[*].path`, `result.filename`) are filesystem-derived and therefore attacker-controlled when packing an untrusted repo.
### Fix Focus Areas
- pacquet/crates/pack/src/lib.rs[357-401]
### Implementation notes
- Treat `\n` (and likely `\r`) as unsafe for terminal rendering: either strip them, replace them with visible escape sequences (e.g. `\n`), or render via a safe escaping routine.
- Consider also addressing other spoofing characters that are not `char::is_control()` (e.g. Unicode bidi override characters) if you want robust “what you see is what you packed” output.

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


View more (4)
11. Wrong pack output base 🐞 Bug ≡ Correctness
Description
When publishConfig.directory is set, pacquet_pack::api resolves the tarball destination relative
to the publish directory (e.g. dist/) rather than the CLI working directory, contradicting the
--pack-destination default contract. This can write artifacts into build output trees unexpectedly
and break scripts/CI that assume pack outputs alongside the project root.
Code

pacquet/crates/pack/src/lib.rs[R227-297]

+    // The publish directory may differ from the project root when
+    // `publishConfig.directory` redirects packing at a build output.
+    let dir = match publish_config_directory(&entry_manifest) {
+        Some(relative) => opts.dir.join(relative),
+        None => opts.dir.clone(),
+    };
+
+    // Re-read the manifest from `dir`: a `prepack` / `prepare` script
+    // may have rewritten it.
+    let manifest = read_manifest(&dir)?;
+    prevent_bundled_dependencies_without_hoisted(opts.node_linker, &manifest)?;
+
+    let name = manifest
+        .get("name")
+        .and_then(Value::as_str)
+        .filter(|name| !name.is_empty())
+        .ok_or(PackError::PackageNameNotFound)?;
+    if !is_valid_old_npm_package_name(name) {
+        return Err(PackError::InvalidPackageName { name: name.to_string() });
+    }
+    let version = manifest
+        .get("version")
+        .and_then(Value::as_str)
+        .filter(|version| !version.is_empty())
+        .ok_or(PackError::PackageVersionNotFound)?;
+    // The version is interpolated into the default tarball filename
+    // (`<name>-<version>.tgz`), and the manifest is attacker-controlled.
+    // A separator would let `version` smuggle path components into the
+    // join and write the tarball outside `dest_dir`. A real semver
+    // version never contains one, so reject it.
+    if version.contains('/') || version.contains('\\') {
+        return Err(PackError::InvalidPackageVersion { version: version.to_string() });
+    }
+
+    let modules_dir = opts.dir.join("node_modules");
+    let mut publish_manifest = create_exportable_manifest(
+        &dir,
+        &manifest,
+        &CreateExportableManifestOptions {
+            catalogs: &opts.catalogs,
+            modules_dir: Some(&modules_dir),
+            skip_manifest_obfuscation: opts.skip_manifest_obfuscation,
+            embed_readme: opts.embed_readme,
+        },
+    )
+    .map_err(PackError::CreateManifest)?;
+
+    // Strip semver build metadata (the `+<build>` segment) so the
+    // tarball name, the packed manifest, and any registry metadata all
+    // agree on the version. See pnpm/pnpm#11518.
+    let published_version =
+        strip_build_metadata(publish_manifest.get("version").and_then(Value::as_str).unwrap_or(""))
+            .to_string();
+    if let Some(object) = publish_manifest.as_object_mut() {
+        object.insert("version".to_string(), Value::String(published_version.clone()));
+    }
+
+    let normalized_name = normalize_tarball_name(name);
+    let (tarball_name, pack_destination) =
+        resolve_output(opts, &normalized_name, &published_version)?;
+
+    let files = packlist(&dir, &publish_manifest).map_err(PackError::Packlist)?;
+    let mut files_map = build_files_map(&dir, &files);
+    inject_workspace_license(opts, &dir, &files, &mut files_map);
+
+    let manifest_json = serde_json::to_string_pretty(&publish_manifest)
+        .expect("publish manifest serializes to JSON")
+        .into_bytes();
+
+    let dest_dir = resolve_dest_dir(&dir, pack_destination.as_deref());
+
Evidence
The CLI docs state --pack-destination defaults to the current working directory, but api()
computes dir from publishConfig.directory and then uses that dir as the base for
resolve_dest_dir, shifting default/relative output under the publish directory.

pacquet/crates/cli/src/cli_args/pack.rs[43-46]
pacquet/crates/pack/src/lib.rs[227-233]
pacquet/crates/pack/src/lib.rs[296-297]
pacquet/crates/pack/src/lib.rs[555-562]

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_pack::api` changes the output base directory when `publishConfig.directory` is set by using the publish directory (`opts.dir.join(publishConfig.directory)`) as the base for `resolve_dest_dir(...)`. This conflicts with the CLI arg docs (`--pack-destination` defaults to current working directory) and can cause tarballs to be written into `dist/` by default.
### Issue Context
- The pack command explicitly documents that `--pack-destination` defaults to the current working directory.
- `api()` computes a `dir` that may differ from `opts.dir` when `publishConfig.directory` is present, and currently uses that publish `dir` as the base for `resolve_dest_dir`.
### Fix Focus Areas
- pacquet/crates/pack/src/lib.rs[227-233]
- pacquet/crates/pack/src/lib.rs[292-327]
- pacquet/crates/pack/src/lib.rs[555-579]
- pacquet/crates/cli/src/cli_args/pack.rs[43-46]
### What to change
1. Decide and enforce a single contract: output destination should be resolved against the CLI/project dir (`opts.dir`), not the publish dir.
2. Update `resolve_dest_dir(...)` call site to use `&opts.dir` (or a new `output_base_dir`) for relative destinations and defaulting.
3. Adjust `packed_tarball_path(...)` to report the actual tarball location correctly when `publish_dir != project_dir` (today it assumes the tarball is under `publish_dir` when `dest_dir == project_dir`).
4. Add/adjust a test case covering `publishConfig.directory` ensuring the tarball lands in the intended directory and the returned `tarball_path` matches.

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


12. Nondeterministic LICENSE injection 🐞 Bug ☼ Reliability
Description
inject_workspace_license() iterates read_dir() and inserts matching license files in
OS-dependent enumeration order, so tarball entry order (and thus tarball bytes) can vary between
runs when multiple license-like files exist. This undermines the PR’s reproducible tarball goal and
can cause cache misses/non-reproducible publish artifacts.
Code

pacquet/crates/pack/src/lib.rs[R615-629]

+    let Ok(entries) = std::fs::read_dir(workspace_dir) else { return };
+    for entry in entries.flatten() {
+        let name = entry.file_name().to_string_lossy().into_owned();
+        if !is_license_filename(&name) {
+            continue;
+        }
+        // Only inject a regular file. A directory named `LICENSE` would
+        // fail the later read/size pass with "Is a directory", and a
+        // symlink could point outside the workspace and leak its target's
+        // bytes into the published tarball. `DirEntry::file_type` does not
+        // follow symlinks, so `is_file()` rejects both — matching the
+        // symlink-skipping `read_readme_file` does in `exportable-manifest`.
+        if entry.file_type().is_ok_and(|file_type| file_type.is_file()) {
+            files_map.insert(format!("package/{name}"), workspace_dir.join(&name));
+        }
Evidence
inject_workspace_license() inserts matching LICENSE files in read_dir() iteration order, and
tarball construction iterates files_map in insertion order, so directory enumeration order impacts
archive bytes.

pacquet/crates/pack/src/lib.rs[602-631]
pacquet/crates/pack/src/tarball.rs[44-72]

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

## Issue description
`inject_workspace_license()` uses `std::fs::read_dir()` and inserts matches into an `IndexMap` in iteration order. `read_dir()` order is not stable, and `tarball::build_tarball()` emits entries in `IndexMap` insertion order, making the archive non-deterministic when multiple license files match.
### Issue Context
This shows up when the workspace root contains multiple license-like files (e.g. `LICENSE` and `LICENSE.md`, or case variants) and a sub-package lacks a license.
### Fix Focus Areas
- pacquet/crates/pack/src/lib.rs[602-631]
- pacquet/crates/pack/src/tarball.rs[44-72]
### Suggested fix
1. Collect matching license filenames (or `DirEntry`s) into a vector.
2. Sort deterministically (e.g. by `to_ascii_lowercase()` then by original name for tie-break).
3. Insert into `files_map` in that sorted order.
4. (Optional) If pnpm only injects one license, pick a deterministic precedence order (e.g. prefer exact `LICENSE`/`LICENCE` over suffixed variants) and inject only that one.

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


13. Non-string bin key 🐞 Bug ≡ Correctness
Description
exportable-manifest::transform_required_fields accepts any truthy JSON value for name, but
transform_bin then reads name via Value::as_str().unwrap_or_default(), producing an empty
command name when name is truthy-but-non-string and bin is a string. This can yield an invalid
packed manifest ("bin": { "": "..." }) and diverges from pnpm’s JS coercion behavior.
Code

pacquet/crates/exportable-manifest/src/transform.rs[R46-86]

+/// Reject a manifest missing the registry-required `name` / `version`.
+/// Mirrors upstream's `if (!manifest.name)` truthiness check: a field
+/// counts as missing only when it is absent or JS-falsy (`null`, `false`,
+/// `0`, or `""`), so any other present value — including a non-string —
+/// passes, matching pnpm exactly.
+fn transform_required_fields(manifest: &Map<String, Value>) -> Result<(), TransformError> {
+    for field in ["name", "version"] {
+        if !manifest.get(field).is_some_and(is_truthy) {
+            return Err(TransformError::MissingRequiredField { field });
+        }
+    }
+    Ok(())
+}
+
+/// Whether a JSON value is truthy under JavaScript's coercion rules, so
+/// the publish-manifest transforms gate the same way pnpm's `if (!value)`
+/// checks do. Arrays and objects are always truthy, even when empty.
+fn is_truthy(value: &Value) -> bool {
+    match value {
+        Value::Null => false,
+        Value::Bool(boolean) => *boolean,
+        Value::Number(number) => number.as_f64().is_some_and(|number| number != 0.0),
+        Value::String(string) => !string.is_empty(),
+        Value::Array(_) | Value::Object(_) => true,
+    }
+}
+
+/// Normalize a string `bin` into the object form `{ <command>: <path> }`.
+/// A `bin` that is already an object (or absent) is left untouched.
+fn transform_bin(manifest: &mut Map<String, Value>) -> Result<(), TransformError> {
+    let Some(Value::String(bin)) = manifest.get("bin") else {
+        return Ok(());
+    };
+    let bin = bin.clone();
+    // `transformRequiredFields` already guaranteed a string `name`.
+    let pkg_name = manifest.get("name").and_then(Value::as_str).unwrap_or_default();
+    let command_name = normalize_bin_name(pkg_name)?;
+    let mut bin_object = Map::new();
+    bin_object.insert(command_name, Value::String(bin));
+    manifest.insert("bin".to_string(), Value::Object(bin_object));
+    Ok(())
Evidence
The transform explicitly allows truthy non-string name/version values, and tests lock that in;
but transform_bin then treats non-string names as empty, which can create an empty bin command
key.

pacquet/crates/exportable-manifest/src/transform.rs[46-86]
pacquet/crates/exportable-manifest/src/transform/tests.rs[36-44]

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 transform pipeline intentionally mirrors pnpm’s truthiness check for required fields, which allows truthy non-string `name`/`version` values. However, `transform_bin` assumes `name` is a string and falls back to `""`, causing the bin command key to become empty for non-string (but truthy) names.
## Issue Context
There is an explicit test asserting numeric `name`/`version` survive validation. With that contract, downstream steps must not silently treat non-string `name` as empty when normalizing string `bin`.
## Fix Focus Areas
- pacquet/crates/exportable-manifest/src/transform.rs[46-86]
- pacquet/crates/exportable-manifest/src/transform/tests.rs[36-56]
## Suggested fix
- Update `transform_bin` to derive the command name using JS-like string coercion of `manifest["name"]` (approximate `String(value)` / property-key coercion), rather than `as_str().unwrap_or_default()`.
- For example: strings use the string; numbers/bools use their textual representation; objects -> `"[object Object]"`; arrays -> comma-joined element coercions.
- Add a test case: `{ "name": 1, "version": 2, "bin": "cli.js" }` should normalize to `{ "bin": { "1": "cli.js" } }` (or whatever exact coercion you choose), but must not produce an empty key.
- Also fix the misleading comment `// transformRequiredFields already guaranteed a string name.`

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


14. In-memory tarball build ✓ Resolved 🐞 Bug ➹ Performance
Description
tarball::build_tarball reads each packed file into memory and builds the entire gzipped tarball
into a Vec, which can cause large peak RSS/OOM and significant allocation/copy overhead on big
packages. The caller also holds the full tarball bytes until Sys::write, compounding memory
pressure.
Code

pacquet/crates/pack/src/tarball.rs[R43-52]

+    let compression =
+        gzip_level.map_or_else(Compression::default, |level| Compression::new(level.min(9)));
+    let mut builder = tar::Builder::new(GzEncoder::new(Vec::new(), compression));
+
+    for (name, source) in files_map {
+        let (entry_name, data) = if is_manifest_entry(name) {
+            (PACKED_MANIFEST_NAME, manifest_json.to_vec())
+        } else {
+            (name.as_str(), Sys::read_file(source)?)
+        };
Evidence
build_tarball uses GzEncoder::new(Vec::new(), ...) and appends entries after materializing each
entry’s data into a Vec (including Sys::read_file). api() then stores the returned Vec as
tarball until it calls Sys::write, ensuring the entire archive is resident in memory.

pacquet/crates/pack/src/tarball.rs[37-65]
pacquet/crates/pack/src/lib.rs[290-306]

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 tarball is constructed fully in memory (`GzEncoder<Vec<u8>>`) and each source file is fully read into a `Vec<u8>` before being appended. This scales poorly and can OOM for large workspaces or attacker-inflated repos.
## Issue Context
This is a packing hot spot: it is proportional to total bytes packed. The code already writes atomically via a temp file in `Host::write`, so streaming into a temp file (or into the `FsWrite` capability via a writer) would preserve safety while eliminating the big in-memory buffer.
## Fix Focus Areas
- pacquet/crates/pack/src/tarball.rs[37-65]
- pacquet/crates/pack/src/lib.rs[290-306]
### Suggested fix approach
1. Change tarball building to be streaming:
- Option A: introduce a new capability (e.g. `FsCreateFile`/`FsOpenTempFile`) returning a `Write` handle, and have `build_tarball_into(writer, ...)` write into it.
- Option B: keep the current atomic temp-file pattern in `Host::write`, but move tarball construction inside `Host::write` so it can stream directly into the temp file.
2. Avoid per-file `Vec<u8>` reads by passing a `Read` (e.g. `std::fs::File`) to `tar::Builder::append_data` instead of `Sys::read_file`.
3. Keep reproducibility (fixed mtime/mode) by continuing to set headers explicitly per entry.

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


Grey Divider

Qodo Logo

Comment thread pacquet/crates/pack/src/lib.rs Resolved
Comment thread pacquet/crates/pack/src/lib.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pacquet/crates/exportable-manifest/src/transform/tests.rs`:
- Around line 29-33: Update the falsy regression coverage in
falsy_version_is_rejected so it also exercises version: "" alongside the
existing falsy values. The transform_required_fields behavior applies the same
truthiness check to version as to name, so add the empty-string version case to
the run(json!({ "name": "foo", "version": falsy })) loop and keep asserting
MissingRequiredField for version using the existing run and TransformError
symbols.
🪄 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: 6c933cf0-599c-49f1-8fa7-c38324d4a10a

📥 Commits

Reviewing files that changed from the base of the PR and between e8ffde6 and f81941b.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (25)
  • Cargo.toml
  • pacquet/crates/cli/Cargo.toml
  • pacquet/crates/cli/README.md
  • pacquet/crates/cli/src/cli_args.rs
  • pacquet/crates/cli/src/cli_args/pack.rs
  • pacquet/crates/exportable-manifest/Cargo.toml
  • pacquet/crates/exportable-manifest/src/create.rs
  • pacquet/crates/exportable-manifest/src/create/tests.rs
  • pacquet/crates/exportable-manifest/src/lib.rs
  • pacquet/crates/exportable-manifest/src/transform.rs
  • pacquet/crates/exportable-manifest/src/transform/tests.rs
  • pacquet/crates/fs-packlist/Cargo.toml
  • pacquet/crates/fs-packlist/src/lib.rs
  • pacquet/crates/fs-packlist/src/tests.rs
  • pacquet/crates/git-fetcher/Cargo.toml
  • pacquet/crates/git-fetcher/src/error.rs
  • pacquet/crates/git-fetcher/src/fetcher.rs
  • pacquet/crates/git-fetcher/src/lib.rs
  • pacquet/crates/git-fetcher/src/tarball_fetcher.rs
  • pacquet/crates/pack/Cargo.toml
  • pacquet/crates/pack/src/capabilities.rs
  • pacquet/crates/pack/src/lib.rs
  • pacquet/crates/pack/src/manifest_entry.rs
  • pacquet/crates/pack/src/tarball.rs
  • pacquet/crates/pack/src/tests.rs
✅ Files skipped from review due to trivial changes (6)
  • pacquet/crates/git-fetcher/src/fetcher.rs
  • pacquet/crates/git-fetcher/src/tarball_fetcher.rs
  • pacquet/crates/exportable-manifest/src/lib.rs
  • Cargo.toml
  • pacquet/crates/fs-packlist/Cargo.toml
  • pacquet/crates/cli/README.md
🚧 Files skipped from review as they are similar to previous changes (17)
  • pacquet/crates/pack/src/manifest_entry.rs
  • pacquet/crates/pack/src/capabilities.rs
  • pacquet/crates/exportable-manifest/Cargo.toml
  • pacquet/crates/pack/Cargo.toml
  • pacquet/crates/cli/src/cli_args.rs
  • pacquet/crates/pack/src/tarball.rs
  • pacquet/crates/git-fetcher/Cargo.toml
  • pacquet/crates/exportable-manifest/src/transform.rs
  • pacquet/crates/git-fetcher/src/lib.rs
  • pacquet/crates/git-fetcher/src/error.rs
  • pacquet/crates/cli/Cargo.toml
  • pacquet/crates/cli/src/cli_args/pack.rs
  • pacquet/crates/pack/src/tests.rs
  • pacquet/crates/exportable-manifest/src/create.rs
  • pacquet/crates/exportable-manifest/src/create/tests.rs
  • pacquet/crates/fs-packlist/src/lib.rs
  • pacquet/crates/pack/src/lib.rs

A symlinked workspace-root LICENSE was followed via fs::metadata, so a
symlink pointing outside the workspace could leak its target's bytes
into a sub-package's tarball. Use DirEntry::file_type (which does not
follow symlinks) so only a regular file is injected, mirroring the
symlink-skipping read_readme_file in exportable-manifest. Add a unix
regression test.

Also pin the empty-string version case in the required-field truthiness
test.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

@zkochan

zkochan commented Jun 25, 2026

Copy link
Copy Markdown
Member

Re: Qodo finding #3 — "Tarball built in memory" (tarball.rs)

Thanks — valid observation, tracking it as a follow-up rather than fixing it in this PR.

pack is not on the hot-path list the REVIEW_GUIDE calls out (install / add / update / remove / resolution / fetching / linking / lockfile / store / pnpr), so the performance bar here is lower, and for typical packages the in-memory build is a few MB. Streaming to a Write would mean evolving the Sys capability seam from FsWrite(path, bytes) to a streaming interface (create_file(path) -> impl Write) and threading file handles through build_tarball and the size pass — a larger, self-contained refactor that's better as its own change than bundled into this command port. Filing it as a follow-up.


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

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 384d827

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
pacquet/crates/fs-packlist/src/tests.rs (1)

720-743: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Solid regression test — it fails without the containment check (the old is_file() on pkg_dir.join("../secret.js") would resolve to the existing outside file and force-include it).

Optional: the symlink branch of is_regular_file (a main/bin symlinking to a file outside the package) is not yet exercised. A second case writing an outside file and symlinking pkg/link.js → ../secret.js would lock in that protection too.

🤖 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/fs-packlist/src/tests.rs` around lines 720 - 743, Add a
regression test around escaping_main_and_bin_fields_are_not_force_included to
cover the symlink path too: create a package-local symlink for a main/bin target
that points outside the package and assert packlist does not force-include the
બહાર file. Use the existing packlist setup in this test to verify the
containment behavior exercised by is_regular_file and the main/bin resolution
logic.
🤖 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/fs-packlist/src/lib.rs`:
- Around line 596-601: The current `is_regular_file`/`is_contained_field_path`
checks do not protect against intermediate symlink traversal, so `main` and
`bin` can still resolve outside the package root. Update the validation in
`build_files_map` (or the helper it uses) to canonicalize the candidate path and
verify the resolved absolute file is strictly within the canonical package
directory before including it. Keep the final regular-file check, but replace or
augment `is_contained_field_path` with this containment check for the
`main`/`bin` path handling.

---

Nitpick comments:
In `@pacquet/crates/fs-packlist/src/tests.rs`:
- Around line 720-743: Add a regression test around
escaping_main_and_bin_fields_are_not_force_included to cover the symlink path
too: create a package-local symlink for a main/bin target that points outside
the package and assert packlist does not force-include the બહાર file. Use the
existing packlist setup in this test to verify the containment behavior
exercised by is_regular_file and the main/bin resolution logic.
🪄 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: ce319d28-6b0b-4108-a2ed-d02aa7db2c59

📥 Commits

Reviewing files that changed from the base of the PR and between e866c43 and 384d827.

📒 Files selected for processing (4)
  • pacquet/crates/fs-packlist/src/lib.rs
  • pacquet/crates/fs-packlist/src/tests.rs
  • pacquet/crates/pack/src/lib.rs
  • pacquet/crates/pack/src/tests.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • pacquet/crates/pack/src/lib.rs
  • pacquet/crates/pack/src/tests.rs

Comment thread pacquet/crates/fs-packlist/src/lib.rs Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 384d827

Recursive pack resolved a shared destination before `api` ran, so the
`--out` branch silently dropped `pack_destination` and the mutually-
exclusive pair was accepted — unlike single-project pack, which rejects
it with ERR_PNPM_INVALID_OPTION. Validate the pair up front in the
recursive path so both modes behave the same.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 878dc37

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 878dc37

Address the remaining Qodo findings on the pack port:

- Stream the gzip+tar archive into the atomic temp file instead of
  buffering the whole archive in a Vec, so peak memory no longer scales
  with the packed size. Per-file reads stay in memory, matching pnpm's
  readFileSync. The FsWrite seam becomes FsAtomicWrite, taking a
  streaming write body.
- Thread Config.unsafe_perm into PackOptions instead of hardcoding
  unsafe_perm = true for prepack/prepare/postpack, so packing honors the
  same policy (and TMPDIR isolation) as pnpm.
- Strip control characters from the text pack output, so a filename with
  raw ANSI escapes can't spoof the terminal. JSON output is left as data.
- Reject an --out value that resolves to no file name (., .., "") up
  front instead of failing later with a confusing OS write error.
- Sort the contents list with one cached lowercase key per item instead
  of recomputing to_lowercase on both sides per comparison, and check
  bin executability against a HashSet instead of a linear scan.

Add regression tests for the --out and control-character cases.
@zkochan

zkochan commented Jun 25, 2026

Copy link
Copy Markdown
Member

Disposition of the remaining findings in Qodo's review summary (these were summary-only, with no inline threads):

# Finding Disposition
1 unsafe_perm hardcoded true Fixed (67bcd63eaa) — PackOptions.unsafe_perm is now threaded from Config.unsafe_perm instead of hardcoded true, so lifecycle scripts honor the same policy/TMPDIR isolation as pnpm.
7 Unbounded README read Declined (parity) — pnpm's readReadmeFile reads the whole file with no size cap either; embed_readme is also always-false today.
8 Recursive flag validation bypass Fixed (878dc37140) — recursive pack now rejects --out + --pack-destination up front, matching single-project pack.
9 Terminal escape injection Fixed (67bcd63eaa) — text output strips control characters from manifest/filesystem-derived paths; JSON output left as data.
10 Invalid --out filename accepted Fixed (67bcd63eaa) — --out ./../"" is rejected with ERR_PNPM_INVALID_OPTION instead of a confusing later write error.
11 Alloc-heavy contents sorting Fixed (67bcd63eaa) — one cached lowercase key per item instead of to_lowercase on both sides per comparison.
12 Quadratic bin mode check Fixed (67bcd63eaa) — bin executability is checked against a HashSet instead of a linear scan.
13 Bin normalization assumes string Declined (unreachable) — pack rejects a non-string name with PackageNameNotFound before transform runs; latent only for a future publish.
14 Tarball built in memory Fixed (67bcd63eaa) — the gzip+tar archive now streams into the atomic temp file instead of buffering the whole Vec; per-file reads stay in memory, matching pnpm's readFileSync.

(#2/#3/#4/#6 were resolved via their inline threads; #5 publishConfig.directory was declined for pnpm parity in its inline thread.)


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

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 67bcd63

Two follow-ups from review:

- The main/bin force-include verified containment only on the path
  string, so an intermediate symlinked directory (subdir -> /outside)
  could still resolve a host file into the packlist. Verify the
  canonical resolved path is strictly inside the canonical package root
  instead, which also follows symlinks that stay in-package (matching
  npm-packlist) while failing closed on any escape.
- The atomic tarball write read the destination's mode with metadata
  (follows symlinks), so a symlink at the output path could donate its
  target's or a directory's mode to the archive. Use symlink_metadata
  and only inherit from an existing regular file, and set the mode
  before syncing so content and metadata flush together.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 67bcd63

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 676729d

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 676729d

…tering

Hardening the shared packlist to drop `..`-escaping main/bin fields
means patch-commit's `prepare_pkg_files_for_diff` no longer receives an
escaping entry, so the old integration test's `expect_err` no longer
fires. Unit-test patch-commit's own `safe_package_file_path` guard
directly (defense in depth), and rework the integration test to assert
the escaping `main` is filtered and never materialized into the diff
view.
@zkochan
zkochan enabled auto-merge June 25, 2026 18:44
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

@zkochan
zkochan added this pull request to the merge queue Jun 25, 2026
Comment on lines +403 to +409
/// Read the raw manifest under `dir`, erroring when it is absent.
fn read_manifest(dir: &Path) -> Result<Value, PackError> {
match safe_read_package_json_from_dir(dir) {
Ok(Some(manifest)) => Ok(manifest),
Ok(None) => Err(PackError::ManifestNotFound { dir: dir.display().to_string() }),
Err(source) => Err(PackError::ReadManifest(source)),
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

1. Symlinked manifest read 🐞 Bug ⛨ Security

pacquet_pack::read_manifest() reads <dir>/package.json via safe_read_package_json_from_dir(),
which uses fs::read_to_string and follows symlinks. An attacker-controlled repo can replace
package.json with a symlink to an out-of-tree JSON file, causing pack to publish attacker-chosen
manifest contents (and potentially leak local JSON data) despite other symlink-hardening in this PR.
Agent Prompt
## Issue description
`pacquet_pack::read_manifest()` accepts a symlinked `package.json` because `safe_read_package_json_from_dir()` reads it via `fs::read_to_string` (symlinks followed). This allows an untrusted repo to point `package.json` outside the project and have `pack` embed attacker-chosen manifest JSON into the produced tarball.

## Issue Context
This PR already explicitly avoids symlink reads for other embedded files (README/license), so `package.json` should follow the same rule.

## Fix Focus Areas
- pacquet/crates/pack/src/lib.rs[403-409]
- pacquet/crates/package-manifest/src/lib.rs[561-569]

## Suggested fix
- Add a non-following check before reading `package.json`:
  - Use `std::fs::symlink_metadata(dir.join("package.json"))` and require `file_type().is_file()` **and** `!file_type().is_symlink()` (or equivalently, reject when `is_symlink()`), returning `Ok(None)`/a typed error if it’s not a regular file.
- Prefer fixing this in `safe_read_package_json_from_dir()` so all call sites (including `pack`) get the same protection, and adjust any tests accordingly.

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

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

Copy link
Copy Markdown

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

Merged via the queue into main with commit 159bd27 Jun 25, 2026
32 checks passed
@zkochan
zkochan deleted the claude/friendly-galileo-aotu46 branch June 25, 2026 19:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

reviewed: coderabbit CodeRabbit submitted an approving review state: automerge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants