Skip to content

[WRONG BRANCH] fix(update): reject project-local npm commands - #61

Draft
luvs01 wants to merge 1 commit into
mainfrom
codex/fix-windows-project-local-npm.cmd-execution
Draft

[WRONG BRANCH] fix(update): reject project-local npm commands#61
luvs01 wants to merge 1 commit into
mainfrom
codex/fix-windows-project-local-npm.cmd-execution

Conversation

@luvs01

@luvs01 luvs01 commented Aug 7, 2026

Copy link
Copy Markdown
Owner

Motivation

  • Prevent a Windows command-resolution regression that could execute npm.cmd from attacker-controlled project-local PATH entries (for example node_modules\\.bin) during update/version checks and installs.
  • Restore the stronger containment guard while preserving the normal resolution of the standard %APPDATA%\\npm global prefix when the current working directory is an ancestor.

Description

  • Replace the exact-cwd helper with an isInside() subtree test and add isSamePath() plus appDataNpm detection to distinguish the AppData npm prefix from untrusted project subtrees.
  • Update resolveNpmCommand to skip absolute PATH entries that are inside the launch cwd (unless the entry is the AppData npm prefix) and otherwise resolve the first existing npm* candidate as before.
  • Keep the existing Windows command wrapping in npmInvocation unchanged and add a focused regression test to ensure project-local node_modules\\.bin\\npm.cmd is ignored in favor of a trusted absolute PATH candidate.

Testing

  • Ran bun test tests/update-npm-invocation.test.ts and the file's tests all passed.
  • Ran bun run typecheck and bun run privacy:scan, both of which succeeded.
  • Attempted the full suite with bun run test; the targeted regression passed, but the full run could not complete due to unrelated GUI dependency fetch errors and timeouts in other integration tests.

Summary by CodeRabbit

  • Bug Fixes
    • Improved Windows npm command resolution by ignoring executables located within the current working directory and its subdirectories.
    • Preserved support for npm installations in the standard %APPDATA%\npm location when configured with an absolute path.
    • Added regression coverage for reliable command discovery and invocation.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown

Deterministic PR hygiene checks passed.

@github-actions github-actions Bot changed the title fix(update): reject project-local npm commands [WRONG BRANCH] fix(update): reject project-local npm commands Aug 7, 2026
@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown

⏳ DRAFT

  • wrong target branch (main); retarget to dev. UI screenshot required.

What to do

  • Retarget this PR to dev — all contributions go to dev.
  • Add a screenshot of the UI change to the PR description.

Its title has been prefixed with [WRONG BRANCH].
This pull request was already a draft. Its draft status will be preserved after every issue above is resolved.

@github-actions
github-actions Bot marked this pull request as draft August 7, 2026 21:57
@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Windows npm resolution now excludes PATH entries inside the current working directory. It allows %APPDATA%\npm when APPDATA is absolute. Tests cover nested local npm binaries and selected invocation arguments.

Changes

Windows npm PATH filtering

Layer / File(s) Summary
Path filtering and APPDATA exception
src/update/npm-invocation.mjs
Lines 15–26 add subtree detection and case-insensitive resolved-path comparison. Lines 42–44 derive the allowed npm directory from absolute APPDATA. Line 55 skips working-directory PATH entries unless they match that directory.
npm resolution regression coverage
tests/update-npm-invocation.test.ts
Line 48 adds APPDATA to the Windows fixture. Lines 59–80 verify that node_modules/.bin under the current directory is rejected and that the absolute npm installation supplies the resolution and invocation arguments.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: invalid-email-address, ingwannu

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: rejecting project-local npm commands during updates.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/fix-windows-project-local-npm.cmd-execution

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

@github-actions github-actions Bot added the bug Something isn't working label Aug 7, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

Inline comments:
In `@src/update/npm-invocation.mjs`:
- Around line 15-26: Canonicalize Windows paths before trust checks: update the
PATH filtering flow and its isInside/isSamePath inputs to use Bun-supported
realpathSync.native for cwd, each existing PATH directory, and APPDATA\npm.
Treat any canonicalization failure as untrusted and skip execution, while
preserving existing path comparisons after canonicalization. Add a Windows
regression test covering a junction, symlink, or 8.3 alias that resolves into
cwd\node_modules\.bin.
🪄 Autofix

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

Plan: Pro Plus

Run ID: c6004453-1722-4211-8c67-da1642505158

📥 Commits

Reviewing files that changed from the base of the PR and between 2468502 and c2b41f2.

📒 Files selected for processing (2)
  • src/update/npm-invocation.mjs
  • tests/update-npm-invocation.test.ts

Comment on lines +15 to 26
function isInside(root, candidate) {
const relative = win32.relative(win32.resolve(root), win32.resolve(candidate));
return relative === "" || (
relative !== ".."
&& !relative.startsWith(`..${win32.sep}`)
&& !win32.isAbsolute(relative)
);
}

function isSamePath(left, right) {
return win32.resolve(left).toLowerCase() === win32.resolve(right).toLowerCase();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu
file=$(git ls-files 'src/update/npm-invocation.mjs' | head -n 1)
printf '%s\n' "FILE=$file"
wc -l "$file"
printf '%s\n' '--- outline ---'
ast-grep outline "$file" --lang javascript || true
printf '%s\n' '--- relevant source ---'
cat -n "$file" | sed -n '1,120p'
printf '%s\n' '--- related references ---'
rg -n --glob '!node_modules' --glob '!dist' --glob '!build' 'isInside|isSamePath|APPDATA|npm-invocation|npm\.cmd|PATH' src package.json bun.lockb bun.lock 2>/dev/null || true
printf '%s\n' '--- runtime/tool availability ---'
command -v bun || true
bun --version 2>/dev/null || true

Repository: luvs01/opencodex

Length of output: 29297


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- update tests and package metadata ---'
git ls-files | rg '(^|/)(test|tests|spec|__tests__)/|npm-invocation|package\.json$|bunfig|tsconfig'
printf '%s\n' '--- npm invocation references and tests ---'
rg -n -C 5 'resolveNpmCommand|npmInvocation|trusted PATH|APPDATA|node_modules.*bin' --glob '!node_modules' --glob '!dist' --glob '!build' .
printf '%s\n' '--- relevant updater call sites ---'
cat -n src/update/index.ts | sed -n '100,205p'
printf '%s\n' '--- existing path canonicalization patterns ---'
rg -n -C 4 'realpathSync|realpath|native\(' src --glob '*.ts' --glob '*.mjs' --glob '*.js'
printf '%s\n' '--- package/runtime declarations ---'
for f in package.json bunfig.toml tsconfig.json; do
  if [ -f "$f" ]; then echo "--- $f"; cat -n "$f" | sed -n '1,180p'; fi
done

Repository: luvs01/opencodex

Length of output: 50373


🌐 Web query:

Bun documentation realpathSync native node:fs support Windows symlink junction 8.3 path canonicalization

💡 Result:

Bun's implementation of node:fs provides full support for Windows symlinks, junctions, and 8.3 path canonicalization, though the behavior depends on the specific method used [1][2]. To achieve reliable path canonicalization on Windows—including resolving NTFS junctions, symlinks, and expanding 8.3 "short" path names (e.g., PROGRA~1) to their full, long-form equivalents—you should use fs.realpathSync.native (or fs.realpath.native) [3][1][2]. Key implementation details: 1. Native Resolution: fs.realpathSync.native and its asynchronous counterpart leverage the Win32 GetFinalPathNameByHandle API [4][5][3]. This native approach is required to correctly "see through" NTFS junctions and map 8.3 short names to their canonical long names [1][2]. 2. Compatibility: While the standard, pure-JavaScript fs.realpathSync exists for Node.js compatibility, it historically has limitations regarding complex Windows reparse points (like junctions) compared to the native binding [4][1]. Bun's implementation ensures realpathSync.native effectively handles these Windows-specific filesystem structures [2]. 3. Canonicalization: Because GetFinalPathNameByHandle is used, the returned paths may include the Windows extended-length path prefix (\\?\), which allows for long path support but requires that consumers handle this format correctly if passing paths to other applications [5][6]. 4. Best Practice: If your application requires robust path comparison or identity verification on Windows, prioritize fs.realpathSync.native over fs.realpathSync or path.resolve [4][3]. Bun maintains these behaviors to ensure that filesystem-dependent operations (such as bundler asset resolution and package installation) remain consistent even when complex filesystem links are involved [5][7].

Citations:


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- focused npm invocation tests ---'
cat -n tests/update-npm-invocation.test.ts | sed -n '1,140p'
printf '%s\n' '--- package metadata ---'
if [ -f package.json ]; then sed -n '1,220p' package.json; fi
printf '%s\n' '--- focused updater call graph ---'
cat -n src/update/index.ts | sed -n '45,70p;120,205p'
printf '%s\n' '--- canonicalization usage in source ---'
rg -n -C 3 --glob 'src/**' 'realpathSync|realpath\.native|realpathSync\.native'
printf '%s\n' '--- Bun references and version constraints ---'
rg -n -C 3 --glob '!node_modules' --glob '!dist' --glob '!build' 'Bun|bun [0-9]|engines|runtime' package.json README.md src/update src/lib tests 2>/dev/null | head -n 240

Repository: luvs01/opencodex

Length of output: 14063


🏁 Script executed:

#!/bin/bash
set -eu
node - <<'JS'
const { win32 } = require("node:path");

function isInside(root, candidate) {
  const relative = win32.relative(win32.resolve(root), win32.resolve(candidate));
  return relative === "" || (
    relative !== ".." &&
    !relative.startsWith(`..${win32.sep}`) &&
    !win32.isAbsolute(relative)
  );
}

const cwd = "C:\\work\\repo";
const cases = [
  ["normal project bin", "C:\\work\\repo\\node_modules\\.bin"],
  ["junction alias to project bin (lexical path)", "C:\\Users\\Public\\repo-bin"],
  ["8.3 alias to project bin (lexical path)", "C:\\PROGRA~1\\repo-bin"],
  ["APPDATA npm", "C:\\Users\\alice\\AppData\\Roaming\\npm"],
];
for (const [label, entry] of cases) {
  console.log(JSON.stringify({ label, entry, insideLexically: isInside(cwd, entry) }));
}
JS

Repository: luvs01/opencodex

Length of output: 579


🌐 Web query:

Bun official docs node:fs realpathSync.native Windows support

💡 Result:

Bun supports fs.realpathSync.native on Windows [1][2]. While Bun generally aims to emulate Node.js behavior, its implementation of fs.realpathSync.native on Windows is specifically designed to provide compatibility. Internally, Bun's implementation for Windows aliases realpathSync.native to its internal fs.realpathNativeSync function [1][3][2]. According to Bun's source code, the implementation for realpathSync on Windows explicitly distinguishes itself from non-Windows platforms to handle path resolution correctly [1][2]. Specifically, Bun's internal code notes that while the standard fs.realpathSync (which is often ported 1:1 from Node.js) may be unable to resolve certain Windows-specific path structures like subst drives, the "native" version (fs.realpathSync.native) is specifically intended to provide the underlying location resolution capability [1][2]. In summary, fs.realpathSync.native is available and supported in Bun on Windows [1][2].

Citations:


Canonicalize Windows PATH directories before applying the trust boundary.

At src/update/npm-invocation.mjs:15-26, win32.resolve() and win32.relative() normalize text only. A junction, symlink, or 8.3 alias can make a PATH entry appear outside cwd while it targets cwd\node_modules\.bin; line 55 then accepts and executes its npm.cmd. Use Bun-supported realpathSync.native to canonicalize cwd, each existing PATH directory, and APPDATA\npm before isInside() and isSamePath(). Fail closed if canonicalization fails. Add a Windows regression test for an alias path.

🤖 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 `@src/update/npm-invocation.mjs` around lines 15 - 26, Canonicalize Windows
paths before trust checks: update the PATH filtering flow and its
isInside/isSamePath inputs to use Bun-supported realpathSync.native for cwd,
each existing PATH directory, and APPDATA\npm. Treat any canonicalization
failure as untrusted and skip execution, while preserving existing path
comparisons after canonicalization. Add a Windows regression test covering a
junction, symlink, or 8.3 alias that resolves into cwd\node_modules\.bin.

Source: Path instructions

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

Labels

aardvark bug Something isn't working codex

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant