Skip to content

feat(pacquet-cli): port the pack-app command - #12669

Merged
zkochan merged 8 commits into
mainfrom
feat/pacquet-pack-app
Jun 25, 2026
Merged

zkochan merged 8 commits into
mainfrom
feat/pacquet-pack-app

Conversation

@zkochan

@zkochan zkochan commented Jun 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Ports pnpm's pack-app command into pacquet (pacquet pack-app). It packs a CommonJS entry file into a standalone executable for one or more target platforms, embedding a Node.js binary through the Node.js Single Executable Applications (SEA) API.

The command reads defaults from package.json's pnpm.app field (entry, targets, runtime, outputDir, outputName), resolves the embedded Node.js version against nodejs.org, downloads the per-target runtime, runs node --build-sea, and ad-hoc signs macOS binaries — matching pnpm's behavior, flags, defaults, and ERR_PNPM_PACK_APP_* error codes.

It reuses pacquet's existing infrastructure: node-version resolution (parse_node_specifier / get_node_mirror / resolve_node_version), ThrottledClient (same proxy/TLS/timeout config as installs), detect-libc for host platform/arch/libc, and node@runtime: installs through pacquet's own add.

Two intentional divergences from the pnpm source, both forced by pacquet being a Rust binary rather than a Node.js script (documented in the module doc comment):

  1. The SEA builder is always downloaded. pnpm reuses its own running interpreter (process.execPath) when it already matches the embedded runtime version; pacquet has no host Node.js to reuse.
  2. The runtime install spawns the pacquet binary (std::env::current_exe() running add --os/--cpu/--libc node@runtime:<version> into an isolated directory under the pnpm home), mirroring pnpm's runPnpmCli.

Known gaps (noted in code):

  • pacquet's Config has no node-download-mirrors field yet, so version resolution always uses the official nodejs.org mirror (matches pnpm's default when unset).
  • The spawned add omits pnpm's --ignore-scripts / --ignore-workspace (pacquet's add lacks those flags). Harmless for node@runtime under the pnpm home.

Ported from 9f3df6b9b4.

Squash Commit Body

feat(pacquet-cli): port the `pack-app` command

Ports pnpm's `pack-app` command into pacquet. It packs a CommonJS entry
file into a standalone executable for one or more target platforms,
embedding a Node.js binary through the Node.js Single Executable
Applications API.

Reuses pacquet's node-version resolution, network client, detect-libc,
and `node@runtime:` installs. Two intentional divergences from pnpm,
both forced by pacquet being a Rust binary rather than a Node.js script:
the SEA builder is always downloaded (pnpm reuses its running
interpreter), and the runtime install spawns the pacquet binary
(mirroring pnpm's runPnpmCli).

Ports the upstream Jest validation suite (17 tests) covering the
fail-fast branches. The download / SEA-injection / signing paths need
network, Node.js, and subprocesses and are out of unit-test scope,
matching upstream coverage.

Ported from pnpm/pnpm@9f3df6b9b4.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pacquet/ port, or the description notes what still needs porting.
    (pack-app already exists in the TypeScript CLI; this PR ports it to pacquet.)
  • Added or updated tests.

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

Summary by CodeRabbit

  • New Features
    • Added a pack-app CLI command to bundle a CommonJS entry into standalone executables for supported targets, with configurable entry, targets, Node runtime, and output directory/name (auto output-name discovery from package.json).
  • Bug Fixes
    • Hardened --entry and --output-dir handling: absolute paths and paths escaping the project directory (including .. and symlink escapes) are now rejected with new error codes.
    • Improved signing for macOS outputs based on the execution host.
  • Tests
    • Added fail-fast validation tests for CLI/config inputs, including path-containment rejection (absolute/traversal/symlink cases).

@coderabbitai

coderabbitai Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a pack-app CLI subcommand that reads pnpm.app defaults, validates entry, target, runtime, and output settings, builds SEA executables per target, and adds path-containment checks plus validation coverage.

Changes

pack-app command and path containment

Layer / File(s) Summary
CLI wiring
pacquet/crates/cli/Cargo.toml, pacquet/crates/cli/src/cli_args.rs
Adds the workspace dependencies, exports the new module, registers the pack-app subcommand, and dispatches it through CliArgs::run.
Pack-app implementation
pacquet/crates/cli/src/cli_args/pack_app.rs
Defines PackAppArgs and PackAppError, reads pnpm.app, validates and derives inputs, resolves runtime and builder versions, provisions Node runtimes, runs SEA builds, and re-signs darwin outputs.
Path containment hardening
.changeset/pack-app-path-containment.md, pnpm11/releasing/commands/src/pack-app/packApp.ts
Updates pack-app to reject absolute and escaping entry and outputDir paths, adds realpath containment checks, and documents the new error codes in release metadata.
Validation tests
pacquet/crates/cli/src/cli_args/pack_app/tests.rs, pnpm11/releasing/commands/test/pack-app/index.test.ts
Adds Rust and TypeScript tests for fail-fast validation, config parsing, target and runtime parsing, output-name rules, and path escape rejection.

Sequence Diagram(s)

sequenceDiagram
  participant CliArgsRun
  participant PackAppArgs
  participant Config
  participant NodeResolver
  participant CommandRunner
  participant MacSigner

  CliArgsRun->>PackAppArgs: args.run(cfg, dir_ref)
  PackAppArgs->>Config: read pnpm.app defaults
  PackAppArgs->>NodeResolver: resolve runtime version
  PackAppArgs->>CommandRunner: install cached node runtime
  PackAppArgs->>CommandRunner: run --build-sea
  PackAppArgs->>MacSigner: sign darwin outputs
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested labels

product: pnpm@11, product: pacquet

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

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

❤️ Share

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

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

Copy link
Copy Markdown

PR Summary by Qodo

feat(cli): port pnpm pack-app as pacquet pack-app (SEA executables)
✨ Enhancement 🧪 Tests ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

Description

• Add pacquet pack-app to build SEA-based standalone executables from a CJS entry.
• Resolve/download matching Node.js runtimes per target and run node --build-sea.
• Add validation + config parsing with pnpm-compatible ERR_PNPM_PACK_APP_* codes.
Diagram

graph TD
U["User / CI"] --> C["pacquet CLI"] --> P["pack-app cmd"] --> J["Read package.json\n(pnpm.app)"] --> V{"Validate\nentry/targets/names"} --> R["Resolve Node version\n(nodejs.org)"] --> I["Install node@runtime\n(spawn pacquet add)"] --> B["Build SEA\nnode --build-sea"] --> S{"darwin target?"} -->|"yes"| M["Ad-hoc sign\ncodesign/ldid"] --> O["Write executables\ndist-app/<target>"]
S -->|"no"| O
subgraph Legend
direction LR
_user["Actor"] ~~~ _proc["Process"] ~~~ _dec{"Decision"}
end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Download Node runtimes directly (avoid spawning `pacquet add`)
  • ➕ Avoids recursive CLI invocation and its future flag/behavior drift
  • ➕ More predictable install layout and fewer moving parts
  • ➕ Potentially faster for pack-app-only usage (no pnpm-home install graph)
  • ➖ Duplicates pacquet's existing install/store/hardlink caching behavior
  • ➖ Must re-implement proxy/TLS/CA-store and integrity handling correctly
  • ➖ Loses parity with pnpm’s approach of leveraging package installs
2. Require a system Node for SEA building (skip builder download)
  • ➕ Eliminates one download (host-arch builder runtime)
  • ➕ Simplifies build_root caching and reduces disk usage
  • ➖ Breaks pnpm parity and makes the command less hermetic
  • ➖ Hard to ensure builder version exactly matches embedded runtime
  • ➖ Worse UX in CI/containers that intentionally omit Node
3. Integrate a dedicated SEA builder crate/tooling wrapper
  • ➕ Could encapsulate SEA config writing + subprocess management cleanly
  • ➕ Easier to reuse for future commands (e.g., pack extensions, validate SEA)
  • ➖ Adds abstraction overhead for a single-command feature
  • ➖ May obscure the goal of staying close to pnpm behavior and error codes

Recommendation: Keep the current approach: reusing pacquet’s node version resolver + ThrottledClient, and using a self-spawned pacquet add node@runtime: best preserves caching, proxy/TLS behavior, and pnpm parity while keeping the implementation contained. If recursion becomes problematic later (e.g., flags/env drift), the most viable follow-up would be to factor runtime acquisition into an internal library API rather than downloading runtimes ad-hoc.

Files changed (4) +1041 / -0

Enhancement (2) +800 / -0
cli_args.rsRegister and dispatch new 'pack-app' subcommand +15/-0

Register and dispatch new 'pack-app' subcommand

• Introduces the 'pack-app' clap subcommand, imports 'PackAppArgs', and wires execution through the config-only dispatch path (no lockfile/install pipeline).

pacquet/crates/cli/src/cli_args.rs

pack_app.rsImplement 'pacquet pack-app' SEA packaging workflow +785/-0

Implement 'pacquet pack-app' SEA packaging workflow

• Adds a full Rust port of pnpm’s 'pack-app': reads 'pnpm.app' defaults, validates entry/targets/runtime/output name with pnpm-compatible diagnostics, resolves an exact Node version, installs per-target 'node@runtime' by spawning 'pacquet add', runs 'node --build-sea', and ad-hoc signs darwin outputs (codesign/ldid).

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

Tests (1) +239 / -0
tests.rsPort pnpm validation tests for fail-fast branches +239/-0

Port pnpm validation tests for fail-fast branches

• Adds unit tests covering config parsing and fail-fast validation (missing/invalid entry, targets, runtime, output name, and 'pnpm.app' shape), asserting pnpm-style 'ERR_PNPM_PACK_APP_*' diagnostic codes.

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

Other (1) +2 / -0
Cargo.tomlAdd dependencies needed for 'pack-app' platform/runtime resolution +2/-0

Add dependencies needed for 'pack-app' platform/runtime resolution

• Adds 'pacquet-detect-libc' for host OS/arch/libc detection and 'pacquet-engine-runtime-node-resolver' for Node.js version resolution against mirrors.

pacquet/crates/cli/Cargo.toml

@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 (15) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Signer PATH hijack 🐞 Bug ⛨ Security
Description
ad_hoc_sign_mac_binary spawns codesign/ldid by bare name, so the resolved executable comes
from PATH. If PATH includes a repo-controlled directory (commonly node_modules/.bin in dev/CI
shells), a malicious repo/dependency can get an attacker-provided ldid/codesign executed when
packaging darwin targets.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R897-905]

+        "darwin" => run_command(
+            Command::new("codesign").arg("--sign").arg("-").arg(output_file),
+            "codesign",
+        ),
+        "linux" => {
+            run_command(Command::new("ldid").arg("-S").arg(output_file), "ldid").map_err(|_| {
+                PackAppError::MacosSignFailed { path: output_file.display().to_string() }.into()
+            })
+        }
Evidence
The code uses PATH-based command resolution for signing tools, which is exactly the class of risk
the repo’s review guide highlights (executable resolution / environment trust).

pacquet/crates/cli/src/cli_args/pack_app.rs[892-905]
REVIEW_GUIDE.md[50-55]

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

## Issue description
`ad_hoc_sign_mac_binary` invokes `codesign` and `ldid` via `Command::new("codesign")` / `Command::new("ldid")`, which relies on PATH lookup. In environments where PATH includes repo-controlled locations (e.g. `node_modules/.bin`), this can be exploited to execute an attacker-controlled binary during `pacquet pack-app`.
### Issue Context
This command is explicitly intended to be runnable in potentially untrusted repositories (it reads repo-controlled `package.json` and builds executables). The repo’s security guidance calls out executable resolution + environment-variable trust as a priority.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[892-905]
### Suggested fix
- Prefer absolute, platform-known paths where possible (e.g. on macOS use `/usr/bin/codesign`).
- For `ldid` (no universal absolute location), resolve to an absolute path first (e.g. via `which::which("ldid")`) and *reject* resolutions inside the project directory / `node_modules/.bin` (or more generally inside the current workspace), then execute using the resolved absolute path.
- Optionally: allow an explicit override (env var or CLI flag) to point to a trusted `ldid` path, bypassing PATH lookup entirely.

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


2. Output file symlink escape 🐞 Bug ⛨ Security
Description
pack-app verifies outputDir and dist-app/ stay within the project, but it never rejects a
pre-existing symlink at the final executable path (dist-app//[.exe]). node --build-sea will then
write via that symlink, allowing an untrusted repo to overwrite arbitrary files outside the project
when a developer runs pack-app.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R395-429]

+            let output_file = if target.platform == "win32" {
+                target_output_dir.join(format!("{output_name}.exe"))
+            } else {
+                target_output_dir.join(&output_name)
+            };
+
+            let sea_config = serde_json::json!({
+                "main": resolved_entry,
+                "output": output_file,
+                "executable": embedded_node_bin,
+                "disableExperimentalSEAWarning": true,
+                "useCodeCache": false,
+                "useSnapshot": false,
+            });
+            // Write the SEA config into a fresh, unpredictable temp
+            // directory (0700 by default) rather than a predictable path
+            // under the system temp dir. Avoids TOCTOU/symlink attacks on
+            // multi-user systems.
+            let tmp_config_dir = tempfile::Builder::new()
+                .prefix("pacquet-pack-app-")
+                .tempdir()
+                .into_diagnostic()
+                .wrap_err("creating a temp directory for the SEA config")?;
+            let config_path = tmp_config_dir.path().join("sea-config.json");
+            fs::write(
+                &config_path,
+                serde_json::to_vec_pretty(&sea_config).expect("serialize SEA config"),
+            )
+            .into_diagnostic()
+            .wrap_err("writing the SEA config")?;
+
+            run_command(
+                Command::new(&builder_bin).arg("--build-sea").arg(&config_path),
+                "node --build-sea",
+            )?;
Evidence
The Rust and TS implementations both pass the computed output_file directly into the SEA config
(output) and then execute the builder, without any lstat/symlink check on that final path. The
repo already documents why symlink_metadata checks are needed to prevent symlink routing on
writes.

pacquet/crates/cli/src/cli_args/pack_app.rs[381-429]
pnpm11/releasing/commands/src/pack-app/packApp.ts[241-276]
pacquet/crates/fs/src/ensure_file.rs[254-266]

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

## Issue description
`pack-app` ensures the output directory and per-target subdirectory are contained within the project, but it doesn't validate the final output executable path. If `dist-app/<target>/<name>` already exists as a symlink (committed by a malicious repo), `node --build-sea` can follow it and overwrite files outside the project.
### Issue Context
This is a classic “leaf symlink” escape: directory containment checks do not prevent an attacker from placing a symlink at the *file* being written.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[381-433]
- pnpm11/releasing/commands/src/pack-app/packApp.ts[241-286]
### Suggested fix
1. Before invoking the SEA builder, check `output_file`/`outputFile` with `symlink_metadata`/`lstat`:
- If it exists and is a symlink (or any non-regular file), abort with a pack-app error.
- If it exists and is a regular file, allow overwrite (current behavior) or delete it explicitly.
2. Add a unit test mirroring the existing `output_dir` symlink tests: create `dist-app/<target>/app` as a symlink to an outside temp file and assert the command fails before build work.

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


3. Unverified cached Node binary 🐞 Bug ⛨ Security
Description
ensure_node_runtime() returns a cached Node binary solely based on binary_path.exists(), and
pack-app later executes that path as the SEA builder. If PNPM_HOME (or its pack-app subdir) is
shared/attacker-writable, a malicious preplaced binary at that path will be executed when the user
runs pacquet pack-app.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R527-532]

+    let install_dir = build_root.join(format!("{target_id}-{version}"));
+    let node_dir = install_dir.join("node_modules").join("node");
+    let binary_path = node_binary_path(&node_dir, platform);
+    if binary_path.exists() {
+        return Ok(binary_path);
+    }
Evidence
The code short-circuits solely on file existence, and the returned path is later executed. The cache
root is derived from pnpm_home_dir(), which is overrideable via PNPM_HOME, making
shared/writable cache scenarios plausible.

pacquet/crates/cli/src/cli_args/pack_app.rs[356-365]
pacquet/crates/cli/src/cli_args/pack_app.rs[466-489]
pacquet/crates/cli/src/cli_args/pack_app.rs[513-532]
pacquet/crates/cli/src/cli_args/pack_app.rs[426-429]
pacquet/crates/config/src/defaults.rs[124-151]

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

## Issue description
`ensure_node_runtime()` treats a runtime as "installed" if the expected binary path exists, without validating it is a regular file, the expected Node version, or a trustworthy artifact. That path is later executed as the SEA builder (`Command::new(&builder_bin)`), creating a cache-poisoning RCE primitive when the pnpm home is shared or writable by another principal.
## Issue Context
- The cache lives under `pnpm_home_dir()/pack-app`, and `pnpm_home_dir` is environment-overridable via `PNPM_HOME`.
- `binary_path.exists()` is not a sufficient trust signal for an executable that will be spawned.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[513-572]
- pacquet/crates/cli/src/cli_args/pack_app.rs[426-429]
- pacquet/crates/config/src/defaults.rs[124-151]
## Suggested change
- Replace the `binary_path.exists()` fast-path with validation such as:
- `symlink_metadata` + `is_file` (reject symlinks), and
- execute `binary_path --version` (or `-p process.versions.node`) and require it matches `version` (or is semver-equal after normalization).
- Consider writing/reading an install success marker (e.g. `<install_dir>/.installed`) created only after a successful `pacquet add`, and/or verifying directory permissions/ownership (fail closed if group/other-writable) when under `PNPM_HOME`.
- If validation fails, reinstall into a fresh temp dir and atomically rename into place (also helps with partial installs).

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


View more (5)
4. Windows path escape bypass 🐞 Bug ⛨ Security
Description
pathEscapesProject() only rejects path.isAbsolute() and .. segments, so Windows drive-relative
paths like C:foo are not rejected and can resolve outside the project. Because outputDir is
mkdir()’d before isWithinDir() runs, a repo-controlled pnpm.app.outputDir can still cause
filesystem writes (directory creation) outside the workspace on Windows before the command errors
out.
Code

pnpm11/releasing/commands/src/pack-app/packApp.ts[R592-595]

+function pathEscapesProject (rawPath: string): boolean {
+  if (path.isAbsolute(rawPath)) return true
+  return rawPath.split(/[/\\]/).includes('..')
+}
Evidence
The new TypeScript guard only checks path.isAbsolute() and .., which does not cover Windows
drive-relative paths. The command then mkdirs outputDir before the later isWithinDir()
realpath check, so the bypass can still cause side-effectful writes outside the project. The Rust
port’s comment explicitly calls out drive-relative forms as needing special handling, underscoring
the TS mismatch.

pnpm11/releasing/commands/src/pack-app/packApp.ts[587-595]
pnpm11/releasing/commands/src/pack-app/packApp.ts[194-211]
pacquet/crates/cli/src/cli_args/pack_app.rs[617-628]

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

## Issue description
`pnpm11/releasing/commands/src/pack-app/packApp.ts` introduced `pathEscapesProject()` as a fail-fast, side-effect-free lexical guard, but it doesn’t reject Windows drive-relative paths (e.g. `C:foo`). On Windows, these are not absolute (`path.isAbsolute()` returns false) and may not contain `..`, yet they can still resolve outside the project.
Because `outputDir` is created with `mkdir(..., { recursive: true })` before the realpath-based containment check, this bypass can still create directories outside the project before aborting.
### Issue Context
The Rust port explicitly accounts for Windows root-/drive-relative forms by rejecting `Component::RootDir` and `Component::Prefix(_)`, highlighting the mismatch in the TypeScript implementation.
### Fix Focus Areas
- pnpm11/releasing/commands/src/pack-app/packApp.ts[592-595]
- pnpm11/releasing/commands/src/pack-app/packApp.ts[194-211]
### Implementation notes
Update `pathEscapesProject()` to also reject Windows root/drive-prefixed forms, not just `path.isAbsolute()` and `..`.
One robust approach is to reject any non-empty root under both path flavors:
- `path.parse(rawPath).root !== ''` (host semantics)
- `path.win32.parse(rawPath).root !== ''` (Windows semantics even when running elsewhere)
Additionally, keep the `..` segment check.
Add/adjust tests in `pnpm11/releasing/commands/test/pack-app/index.test.ts` to cover Windows-specific bypass strings like `C:foo` (and optionally `C:foo\\bar`).

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


5. OutputDir symlink escape 🐞 Bug ⛨ Security
Description
pacquet pack-app rejects absolute/.. in output_dir_raw but never verifies that the resolved
output_dir (or output_dir/) stays within the project after symlink resolution, so a repo can
symlink dist-app (or a target subdir) to write artifacts outside the workspace. This contradicts
the changeset’s stated behavior and creates an arbitrary write-outside-project primitive when
running pack-app in an untrusted repo.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R334-378]

+        // `outputDir` is likewise repo-controllable; reject absolute paths
+        // and `..` traversal so build artifacts cannot be written outside the
+        // project directory.
+        let output_dir_raw = self
+            .output_dir
+            .clone()
+            .or_else(|| project.app.as_ref().and_then(|app| app.output_dir.clone()))
+            .unwrap_or_else(|| "dist-app".to_string());
+        if escapes_project(&output_dir_raw) {
+            return Err(PackAppError::OutputDirOutsideProject { path: output_dir_raw }.into());
+        }
+        let output_dir = dir.join(&output_dir_raw);
+        fs::create_dir_all(&output_dir)
+            .into_diagnostic()
+            .wrap_err_with(|| format!("creating output directory {}", output_dir.display()))?;
+
+        let build_root = pnpm_home_dir()?.join("pack-app");
+
+        // Resolve the embedded target version first so the builder can be
+        // pinned to the same version. SEA blobs carry no version header and
+        // the serialized format has changed across Node.js minor releases,
+        // so a blob produced by a builder of a different version than the
+        // embedded runtime fails deserialization at startup.
+        let resolved_target_version = resolve_version(config, &requested_node_spec).await?;
+        let builder_bin = resolve_builder_binary(&build_root, &resolved_target_version)?;
+
+        let pacquet_bin = std::env::current_exe()
+            .into_diagnostic()
+            .wrap_err("resolving the pacquet executable path")?;
+
+        let mut results = Vec::with_capacity(targets.len());
+        for target in &targets {
+            let embedded_node_bin = ensure_node_runtime(
+                &pacquet_bin,
+                &build_root,
+                &resolved_target_version,
+                &target.platform,
+                &target.arch,
+                target.libc.as_deref(),
+            )?;
+
+            let target_output_dir = output_dir.join(&target.raw);
+            fs::create_dir_all(&target_output_dir).into_diagnostic().wrap_err_with(|| {
+                format!("creating target output directory {}", target_output_dir.display())
+            })?;
Evidence
Rust validates entry with a symlink-aware containment check (path_is_within), but for
outputDir it only checks escapes_project and then creates/uses the directory without any
canonicalization-based containment check; therefore a symlinked dist-app (or dist-app/) can
redirect writes outside the project. The changeset explicitly claims symlink escapes for outputDir
are rejected, which is not enforced by the current code (and TS similarly only does lexical
validation for outputDir).

pacquet/crates/cli/src/cli_args/pack_app.rs[269-297]
pacquet/crates/cli/src/cli_args/pack_app.rs[334-378]
.changeset/pack-app-path-containment.md[1-6]
pnpm11/releasing/commands/src/pack-app/packApp.ts[194-204]

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

## Issue description
`outputDir` is only protected by a lexical check (`escapes_project`) and then used with `create_dir_all` and further `join`s. If `dist-app` (or `dist-app/<target>`) is a symlink to a location outside the project, `pack-app` will write build outputs outside the workspace.
This also conflicts with the changeset text that claims symlink escapes are rejected for `outputDir`.
## Issue Context
The entry path already performs a defense-in-depth realpath containment check via `path_is_within`, but output directories do not.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[334-378]
- pnpm11/releasing/commands/src/pack-app/packApp.ts[194-204]
- .changeset/pack-app-path-containment.md[1-6]
## Implementation notes
- After `fs::create_dir_all(&output_dir)`, require `path_is_within(&output_dir, dir)`; on failure, return `PackAppError::OutputDirOutsideProject { path: output_dir_raw }`.
- Do the same for `target_output_dir` (after creating it), so a repo-controlled symlink at `dist-app/<target>` can’t redirect writes.
- Mirror the same behavior in the TS implementation (after `await mkdir(outputDir, { recursive: true })`, validate with `isWithinDir(outputDir, opts.dir)`; and consider validating `targetOutputDir` similarly).
- Add a unit test covering symlinked outputDir/targetOutputDir escape (skip on platforms where symlink creation requires privileges, if needed).

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


6. Entry path escapes project 🐞 Bug ⛨ Security
Description
PackAppArgs::run accepts pnpm.app.entry (repo-controlled) and resolves it via
dir.join(entry_path) without rejecting absolute paths or .., so running pacquet pack-app in an
untrusted repo can embed arbitrary local files outside the workspace into the produced executable.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R245-255]

+        let entry_path = self
+            .entry
+            .clone()
+            .or_else(|| self.params.first().cloned())
+            .or_else(|| project.app.as_ref().and_then(|app| app.entry.clone()))
+            .ok_or(PackAppError::MissingEntry)?;
+        let resolved_entry = dir.join(&entry_path);
+        let entry_meta = fs::metadata(&resolved_entry).map_err(|_| {
+            PackAppError::EntryNotFound { path: resolved_entry.display().to_string() }
+        })?;
+        if !entry_meta.is_file() {
Evidence
The code selects entry_path from CLI params or pnpm.app.entry, then uses dir.join(&entry_path)
directly; Rust Path::join will drop the base when the RHS is absolute and will not prevent ..
traversal. The repo’s security guide explicitly treats manifests and filesystem paths as
attacker-controlled and calls out traversal/root escape as a primary class to reject.

pacquet/crates/cli/src/cli_args/pack_app.rs[245-255]
REVIEW_GUIDE.md[30-46]
REVIEW_GUIDE.md[79-82]

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

## Issue description
`pnpm.app.entry` (and `--entry`) are treated as attacker-controlled per the repo security rules, but the current code resolves the entry by `dir.join(entry_path)` and only checks that the resulting path exists and is a file. This allows absolute paths (which ignore `dir`) and `..` traversal segments to escape the project directory and read/embed arbitrary host files.
### Issue Context
This command intentionally reads defaults from `package.json` (untrusted input). The entry path becomes the SEA config "main" and will be consumed by the downloaded Node builder, so containment needs to be enforced at the CLI layer.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[245-259]
### Suggested fix
- Reject absolute `entry_path` values.
- Canonicalize both `dir` and `resolved_entry` (`std::fs::canonicalize`) and require `resolved_entry.starts_with(dir)`.
- Consider also rejecting any `ParentDir` (`..`) path component before filesystem access, so you fail fast even if the path doesn’t exist.

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


7. OutputDir escapes project 🐞 Bug ⛨ Security
Description
PackAppArgs::run uses pnpm.app.outputDir (from a repo-controlled package.json) to compute
output_dir via dir.join(...) and then writes outputs under it; absolute paths or .. segments
can escape the project directory and cause arbitrary filesystem writes as the invoking user. This
violates the repo’s security rules around traversal/root-escape in write destinations.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R282-290]

+        let output_dir = dir.join(
+            self.output_dir
+                .clone()
+                .or_else(|| project.app.as_ref().and_then(|app| app.output_dir.clone()))
+                .unwrap_or_else(|| "dist-app".to_string()),
+        );
+        fs::create_dir_all(&output_dir)
+            .into_diagnostic()
+            .wrap_err_with(|| format!("creating output directory {}", output_dir.display()))?;
Evidence
The command reads outputDir from pnpm.app as an unconstrained string and passes it into
dir.join(...) and create_dir_all, which will honor absolute paths and relative traversal
segments, enabling writes outside the project directory. The review guide explicitly calls out
traversal/root-escape write destinations as a security concern.

pacquet/crates/cli/src/cli_args/pack_app.rs[282-290]
pacquet/crates/cli/src/cli_args/pack_app.rs[677-720]
REVIEW_GUIDE.md[79-82]

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

## Issue description
`pnpm.app.outputDir` is treated as an arbitrary string and used to build a write destination via `dir.join(...)` and `create_dir_all`, allowing project-controlled config to write outside the project root (absolute path override or `..` traversal).
### Issue Context
This command explicitly reads defaults from `package.json` (`pnpm.app.*`), which the review guide treats as attacker-controlled input; write destinations must reject traversal and root escape.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[282-290]
- pacquet/crates/cli/src/cli_args/pack_app.rs[677-720]
### Suggested fix
- Add a `validate_output_dir(dir: &Path, raw: &str) -> Result<PathBuf, PackAppError>` that rejects:
- absolute paths / Windows prefixes
- any `Component::ParentDir` (`..`)
- (optionally) `Component::CurDir` if you want to disallow `./...`
- Apply this validation to the value coming from `pnpm.app.outputDir` (and consider applying it to `--output-dir` too unless you intentionally allow absolute writes from CLI).
- Add unit tests mirroring the output-name tests (e.g. `outputDir: "../../pwn"`, `outputDir: "/tmp/pwn"`).

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


8. Unvalidated version in paths 🐞 Bug ⛨ Security
Description
The resolved Node.js version string is used verbatim when constructing install_dir under
pnpmHomeDir/pack-app, so a malformed/attacker-influenced index.json “latest” entry (triggered by
node@release/node@latest) could inject path separators or .. and escape the intended cache
directory. This creates an arbitrary path write primitive via create_dir_all/write(package.json)
and can redirect which binary gets executed later in the build.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R461-466]

+    let libc = if platform == "linux" { Some(libc.unwrap_or("glibc")) } else { libc };
+    let target_id =
+        [Some(platform), Some(arch), libc].into_iter().flatten().collect::<Vec<_>>().join("-");
+    let install_dir = build_root.join(format!("{target_id}-{version}"));
+    let node_dir = install_dir.join("node_modules").join("node");
+    let binary_path = node_binary_path(&node_dir, platform);
Evidence
ensure_node_runtime formats install_dir using the resolved version string, making the version
a path component. resolve_node_version’s latest branch returns the first index.json entry’s
version without semver parsing/validation, so a malformed first entry can flow into install_dir.

pacquet/crates/cli/src/cli_args/pack_app.rs[457-509]
pacquet/crates/engine-runtime-node-resolver/src/resolve_node_version.rs[75-86]
pacquet/crates/engine-runtime-node-resolver/src/resolve_node_version.rs[120-150]

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

## Issue description
`pack-app` uses the resolved Node.js version string in filesystem path construction (`install_dir = build_root.join(format!("{target_id}-{version}"))`). Today, `resolve_node_version()` can return the first `index.json` entry for `latest` selectors without semver validation, so a compromised/malicious mirror response could return a version containing path separators / `..` and cause writes outside `pnpmHomeDir/pack-app`.
## Issue Context
This is reachable when the runtime specifier ends up resolving to a `latest` selector (e.g. `--runtime node@release`, `--runtime node@latest`, or channel-only forms produced by `parse_node_specifier`). The returned string is then used as a path component and as an identifier in subsequent steps.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[457-509]
- pacquet/crates/engine-runtime-node-resolver/src/resolve_node_version.rs[75-86]
- pacquet/crates/engine-runtime-node-resolver/src/resolve_node_version.rs[120-150]
### Suggested implementation direction
- **Best layer**: harden `resolve_node_version()` to only ever return versions that parse as `node_semver::Version` (or at minimum match a strict allowlist like `^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$`).
- In the `is_latest_selector` branch, instead of returning `first()`, return the **first entry whose `version` parses**.
- Add a **defense-in-depth** check in `pack_app::resolve_version()` or before `ensure_node_runtime()` to reject any version containing `/`, `\\`, or `..` path components before using it in `install_dir`.
- Keep error behavior consistent: if no valid semver exists, treat it as “version not found” (or add a dedicated diagnostic) rather than proceeding.

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



Remediation recommended

9. Dropped npmrc override flag 🐞 Bug ⛨ Security
Description
ensure_node_runtime() spawns pacquet add node@runtime: without forwarding the user-provided
--npmrc-auth-file, so the child process may read a different user-level .npmrc (and thus
different auth/TLS/proxy config) than the parent pack-app invocation. This can break expected
behavior in CI/sandboxed runs that rely on --npmrc-auth-file to avoid using the machine’s default
~/.npmrc.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R575-586]

+    let mut command = Command::new(pacquet_bin);
+    command
+        .arg("-C")
+        .arg(&install_dir)
+        .arg("add")
+        .arg(format!("--os={platform}"))
+        .arg(format!("--cpu={arch}"));
+    if let Some(libc) = libc {
+        command.arg(format!("--libc={libc}"));
+    }
+    command.arg(format!("node@runtime:{version}"));
+    run_command(&mut command, "pacquet add node@runtime")?;
Evidence
The pack-app implementation constructs the child pacquet add command without any
--npmrc-auth-file argument, even though the CLI defines --npmrc-auth-file as a global option
that changes which user-level .npmrc is used. Config::current resolves the user npmrc path with
npmrc_auth_file as the top-precedence input, so dropping the flag changes the child’s config
resolution.

pacquet/crates/cli/src/cli_args/pack_app.rs[575-586]
pacquet/crates/cli/src/cli_args.rs[114-124]
pacquet/crates/config/src/lib.rs[1904-1915]

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

## Issue description
`ensure_node_runtime()` re-invokes the pacquet binary to run `add node@runtime:<version>` but only forwards `-C`, `--os`, `--cpu`, and `--libc`. It does **not** forward the caller’s global `--npmrc-auth-file` override, so the child invocation can load a different user-level `.npmrc` than the parent command.
This causes config divergence (auth/TLS/proxy) and can break workflows that intentionally isolate credentials/config by passing `--npmrc-auth-file`.
## Issue Context
- The CLI explicitly supports `--npmrc-auth-file` as the highest-precedence source for selecting the user-level npmrc.
- `pack-app` is spawning a second pacquet process; without flag propagation, global config overrides don’t carry over.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[537-596]
## Suggested fix
- Thread the parent’s resolved npmrc auth file path into `ensure_node_runtime(...)` (e.g., add a `npmrc_auth_file: Option<&Path>` parameter, or pass it via the `Config` already available in `PackAppArgs::run`).
- When building the child `Command`, if the value is present, append:
- `--npmrc-auth-file <path>`
This keeps the spawned `add` behavior consistent with the parent invocation’s explicit configuration overrides.

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


10. Entry IO errors masked 🐞 Bug ☼ Reliability
Description
PackAppArgs::run maps any fs::metadata() failure for the entry path to
ERR_PNPM_PACK_APP_ENTRY_NOT_FOUND, which misreports permission/IO failures as “not found”. This
can send users down the wrong remediation path and obscures real filesystem problems.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R283-286]

+        let resolved_entry = dir.join(&entry_path);
+        let entry_meta = fs::metadata(&resolved_entry).map_err(|_| {
+            PackAppError::EntryNotFound { path: resolved_entry.display().to_string() }
+        })?;
Evidence
The entry validation explicitly discards the underlying fs::metadata error (map_err(|_| ...)),
so non-NotFound failures cannot be distinguished from “missing”. Elsewhere in the repo, file readers
treat NotFound specially but propagate other IO errors, indicating the expected behavior is to
preserve error kinds.

pacquet/crates/cli/src/cli_args/pack_app.rs[283-286]
pacquet/crates/workspace/src/manifest.rs[123-127]

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::metadata(&resolved_entry)` errors are currently collapsed into `PackAppError::EntryNotFound`, which hides important IO error kinds (e.g. permission denied, transient IO failure) and produces misleading diagnostics.
### Issue Context
This happens in `PackAppArgs::run` during entry validation.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[283-286]
### Implementation notes
- Match on the `io::ErrorKind` from `fs::metadata`.
- Only translate `ErrorKind::NotFound` into `PackAppError::EntryNotFound`.
- For other error kinds, return a diagnostic that preserves the original error (either via a new `PackAppError` variant that carries a `source: io::Error`, or via `IntoDiagnostic`/`wrap_err_with` so miette shows the OS error).

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


11. package.json read errors ignored 🐞 Bug ☼ Reliability
Description
read_project_app_config treats any package.json read failure as “no manifest” and silently falls
back to defaults. This masks permission/encoding/disk errors and can make pack-app behave as if
pnpm.app and name are unset when the real issue is an unreadable file.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R744-748]

+fn read_project_app_config(dir: &Path) -> Result<ReadProjectAppConfigResult, PackAppError> {
+    let manifest_path = dir.join("package.json");
+    let Ok(raw) = fs::read_to_string(&manifest_path) else {
+        return Ok(ReadProjectAppConfigResult::default());
+    };
Evidence
The code returns default config on any read_to_string error, so read failures are
indistinguishable from “no package.json”. The repo’s workspace manifest reader documents and
implements the expected pattern: only NotFound maps to “missing”, while other read errors propagate.

pacquet/crates/cli/src/cli_args/pack_app.rs[744-748]
pacquet/crates/workspace/src/manifest.rs[114-127]

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

## Issue description
`read_project_app_config` currently returns `Ok(default)` for *any* `fs::read_to_string(package.json)` failure, not just "file missing". This silently disables repo config and hides real IO failures.
### Issue Context
This affects defaults for `pnpm.app.*` and output-name derivation (package `name`).
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[744-748]
### Implementation notes
- Change the `let Ok(raw) = ... else { ... }` to a `match`.
- Return `Ok(default)` only for `io::ErrorKind::NotFound`.
- For other errors, return a structured error (likely reusing `ERR_PNPM_PACK_APP_INVALID_PACKAGE_JSON` with a message like `failed to read package.json: ...`, or introducing a dedicated read-failure variant/code if that better matches pnpm parity).

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


View more (4)
12. Non-atomic cache manifest write 🐞 Bug ☼ Reliability
Description
ensure_node_runtime writes PNPM_HOME/pack-app/.../package.json via fs::write, so a
crash/kill/disk-full can leave a truncated manifest in the persistent pnpm-home cache and break
later runs until the directory is cleaned. The repo has established temp-file+rename patterns for
atomic manifest writes, but this code path doesn’t use them.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R534-549]

+    fs::create_dir_all(&install_dir).into_diagnostic().wrap_err_with(|| {
+        format!("creating the runtime install directory {}", install_dir.display())
+    })?;
+    fs::write(
+        install_dir.join("package.json"),
+        format!(
+            "{}\n",
+            serde_json::to_string_pretty(&serde_json::json!({
+                "name": format!("pacquet-pack-app-{target_id}"),
+                "private": true,
+            }))
+            .expect("serialize the runtime install manifest"),
+        ),
+    )
+    .into_diagnostic()
+    .wrap_err("writing the runtime install manifest")?;
Evidence
ensure_node_runtime uses a direct fs::write for a persistent cache manifest, while the
repository’s own guidance and existing package.json writer implement atomic write semantics to
prevent torn files.

pacquet/crates/cli/src/cli_args/pack_app.rs[534-549]
REVIEW_GUIDE.md[95-97]
pacquet/crates/package-manifest/src/lib.rs[100-119]

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

## Issue description
`ensure_node_runtime` writes `install_dir/package.json` non-atomically. If the process is interrupted mid-write (crash/kill -9/power loss/disk-full), the cached install dir can contain a torn JSON file that breaks subsequent `pack-app` invocations.
### Issue Context
The repo’s review guide and existing codebase use atomic write patterns (temp file + fsync + rename) for manifest-like files to avoid torn state.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[534-549]
### Suggested fix
- Replace `fs::write(install_dir.join("package.json"), ...)` with an atomic write helper (tempfile-in-dir + persist/rename), similar to `PackageManifest::write_atomic`, or introduce a small local helper for this command.
- Consider writing the manifest only after a successful install (or writing a completion marker) if you want to treat the directory as valid only when fully populated.

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


13. Offline flag ignored 🐞 Bug ☼ Reliability
Description
resolve_version() always performs a network resolve_node_version() call and does not honor
Config.offline, so pack-app will unexpectedly hit the network (and can hang/fail) in
offline/air-gapped configurations. This bypasses the existing offline-aware behavior used elsewhere
(and in the Node resolver).
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R578-587]

+async fn resolve_version(config: &Config, specifier: &str) -> miette::Result<String> {
+    let parsed = parse_node_specifier(specifier).map_err(miette::Report::new)?;
+    // pacquet has no `node-download-mirrors` config field yet, so the
+    // override map is always absent and the official nodejs.org tree is
+    // used. Matches pnpm's default when `nodeDownloadMirrors` is unset.
+    let mirror = get_node_mirror(None, &parsed.release_channel);
+    let http_client = build_http_client(config)?;
+    let version = resolve_node_version(&http_client, &parsed.version_specifier, Some(&mirror))
+        .await
+        .map_err(miette::Report::new)?;
Evidence
Config exposes an offline flag, and the node resolver enforces it, but pack-app directly
performs network resolution without checking it.

pacquet/crates/cli/src/cli_args/pack_app.rs[578-587]
pacquet/crates/config/src/lib.rs[654-675]
pacquet/crates/engine-runtime-node-resolver/src/node_resolver.rs[140-142]

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-app` resolves Node versions over the network regardless of `Config.offline`. Users who set offline mode (via `.npmrc`/env/yaml) reasonably expect commands to fail fast without network activity.
## Issue Context
The engine-runtime node resolver has an explicit offline gate, but `pack-app` bypasses that type and calls `resolve_node_version()` directly.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[578-598]
- pacquet/crates/config/src/lib.rs[654-675]
- pacquet/crates/engine-runtime-node-resolver/src/node_resolver.rs[140-142]
## Suggested change
- In `resolve_version()`, if `config.offline` is true, return a structured diagnostic immediately (either a new `PackAppError` mapped to an upstream-equivalent code, or reuse the engine-runtime resolver error code if that’s the convention).
- Alternatively, construct and use `NodeResolver` (or a small helper in the resolver crate) with `offline: config.offline` so behavior matches the rest of the codebase.

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


14. Double .exe on Windows 🐞 Bug ≡ Correctness
Description
PackAppArgs::run always appends .exe for win32 targets, but validate_output_name (and its
tests) allow names like tool.exe, producing tool.exe.exe outputs. This is a user-visible
artifact naming bug for Windows builds/configs.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R336-340]

+            let output_file = if target.platform == "win32" {
+                target_output_dir.join(format!("{output_name}.exe"))
+            } else {
+                target_output_dir.join(&output_name)
+            };
Evidence
The win32 output path is built via format!("{output_name}.exe"), while validation and tests accept
tool.exe, so .exe can be applied twice.

pacquet/crates/cli/src/cli_args/pack_app.rs[336-340]
pacquet/crates/cli/src/cli_args/pack_app.rs[620-638]
pacquet/crates/cli/src/cli_args/pack_app/tests.rs[206-211]

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

## Issue description
On win32 targets, `pack-app` always produces `<output_name>.exe`, but the output-name validator permits `tool.exe`. This leads to `tool.exe.exe` outputs, contradicting the flag help text (“without extension”) and breaking expected filenames.
## Issue Context
- The current behavior is caused by unconditional `.exe` appending for `win32`.
- Validation/tests currently accept names containing `.exe`.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[336-340]
- pacquet/crates/cli/src/cli_args/pack_app.rs[620-638]
- pacquet/crates/cli/src/cli_args/pack_app/tests.rs[206-211]
## Suggested fix
Pick one consistent contract:
1) **Treat `output_name` as a stem**: reject `.exe` for output names (or specifically reject a trailing `.exe` case-insensitively) in `validate_output_name`.
OR
2) **Treat `output_name` as a filename**: for win32, append `.exe` only if it doesn’t already end with `.exe` (case-insensitive).
Update the tests accordingly (either remove `tool.exe` from accepted names or add coverage asserting it doesn’t double-suffix).

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


15. PNPM_HOME symlink write risk 🐞 Bug ⛨ Security
Description
Runtime cache paths are created under pnpm_home_dir() (which is overrideable via the PNPM_HOME
environment variable) and then written to with create_dir_all/write without verifying directory
integrity (e.g., rejecting symlinks). If PNPM_HOME points into a shared/writable location (common
with shared caches), a local attacker can pre-create symlinked paths under pack-app/ to redirect
these writes and subsequent -C  operations.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R462-499]

+    let target_id =
+        [Some(platform), Some(arch), libc].into_iter().flatten().collect::<Vec<_>>().join("-");
+    let install_dir = build_root.join(format!("{target_id}-{version}"));
+    let node_dir = install_dir.join("node_modules").join("node");
+    let binary_path = node_binary_path(&node_dir, platform);
+    if binary_path.exists() {
+        return Ok(binary_path);
+    }
+
+    fs::create_dir_all(&install_dir).into_diagnostic().wrap_err_with(|| {
+        format!("creating the runtime install directory {}", install_dir.display())
+    })?;
+    fs::write(
+        install_dir.join("package.json"),
+        format!(
+            "{}\n",
+            serde_json::to_string_pretty(&serde_json::json!({
+                "name": format!("pacquet-pack-app-{target_id}"),
+                "private": true,
+            }))
+            .expect("serialize the runtime install manifest"),
+        ),
+    )
+    .into_diagnostic()
+    .wrap_err("writing the runtime install manifest")?;
+
+    let mut command = Command::new(pacquet_bin);
+    command
+        .arg("-C")
+        .arg(&install_dir)
+        .arg("add")
+        .arg(format!("--os={platform}"))
+        .arg(format!("--cpu={arch}"));
+    if let Some(libc) = libc {
+        command.arg(format!("--libc={libc}"));
+    }
+    command.arg(format!("node@runtime:{version}"));
+    run_command(&mut command, "pacquet add node@runtime")?;
Evidence
default_pnpm_home_dir is explicitly overrideable via PNPM_HOME. pack-app then constructs
build_root under that directory and creates/writes install_dir contents without any
symlink/integrity validation, which is the classic precreated-symlink redirection pattern in shared
writable directories.

pacquet/crates/config/src/defaults.rs[124-151]
pacquet/crates/cli/src/cli_args/pack_app.rs[302-303]
pacquet/crates/cli/src/cli_args/pack_app.rs[462-499]
REVIEW_GUIDE.md[50-56]

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-app` writes and installs into `PNPM_HOME/pack-app/...` without checking whether any path components are symlinks or otherwise unsafe. In shared-cache setups, this enables symlink redirection of writes and `pacquet add -C <dir>` operations.
### Issue Context
This is primarily a local/shared-cache threat model: `PNPM_HOME` is environment-controlled and may point to a directory writable by other users/processes.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/pack_app.rs[302-303]
- pacquet/crates/cli/src/cli_args/pack_app.rs[462-499]
- pacquet/crates/config/src/defaults.rs[124-151]
### Suggested fix
- When deriving `build_root` / `install_dir`:
- Ensure `build_root` exists with restrictive permissions (best-effort on Unix) and is not a symlink.
- If `install_dir` already exists, verify it is a real directory (not a symlink) before using it.
- If creating, consider creating a temp dir under `build_root` and renaming into place, or use a per-install-dir lock (see also race finding).
- At minimum, reject cases where `symlink_metadata()` indicates `build_root` or `install_dir` is a symlink.

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


Grey Divider

Previous review results

Review updated until commit 027007a

Results up to commit 027007a


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


Action required
1. Signer PATH hijack 🐞 Bug ⛨ Security
Description
ad_hoc_sign_mac_binary spawns codesign/ldid by bare name, so the resolved executable comes
from PATH. If PATH includes a repo-controlled directory (commonly node_modules/.bin in dev/CI
shells), a malicious repo/dependency can get an attacker-provided ldid/codesign executed when
packaging darwin targets.
Code

pacquet/crates/cli/src/cli_args/pack_app.rs[R897-905]

+        "darwin" => run_command(
+            Command::new("codesign").arg("--sign").arg("-").arg(output_file),
+            "codesign",
+        ),
+        "linux" => {
+            run_command(Command::new("ldid").arg("-S").arg(output_file), "ldid").map_err(|_| {
+                PackAppError::MacosSignFailed { path: output_file.display().to_string() }.into()
+            })
+        }
Evidence
The code uses PATH-based command resolution for signing tools, which is exactly the class of risk
the repo’s review guide highlights (executable resolution / environment trust).

pacquet/crates/cli/src/cli_args/pack_app.rs[892-905]
REVIEW_GUIDE.md[50-55]

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

## Issue description
`ad_hoc_sign_mac_binary` invokes `codesign` and `ldid` via `Command::new("codesign")` / `Command::new("ldid")`, which relies on PATH lookup. In environments w...

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

🧹 Nitpick comments (1)
pacquet/crates/cli/src/cli_args/pack_app.rs (1)

229-235: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Model target components as closed enums instead of branded strings.

platform, arch, and libc are closed string-literal sets after parse_target, but they are stored as plain String, so invalid states can still be constructed inside the module and passed to runtime install/signing paths. Use enums such as TargetPlatform, TargetArch, and TargetLibc, then render them at command/path boundaries.

As per coding guidelines, string-literal unions in upstream code should become Rust enums, not newtype wrappers, since the set of valid values is closed.

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

In `@pacquet/crates/cli/src/cli_args/pack_app.rs` around lines 229 - 235, Model
the parsed target components in ParsedTarget as closed enums instead of String
fields: replace platform, arch, and libc with TargetPlatform, TargetArch, and
TargetLibc so parse_target can only construct valid states. Update any consumers
in pack_app.rs that read these fields to work with the enums, and only convert
them back to strings at command/path boundaries where runtime install/signing
logic needs text values.

Source: Coding guidelines

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

Inline comments:
In `@pacquet/crates/cli/src/cli_args/pack_app.rs`:
- Around line 488-499: PackAppArgs::run is spawning pacquet add with only -C
install_dir, which drops the already-resolved Config and can lose project-local
proxy/TLS/registry settings for node@runtime installs. Update the child
invocation around Command::new and run_command in PackAppArgs::run to pass the
resolved config through, or refactor to invoke the install path directly with
the existing Config so behavior stays consistent with the parent resolution.
- Around line 282-300: The output-name validation in pack_app’s directory setup
is happening too late, causing dist-app to be created before invalid
--output-name or pnpm.app.outputName values fail. In the pack_app logic that
derives configured_output_name, output_name, and output_dir, move
derive_output_name_from_package and validate_output_name ahead of
fs::create_dir_all so validation stays fail-fast and side-effect-free, then only
create the output directory after the name is confirmed valid.
- Around line 756-760: The native macOS signing branch in pack_app’s command
handling returns a generic exit-status error instead of the pack-app diagnostic
code used by the Linux ldid path. Update the `run_command` handling for the
`codesign` branch in `pack_app` so failures are wrapped or remapped to
`ERR_PNPM_PACK_APP_MACOS_SIGN_FAILED`, matching the public error-code contract
already enforced by the signing logic.
- Around line 75-79: The CLI help text for PackApp::runtime currently misstates
the default as the “running runtime version,” but the actual default comes from
default_runtime_version() and should be documented as the minimum SEA-capable
version. Update the doc comment on runtime to match the real contract and keep
it aligned with default_runtime_version() so clap help does not mislead users.
- Around line 587-593: The parse_runtime helper currently accepts specs with
multiple @ separators because split_once('@') treats everything after the first
separator as the version, so malformed inputs can slip through. Update
parse_runtime to validate that the spec contains exactly one @ before accepting
it, and continue returning PackAppError::InvalidRuntime for any spec that is not
precisely in the node@version form. Use the parse_runtime function and the
InvalidRuntime variant as the main points to adjust the validation.
- Around line 649-674: Do not swallow config errors in read_project_app_config:
in pack_app.rs, the package.json read path should report unreadable files
instead of returning ReadProjectAppConfigResult::default(), and a present but
non-object pnpm.app should be treated as invalid config rather than ignored.
Update the logic around manifest_path, serde_json::from_str, and
validate_app_config so malformed or unreadable package.json/pnpm.app surfaces a
PackAppError with the real failure instead of falling back to missing-config
behavior.

---

Nitpick comments:
In `@pacquet/crates/cli/src/cli_args/pack_app.rs`:
- Around line 229-235: Model the parsed target components in ParsedTarget as
closed enums instead of String fields: replace platform, arch, and libc with
TargetPlatform, TargetArch, and TargetLibc so parse_target can only construct
valid states. Update any consumers in pack_app.rs that read these fields to work
with the enums, and only convert them back to strings at command/path boundaries
where runtime install/signing logic needs text values.
🪄 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: 805c47dc-084f-45f7-b632-8fa2886ea0f8

📥 Commits

Reviewing files that changed from the base of the PR and between af58273 and 343b240.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (4)
  • pacquet/crates/cli/Cargo.toml
  • pacquet/crates/cli/src/cli_args.rs
  • pacquet/crates/cli/src/cli_args/pack_app.rs
  • pacquet/crates/cli/src/cli_args/pack_app/tests.rs

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 343b240

@zkochan
zkochan force-pushed the feat/pacquet-pack-app branch from 343b240 to 4d85831 Compare June 25, 2026 20:23
@zkochan

zkochan commented Jun 25, 2026

Copy link
Copy Markdown
Member Author

Rebased onto latest main (resolved a conflict in cli_args.rs against the new pack command) and addressed the automated review.

Fixed (commit 4d85831):

  • Unvalidated version in path (Qodo, security): resolve_version now requires the resolved Node.js version to parse as semver before it is used as the <target_id>-<version> cache-dir component, closing the compromised-mirror traversal vector for latest/channel selectors.
  • --runtime help default (CodeRabbit): now documents the minimum SEA-capable version (v25.5.0), matching default_runtime_version().
  • Output-name validated before mkdir (CodeRabbit): invalid names now fail fast without leaving an empty dist-app behind.

Declined — these match pnpm's pack-app exactly, so changing them would diverge from the source of truth (per the cardinal rule in pacquet/AGENTS.md). Rationale on each thread:

  • Spawning add with -C install_dir mirrors pnpm's runPnpmCli([...], { cwd: installDir }).
  • parse_runtime accepting node@25@bad mirrors pnpm's /^(node)@(.+)$/.
  • Swallowing all package.json read errors mirrors pnpm's catch { return {} }.
  • Not wrapping native codesign failures mirrors pnpm (only ldid is wrapped).
  • Not validating pnpm.app.outputDir for traversal mirrors pnpm's bare path.resolve — outputDir is a user/config-chosen location in the same repo-trust boundary pack-app already relies on.

CodeRabbit nitpick — model target components as enums: pnpm's ParsedTarget types platform/arch/libc as plain strings (constrained by a regex), not a string-literal union, so the "unions → enums" guideline doesn't apply to an upstream-faithful port. parse_target is the single construction site and already rejects every invalid triple, so the closed-set invariant is enforced there. Happy to switch to enums if a maintainer prefers it as a local improvement.

Rust checks (clippy pedantic/nursery, dylint, cargo doc, taplo) pass via the pre-push hook; all 17 ported tests pass.


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

@zkochan
zkochan enabled auto-merge June 25, 2026 20:27
@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jun 25, 2026
@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
tarball/download_dependency    1.00      7.3±0.38ms   592.6 KB/sec    1.00      7.3±0.24ms   593.7 KB/sec

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 4d85831

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 4d85831

@codecov-commenter

codecov-commenter commented Jun 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 50.11086% with 225 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.19%. Comparing base (6312916) to head (027007a).

Files with missing lines Patch % Lines
pacquet/crates/cli/src/cli_args/pack_app.rs 50.44% 222 Missing ⚠️
pacquet/crates/cli/src/cli_args.rs 0.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #12669      +/-   ##
==========================================
- Coverage   87.48%   87.19%   -0.30%     
==========================================
  Files         370      371       +1     
  Lines       55767    56218     +451     
==========================================
+ Hits        48789    49019     +230     
- Misses       6978     7199     +221     

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

@zkochan
zkochan added this pull request to the merge queue Jun 25, 2026
@zkochan
zkochan removed this pull request from the merge queue due to a manual request Jun 25, 2026
@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: 87897bf8f1f5

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.769 ± 0.166 4.572 4.994 1.70 ± 0.08
pacquet@main 4.753 ± 0.118 4.620 5.034 1.69 ± 0.06
pnpr@HEAD 2.812 ± 0.079 2.665 2.947 1.00
pnpr@main 2.842 ± 0.110 2.732 3.102 1.01 ± 0.05
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.7693337509,
      "stddev": 0.16615210363362665,
      "median": 4.6984310406,
      "user": 3.8418117,
      "system": 3.4511399799999998,
      "min": 4.5723753336,
      "max": 4.9937373666000004,
      "times": [
        4.9911368156,
        4.6572542646,
        4.7369401476,
        4.9857599786,
        4.6599219336,
        4.9937373666000004,
        4.5723753336,
        4.6341991156,
        4.8218102376,
        4.6402023156
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.7530895294,
      "stddev": 0.1175754292433797,
      "median": 4.7311557346,
      "user": 3.9787855,
      "system": 3.4912253799999986,
      "min": 4.6198285836,
      "max": 5.0340654836,
      "times": [
        4.6687591616,
        5.0340654836,
        4.6198285836,
        4.6501652246,
        4.7171728866,
        4.8240191416,
        4.7451385826,
        4.7114338016,
        4.7656613716,
        4.7946510566
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.8124838078,
      "stddev": 0.07857350186019622,
      "median": 2.8071709026000002,
      "user": 2.6547057999999994,
      "system": 2.9487959799999994,
      "min": 2.6650445356,
      "max": 2.9470344746,
      "times": [
        2.7949250496,
        2.9149783696,
        2.7729079736,
        2.8044702686000003,
        2.8169488426,
        2.8374411306000002,
        2.8098715366,
        2.7612158966,
        2.9470344746,
        2.6650445356
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 2.8423863246000005,
      "stddev": 0.11002169265386932,
      "median": 2.8308299076,
      "user": 2.7010451999999994,
      "system": 2.972414079999999,
      "min": 2.7321280876,
      "max": 3.1023622226,
      "times": [
        2.7321280876,
        2.7408010686,
        2.8471649446000002,
        2.7453079056,
        2.8482646256,
        2.9303707956,
        2.8135884116,
        2.8493803136,
        3.1023622226,
        2.8144948706
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 627.4 ± 11.0 614.7 643.0 1.00 ± 0.03
pacquet@main 626.0 ± 14.1 608.3 650.9 1.00
pnpr@HEAD 692.0 ± 21.4 657.2 732.8 1.11 ± 0.04
pnpr@main 676.5 ± 12.8 656.6 697.7 1.08 ± 0.03
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.62737448662,
      "stddev": 0.011018815523014966,
      "median": 0.62425373102,
      "user": 0.37912425999999994,
      "system": 1.30897884,
      "min": 0.61474019002,
      "max": 0.64298205502,
      "times": [
        0.63400665102,
        0.61860033902,
        0.63846101602,
        0.61474019002,
        0.64138987002,
        0.64298205502,
        0.62806242202,
        0.61568177602,
        0.61937550702,
        0.62044504002
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.62595276822,
      "stddev": 0.014087208212268627,
      "median": 0.6217636415200001,
      "user": 0.3656453599999999,
      "system": 1.30379164,
      "min": 0.60828264802,
      "max": 0.65085501702,
      "times": [
        0.6248271360200001,
        0.61744709302,
        0.61632833302,
        0.60828264802,
        0.61870014702,
        0.61419035602,
        0.63623530102,
        0.6456943980200001,
        0.62696725302,
        0.65085501702
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.6920185452199998,
      "stddev": 0.021350327397195282,
      "median": 0.69338897602,
      "user": 0.38911035999999993,
      "system": 1.33829314,
      "min": 0.65721811002,
      "max": 0.73280772702,
      "times": [
        0.68659810202,
        0.73280772702,
        0.69278287302,
        0.70389763102,
        0.67069971702,
        0.69399507902,
        0.67440182102,
        0.65721811002,
        0.70561082002,
        0.70217357202
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.67650306342,
      "stddev": 0.012780360554867741,
      "median": 0.6782101435200001,
      "user": 0.37639145999999996,
      "system": 1.32731964,
      "min": 0.65655380802,
      "max": 0.6976771390200001,
      "times": [
        0.6976771390200001,
        0.68067700202,
        0.65655380802,
        0.6764999740200001,
        0.6804161320200001,
        0.67612319302,
        0.65813849202,
        0.66893400802,
        0.67992031302,
        0.69009057302
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.618 ± 0.057 4.529 4.699 1.46 ± 0.08
pacquet@main 4.611 ± 0.071 4.499 4.716 1.45 ± 0.08
pnpr@HEAD 3.192 ± 0.132 3.074 3.533 1.01 ± 0.07
pnpr@main 3.174 ± 0.160 3.079 3.565 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.618369347,
      "stddev": 0.05729702791146454,
      "median": 4.6189734228,
      "user": 3.7217537399999996,
      "system": 3.3156076,
      "min": 4.5292488478,
      "max": 4.6986376478,
      "times": [
        4.6409765878,
        4.5408292997999995,
        4.6305867678,
        4.6774815848,
        4.6073600778,
        4.5988323998,
        4.6986376478,
        4.5838995908,
        4.6758406658,
        4.5292488478
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.611046691,
      "stddev": 0.07109755636580968,
      "median": 4.6108443033,
      "user": 3.77951404,
      "system": 3.3134933,
      "min": 4.499072926799999,
      "max": 4.7161343618,
      "times": [
        4.5959573268,
        4.7161343618,
        4.6712422218,
        4.6813325628,
        4.6477832848,
        4.499072926799999,
        4.5173989578,
        4.6257312798,
        4.5950728638,
        4.5607411238
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.1916784800999998,
      "stddev": 0.1323096636286701,
      "median": 3.1688303348,
      "user": 2.7972218399999997,
      "system": 3.1681662000000004,
      "min": 3.0741267368000003,
      "max": 3.5330606178000004,
      "times": [
        3.0744581448000003,
        3.1112141198,
        3.1354927978,
        3.5330606178000004,
        3.2383098598,
        3.1780257468000004,
        3.2040772528000003,
        3.0741267368000003,
        3.2083846018,
        3.1596349228
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.1737283835000003,
      "stddev": 0.15979472363130626,
      "median": 3.1020028603000003,
      "user": 2.82501004,
      "system": 3.1671254,
      "min": 3.0789773038000003,
      "max": 3.5654809788,
      "times": [
        3.0789773038000003,
        3.1365910288000003,
        3.0978422568000004,
        3.1026577728,
        3.5654809788,
        3.0898316748,
        3.3558408918000002,
        3.1116050868,
        3.1013479478000003,
        3.0971088928
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.430 ± 0.016 1.412 1.464 1.03 ± 0.06
pacquet@main 1.387 ± 0.082 1.339 1.618 1.00
pnpr@HEAD 1.483 ± 0.089 1.426 1.730 1.07 ± 0.09
pnpr@main 1.437 ± 0.031 1.406 1.515 1.04 ± 0.07
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.4298564851199997,
      "stddev": 0.016247335540470094,
      "median": 1.43009047172,
      "user": 1.4061776399999997,
      "system": 1.76414232,
      "min": 1.4118293297200002,
      "max": 1.46372394972,
      "times": [
        1.4118293297200002,
        1.42272741572,
        1.43242693172,
        1.46372394972,
        1.4368480837200002,
        1.43344561672,
        1.44408701572,
        1.42775401172,
        1.41285762572,
        1.4128648707200002
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.3869426360200001,
      "stddev": 0.08227787620613192,
      "median": 1.3650674817200001,
      "user": 1.33962304,
      "system": 1.7037014199999998,
      "min": 1.3394928807200002,
      "max": 1.6181557807200002,
      "times": [
        1.3394928807200002,
        1.36563926772,
        1.6181557807200002,
        1.3477082687200002,
        1.34778254772,
        1.36957453172,
        1.3725521497200002,
        1.36449569572,
        1.3827538467200002,
        1.36127139072
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.48330336832,
      "stddev": 0.08905181258190788,
      "median": 1.4628903697200002,
      "user": 0.6198550399999999,
      "system": 1.5867756199999998,
      "min": 1.4255580167200002,
      "max": 1.7303284837200001,
      "times": [
        1.7303284837200001,
        1.46188080972,
        1.43900316972,
        1.4835490537200002,
        1.4638999297200002,
        1.4295841067200001,
        1.4486851067200002,
        1.4737017467200002,
        1.47684325972,
        1.4255580167200002
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.43691601862,
      "stddev": 0.031024512978005847,
      "median": 1.43167768422,
      "user": 0.5891289399999999,
      "system": 1.5587906200000001,
      "min": 1.40618435972,
      "max": 1.5150457267200002,
      "times": [
        1.4399923707200002,
        1.5150457267200002,
        1.44881849572,
        1.42581673572,
        1.4170172497200002,
        1.40618435972,
        1.41160360572,
        1.44540856672,
        1.42173444272,
        1.4375386327200002
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 3.126 ± 0.039 3.069 3.184 2.21 ± 0.06
pacquet@main 3.002 ± 0.033 2.945 3.067 2.12 ± 0.06
pnpr@HEAD 1.430 ± 0.017 1.400 1.462 1.01 ± 0.03
pnpr@main 1.415 ± 0.035 1.383 1.503 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 3.1257719604200007,
      "stddev": 0.038774749336220146,
      "median": 3.12311648692,
      "user": 1.8709797999999995,
      "system": 2.06483392,
      "min": 3.0689143634200002,
      "max": 3.18405298042,
      "times": [
        3.16584624542,
        3.11062831842,
        3.1422452824200002,
        3.18405298042,
        3.0689143634200002,
        3.09724386542,
        3.12316587642,
        3.16558841342,
        3.12306709742,
        3.0769671614200003
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 3.0021577654200002,
      "stddev": 0.03302959567831331,
      "median": 2.99664743742,
      "user": 1.7991496999999999,
      "system": 1.9363788199999998,
      "min": 2.94533613442,
      "max": 3.06671037042,
      "times": [
        2.99708982342,
        3.03239731842,
        2.94533613442,
        3.06671037042,
        2.98334242142,
        2.98105860342,
        2.99962726442,
        2.99620505142,
        3.02605551742,
        2.99375514942
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.42999112192,
      "stddev": 0.016736718275428653,
      "median": 1.43171022242,
      "user": 0.6086886,
      "system": 1.54808002,
      "min": 1.3997822754200002,
      "max": 1.4621617664200002,
      "times": [
        1.4621617664200002,
        1.43761520842,
        1.4299869064200001,
        1.42246829142,
        1.4260865204200002,
        1.3997822754200002,
        1.44155531042,
        1.41313002242,
        1.4336913794200001,
        1.43343353842
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.41524342692,
      "stddev": 0.034868181022092846,
      "median": 1.4075728919200001,
      "user": 0.5714973999999999,
      "system": 1.5626767199999998,
      "min": 1.3825653474200001,
      "max": 1.5027054584200001,
      "times": [
        1.43583507042,
        1.41827374742,
        1.5027054584200001,
        1.41883796142,
        1.3825653474200001,
        1.3891355574200002,
        1.4157424354200001,
        1.39839818342,
        1.3994033484200001,
        1.3915371594200001
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12669
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,618.37 ms
(-2.82%)Baseline: 4,752.54 ms
5,703.05 ms
(80.98%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
3,125.77 ms
(+2.91%)Baseline: 3,037.45 ms
3,644.94 ms
(85.76%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
1,429.86 ms
(+6.00%)Baseline: 1,348.97 ms
1,618.76 ms
(88.33%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
4,769.33 ms
(+0.85%)Baseline: 4,729.29 ms
5,675.15 ms
(84.04%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
627.37 ms
(-3.32%)Baseline: 648.92 ms
778.70 ms
(80.57%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12669
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,191.68 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,429.99 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,483.30 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
2,812.48 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
692.02 ms
🐰 View full continuous benchmarking report in Bencher

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 64bc017

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 64bc017

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pnpm11/releasing/commands/src/pack-app/packApp.ts (1)

158-176: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Close the entry-path TOCTOU before handing it to SEA.

isWithinDir() only proves containment at validation time. seaConfig.main later still points at resolvedEntry, so a repo that swaps that path after Line 172 but before node --build-sea runs can make the builder embed a file outside the project. Please stage the validated entry into a private temp file (or otherwise pin the inode) and pass that staged path to SEA instead. As per path instructions, REVIEW_GUIDE.md says to review path handling for TOCTOU and fail-closed behavior.

🤖 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 `@pnpm11/releasing/commands/src/pack-app/packApp.ts` around lines 158 - 176,
The entry-path validation in packApp still leaves a TOCTOU window because
seaConfig.main uses resolvedEntry after isWithinDir() succeeds, so a swapped
file can be embedded later. Fix this by staging the validated entry to a private
temp location (or otherwise pinning the inode) immediately after the checks,
then use that staged path when setting seaConfig.main and invoking the SEA
build. Keep the existing PnpmError checks in packApp() and preserve the
fail-closed behavior for PACK_APP_ENTRY_NOT_FOUND, PACK_APP_ENTRY_NOT_FILE, and
PACK_APP_ENTRY_OUTSIDE_PROJECT.

Source: Path instructions

🤖 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_app.rs`:
- Around line 342-348: The current outputDir validation in pack_app.rs is only
lexical, so symlinked ancestors can still escape the project before
fs::create_dir_all and subsequent writes. Update the containment check in the
pack-app flow around escapes_project/output_dir to verify existing ancestors
using canonicalized paths (symlink-aware) before creating directories, and keep
the pnpm and pacquet path-handling logic aligned so both use the same robust
containment approach.
- Around line 605-608: The escapes_project helper is too permissive on Windows
because Path::is_absolute() does not catch root-relative and drive-relative
forms like \tmp or C:foo. Update escapes_project to also reject paths containing
Component::RootDir and Component::Prefix(_) in addition to Component::ParentDir,
so join-based path handling cannot escape the project root.

In `@pnpm11/releasing/commands/src/pack-app/packApp.ts`:
- Around line 194-202: The `outputDir` validation in `packApp` only blocks
absolute paths and `..` traversal, but it still allows symlink-based escapes
from the project root. Update the containment check used for `outputDirRaw` so
it is symlink-aware like the `entry` handling, and ensure `mkdir()`/writes only
proceed when the resolved target stays inside `opts.dir`. Add regression
coverage for a repo-local symlink such as `dist-app -> /tmp/out`, and make the
test fail fast in both stacks when the resolved output directory escapes the
project.

---

Outside diff comments:
In `@pnpm11/releasing/commands/src/pack-app/packApp.ts`:
- Around line 158-176: The entry-path validation in packApp still leaves a
TOCTOU window because seaConfig.main uses resolvedEntry after isWithinDir()
succeeds, so a swapped file can be embedded later. Fix this by staging the
validated entry to a private temp location (or otherwise pinning the inode)
immediately after the checks, then use that staged path when setting
seaConfig.main and invoking the SEA build. Keep the existing PnpmError checks in
packApp() and preserve the fail-closed behavior for PACK_APP_ENTRY_NOT_FOUND,
PACK_APP_ENTRY_NOT_FILE, and PACK_APP_ENTRY_OUTSIDE_PROJECT.
🪄 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: d2a0a1a4-6be7-49fb-9075-3781ab0052df

📥 Commits

Reviewing files that changed from the base of the PR and between 4d85831 and 64bc017.

📒 Files selected for processing (5)
  • .changeset/pack-app-path-containment.md
  • pacquet/crates/cli/src/cli_args/pack_app.rs
  • pacquet/crates/cli/src/cli_args/pack_app/tests.rs
  • pnpm11/releasing/commands/src/pack-app/packApp.ts
  • pnpm11/releasing/commands/test/pack-app/index.test.ts
✅ Files skipped from review due to trivial changes (1)
  • .changeset/pack-app-path-containment.md

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 18093dd

zkochan added 2 commits June 26, 2026 00:31
The output-directory hardening was only lexical (rejecting absolute and
`..` paths), so a repo-controlled symlink at `dist-app` (or
`dist-app/<target>`) could still redirect build artifacts outside the
project — and the changeset already claimed symlink escapes were
rejected. Re-check containment against the symlink-resolved real path
after each output directory is created, for both the top-level output
dir and the per-target subdir, matching the entry handling.

Also harden the lexical pre-check on the pacquet side to reject Windows
root-relative (`\foo`) and drive-relative (`C:foo`) forms, which
`Path::is_absolute` does not catch.

Landed in both the TypeScript pnpm CLI and the Rust pacquet port with
matching codes and tests (including symlink-escape regressions).
… TS guard

`pathEscapesProject()` used `path.isAbsolute()`, which reports Windows
drive-relative (`C:foo`) and root-relative (`\foo`) paths as relative, so
on Windows such an `outputDir` would slip the lexical pre-check and the
output directory would be created outside the project before the
realpath containment check aborted. Use `path.parse().root` instead,
which is non-empty for every host-rooted form, matching the pacquet port
that rejects `Component::RootDir` / `Component::Prefix`. Kept
platform-specific (host `path`) so a literal `C:foo` filename stays valid
on POSIX, where it cannot escape — same as the Rust side.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 38df4da

@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

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

@zkochan
zkochan force-pushed the feat/pacquet-pack-app branch from 38df4da to 7a0d513 Compare June 25, 2026 22:36
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown

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

The directory containment checks covered `outputDir` and the per-target
subdir but not the final executable path, so a repo could commit
`dist-app/<target>/<name>` as a symlink and `node --build-sea` would
follow it to overwrite an arbitrary file outside the project ("leaf
symlink" escape).

The output path is now checked before anything is downloaded — and again
right before the build — via `symlink_metadata` / `lstat`: if it already
exists and is not a regular file, abort with
`ERR_PNPM_PACK_APP_OUTPUT_FILE_NOT_REGULAR`. A regular file is still
overwritten as before.

Landed in both the TypeScript pnpm CLI and the Rust pacquet port with
matching codes and symlink-escape regression tests.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 328f672

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 328f672

`ad_hoc_sign_mac_binary` spawned `codesign` / `ldid` by bare name, so a
repo-controlled `node_modules/.bin` on the developer's PATH could get an
attacker-provided signer executed when packaging a darwin target.

`codesign` is now run by its absolute system path (`/usr/bin/codesign`),
and `ldid` is resolved through PATH while skipping any match inside the
project directory (returning the first trusted match, else
`ERR_PNPM_PACK_APP_MACOS_SIGN_FAILED`).

Landed in both the TypeScript pnpm CLI and the Rust pacquet port; the
skip-project-local rule is covered by a pacquet unit test.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 027007a

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 027007a

@zkochan
zkochan merged commit 2c7369d into main Jun 25, 2026
34 checks passed
@zkochan
zkochan deleted the feat/pacquet-pack-app branch June 25, 2026 23:49
kairosci pushed a commit to kairosci/pnpm that referenced this pull request Jun 26, 2026
Ports pnpm's `pack-app` command into pacquet. It packs a CommonJS entry
file into a standalone executable for one or more target platforms,
embedding a Node.js binary through the Node.js Single Executable
Applications API.

Reuses pacquet's node-version resolution, network client, detect-libc,
and `node@runtime:` installs. Two intentional divergences from pnpm,
both forced by pacquet being a Rust binary rather than a Node.js script:
the SEA builder is always downloaded (pnpm reuses its running
interpreter), and the runtime install spawns the pacquet binary
(mirroring pnpm's runPnpmCli).

Ports the upstream Jest validation suite (17 tests) covering the
fail-fast branches. The download / SEA-injection / signing paths need
network, Node.js, and subprocesses and are out of unit-test scope,
matching upstream coverage.

Ported from pnpm/pnpm@9f3df6b9b4.
zkochan added a commit that referenced this pull request Jul 4, 2026
)

The Release job for 11.10.0 failed at the Publish `@pnpm/exe` step with
ERR_PNPM_PACK_APP_ENTRY_OUTSIDE_PROJECT: the pack-app hardening from
#12669 rejects entry/output paths that escape the project
directory, and the `@pnpm/exe` build config used exactly that shape
(entry "../../pnpm.cjs", outputDir ".." relative to
pnpm11/pnpm/artifacts/exe).

Move the pnpm.app config to pnpm11/pnpm/package.json (entry "pnpm.cjs",
outputDir "artifacts") and run pack-app from the pnpm package root in
build-artifacts.ts. Output paths are unchanged
(pnpm11/pnpm/artifacts/<target>/pnpm), and the guard stays strict
instead of being loosened to a workspace-root anchor, which would
re-allow embedding files from outside the packed project.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants