Repository navigation
fix(server): handle permission-denied directories gracefully - #856
unhappychoice merged 3 commits into
Conversation
Running mdts (zero-config) in a folder that contains a sub-directory the process can't read made getFileTree's fs.readdirSync throw EACCES. The throw bubbled up as an HTTP 500 from GET /api/filetree and left the tree panel blank, so the app appeared broken. Wrap readdirSync in try/catch. On the "can't enumerate this directory" family (EACCES/EPERM, plus the ENOENT/ENOTDIR races) log a skip and return an empty sub-tree so the rest still renders. Unexpected errors still propagate. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A permission error (EACCES/EPERM) on a single sub-directory is non-fatal — chokidar keeps watching everything else — but the watcher's error handler treated it as fatal: it tore down the whole watcher, disabled livereload, and printed the raw error with a stack trace. Detect permission errors, log a single friendly line, and leave the watcher running. Genuinely fatal errors (e.g. EMFILE) keep the existing teardown and guidance. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
✅ Deploy Preview for mdts-unhappychoice ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe file tree now skips inaccessible directories while preserving readable entries. Directory and file-pattern watchers treat permission-denied errors as non-fatal, logging affected paths without closing watchers or disabling live reload. Shared error predicates and unit tests support these behaviors. ChangesFilesystem resilience
Estimated code review effort: 3 (Moderate) | ~20 minutes Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
test/unit/server/watcher.test.ts (1)
273-291: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winTest EPERM as well as EACCES.
Both watcher tests cover only
EACCES, although production treatsEPERMequivalently. Parameterize each case over both permission-denied codes so either handler cannot regress to supporting only one.Also applies to: 426-449
🤖 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 `@test/unit/server/watcher.test.ts` around lines 273 - 291, Update the permission-error watcher tests, including the case near the referenced secondary range, to parameterize each test over both EACCES and EPERM. Ensure each generated error uses the current permission code while preserving the existing non-fatal assertions and expected logging behavior.test/unit/server/routes/filetree.test.ts (1)
78-97: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winCover the complete filesystem-error contract.
This test only exercises
EACCES; it does not verify the other supported codes, the skip log, or that unexpected errors still propagate. Add parameterized cases forEACCES,EPERM,ENOENT, andENOTDIR, plus anEIOcase that remains an error.🤖 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 `@test/unit/server/routes/filetree.test.ts` around lines 78 - 97, Expand the file-tree error-handling tests around the existing inaccessible-directory case with parameterized skip cases for EACCES, EPERM, ENOENT, and ENOTDIR, asserting the readable file remains returned and the skip log is emitted. Add an EIO case asserting the request still fails and the unexpected error propagates.
🤖 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/server/watcher.ts`:
- Around line 81-87: Update describeWatchTarget to use path.win32 for
Windows-aware relative-path handling: determine whether errorPath is absolute,
compute its relation to directory with path.win32.relative, and use
path.win32.sep rather than hard-coded “/” separators. Preserve the fallback for
non-string paths and ensure relative targets are logged while unrelated paths
remain unchanged.
---
Nitpick comments:
In `@test/unit/server/routes/filetree.test.ts`:
- Around line 78-97: Expand the file-tree error-handling tests around the
existing inaccessible-directory case with parameterized skip cases for EACCES,
EPERM, ENOENT, and ENOTDIR, asserting the readable file remains returned and the
skip log is emitted. Add an EIO case asserting the request still fails and the
unexpected error propagates.
In `@test/unit/server/watcher.test.ts`:
- Around line 273-291: Update the permission-error watcher tests, including the
case near the referenced secondary range, to parameterize each test over both
EACCES and EPERM. Ensure each generated error uses the current permission code
while preserving the existing non-fatal assertions and expected logging
behavior.
🪄 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: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: b54ce9df-d32c-4d46-9d2f-fc4178650d6c
📒 Files selected for processing (4)
src/server/routes/filetree.tssrc/server/watcher.tstest/unit/server/routes/filetree.test.tstest/unit/server/watcher.test.ts
| const describeWatchTarget = (error: unknown, directory: string): string => { | ||
| const errorPath = (error as NodeJS.ErrnoException)?.path; | ||
| if (typeof errorPath !== 'string') return 'a path'; | ||
| return errorPath.startsWith(`${directory}/`) | ||
| ? errorPath.slice(directory.length + 1) | ||
| : errorPath; | ||
| }; |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== file around watcher.ts =="
if [ -f src/server/watcher.ts ]; then
sed -n '1,140p' src/server/watcher.ts | nl -ba
else
echo "src/server/watcher.ts not found"
fi
echo
echo "== Node path behavior for POSIX and win32 =="
node - <<'JS'
const path = require('path');
function describeWatchTarget(errorPath, directory) {
if (typeof errorPath !== 'string') return 'a path';
return errorPath.startsWith(`${directory}/`)
? errorPath.slice(directory.length + 1)
: errorPath;
}
const cases = [
{
message: 'Linux-style absolute inside',
errorPath: '/home/app/logs/foo.log',
directory: '/home/app/logs'
},
{
message: 'Windows-style absolute inside unquoted win32',
errorPath: 'C:\\Users\\AppData\\Local\\Logs\\foo.log',
directory: 'C:\\Users\\AppData\\Local\\Logs'
},
{
message: 'Windows-style absolute inside with path.win32.relative',
errorPath: 'C:\\Users\\AppData\\Local\\Logs\\foo.log',
directory: 'C:\\Users\\AppData\\Local\\Logs',
win32: true
}
];
for (const c of cases) {
if (c.win32) {
const relativePath = path.win32.relative(c.directory, c.errorPath);
const isInsideDirectory =
relativePath !== '..' &&
!relativePath.startsWith(`..${path.win32.sep}`) &&
!path.win32.isAbsolute(relativePath);
console.log(`${c.message}`);
console.log(` startsWith slash: ${describeWatchTarget(c.errorPath, c.directory)}`);
console.log(` path.win32.relative approach: ${isInsideDirectory && relativePath ? relativePath : c.errorPath}`);
console.log(` separators in path: "${c.errorPath}" contains \\? ${c.errorPath.includes('\\')}`);
} else {
console.log(`${c.message}`);
console.log(` startsWith slash: ${describeWatchTarget(c.errorPath, c.directory)}`);
}
}
JSRepository: unhappychoice/mdts
Length of output: 225
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== file around watcher.ts =="
if [ -f src/server/watcher.ts ]; then
sed -n '1,140p' src/server/watcher.ts | awk '{printf "%5d\t%s\n", NR, $0}'
else
echo "src/server/watcher.ts not found"
fi
echo
echo "== package typescript availability =="
node - <<'JS'
try {
console.log(require.resolve('typescript'));
} catch (e) {
console.log('typescript not resolved');
}
JS
echo
echo "== Node path behavior for POSIX and win32 separators =="
node - <<'JS'
const path = require('path');
function describeWatchTarget(errorPath, directory) {
if (typeof errorPath !== 'string') return 'a path';
return errorPath.startsWith(`${directory}/`)
? errorPath.slice(directory.length + 1)
: errorPath;
}
const cases = [
{
message: 'Linux-style absolute inside',
errorPath: '/home/app/logs/foo.log',
directory: '/home/app/logs'
},
{
message: 'Windows-style absolute inside',
errorPath: 'C:\\Users\\AppData\\Local\\Logs\\foo.log',
directory: 'C:\\Users\\AppData\\Local\\Logs'
}
];
for (const c of cases) {
console.log(`${c.message}`);
console.log(` current startsWith slash: ${describeWatchTarget(c.errorPath, c.directory)}`);
const relativePath = path.win32.relative(c.directory, c.errorPath);
const isInsideDirectory =
relativePath !== '..' &&
!relativePath.startsWith(`..${path.win32.sep}`) &&
!path.win32.isAbsolute(relativePath);
console.log(` path.win32.relative approach: ${isInsideDirectory && relativePath ? relativePath : c.errorPath}`);
console.log(` path input contains backslash: ${c.errorPath.includes('\\')}`);
}
JSRepository: unhappychoice/mdts
Length of output: 6368
Use path.win32 handling for the logged watch target.
describeWatchTarget currently uses / concatenation and a POSIX prefix check, so Windows error paths like C:\Users\...\foo.log are logged as the full absolute path instead of the relative target. Use path.win32 for relative, isAbsolute, and sep while remaining compatible in Node.
🤖 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/server/watcher.ts` around lines 81 - 87, Update describeWatchTarget to
use path.win32 for Windows-aware relative-path handling: determine whether
errorPath is absolute, compute its relation to directory with
path.win32.relative, and use path.win32.sep rather than hard-coded “/”
separators. Preserve the fallback for non-string paths and ensure relative
targets are logged while unrelated paths remain unchanged.
Deduplicate the permission-error handling introduced for inaccessible directories: - Move the near-identical `isUnreadableDirectoryError` (filetree) and `isPermissionError` (watcher) predicates into `src/utils/errors.ts`, built on a shared `hasErrnoCode` helper. - Extract the copy-pasted permission branch of both chokidar `error` handlers into `logSkippedWatchTarget`. - Add unit tests for the new helpers. No behavior change. Co-Authored-By: Claude Opus 5 <[email protected]>
unhappychoice
left a comment
There was a problem hiding this comment.
Thanks for the fix, and for the detailed write-up. I reproduced the problem and the fix locally (a chmod 000 sub-directory under the mounted folder): GET /api/filetree returns 200 with the readable part of the tree, the skip line is logged, and the watcher stays alive. npm test (123 passed) and npm run lint are green on your branch. The approach looks right to me: permission errors are non-fatal, unexpected errors still propagate.
I pushed one refactor commit on top of your branch (7e33313) rather than asking you to round-trip on it:
isUnreadableDirectoryError(filetree.ts) andisPermissionError(watcher.ts) were the same predicate with different code lists, so both now live in a newsrc/utils/errors.tson top of a sharedhasErrnoCodehelper.- The permission branch of the chokidar
errorhandler was copy-pasted into bothsetupDirectoryWatcherandsetupFilePatternWatcher, so it is now a singlelogSkippedWatchTarget. - Added unit tests for the new helpers.
No behavior change, and your tests still pass (138 passed / 14 suites after the added ones).
A few remaining points, none blocking:
-
chokidar has a built-in
ignorePermissionErrorsoption. In v4_handleErrorskips emittingerrorentirely forEPERM/EACCESwhen it is set, so the watcher half of this PR could be a one-line option instead of a handler branch. The trade-off is that the option is silent while your version logs a friendly line, which is arguably the better UX. Did you consider it? If the log line is the point, the current code is fine as is, but it is worth a comment in the code saying so. -
The skip line is logged on every
/api/filetreerequest. Livereload reloads the tree on every file add/remove, so a long session inside a folder with an unreadable directory repeats the line indefinitely. Remembering already-warned paths in aSetand logging once would be quieter. -
describeWatchTargetslices on a hardcoded${directory}/, which does not match on Windows separators and falls back to printing the absolute path.path.relative(directory, errorPath)handles both. Note the existing code at watcher.ts has the same pattern, so this is consistent with what is already there, not a regression. -
ENOENT/ENOTDIRin the file-tree skip list: the race rationale makes sense, but the message ("Skipping inaccessible directory" with a lock emoji) reads as a permission problem for what may just be a directory that vanished mid-scan. Slightly different wording would avoid the confusion.
One process note on my side: the lint and test workflows have not run on this PR yet, only the Netlify and CodeRabbit checks. I will approve the workflow run so CI actually verifies it before merge.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #856 +/- ##
==========================================
- Coverage 99.41% 99.19% -0.23%
==========================================
Files 69 70 +1
Lines 1549 1616 +67
Branches 371 395 +24
==========================================
+ Hits 1540 1603 +63
- Misses 8 12 +4
Partials 1 1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Summary
Fixes a crash where running
npx mdtsin a folder that contains a sub-directory the process can't read made the whole tree view unusable (Error: EACCES: permission denied, scandir ...). Inaccessible directories are now skipped gracefully — in both the file-tree API and the livereload watcher — with a single friendly log line, and no scary error/stack trace.Problem
When mdts is started (zero-config, no
--glob) inside a directory tree that has an unreadable sub-folder, two things break:GET /api/filetreereturns HTTP 500.getFileTreecallsfs.readdirSyncrecursively with no error handling; the first unreadable sub-directory throwsEACCES, the async Express 5 handler rejects, and with no error handler registered the default 500 is returned. The frontend's tree panel is left blank — the app appears completely broken.EACCESon the same directory and theerrorhandler prints the raw error with a full stack trace, then tears down the entire watcher and disables livereload — even though a single unreadable path is non-fatal.There was no simple workaround: no
--excludeflag exists,EXCLUDED_DIRECTORIESis hardcoded, and--globonly helps if the user already knows and lists every markdown path.Root cause
src/server/routes/filetree.ts—getFileTreeusedfs.readdirSync(...)with notry/catch.src/server/watcher.ts— the chokidarerrorhandler treated every error as fatal. Per chokidar's own_handleError,EACCES/EPERMon one path is non-fatal: that path simply isn't watched while the rest continue.Changes
1. File tree — skip unreadable directories (
getFileTree)Wrapped
readdirSyncin atry/catch. The "can't enumerate this directory" error family (EACCES,EPERM, plus theENOENT/ENOTDIRraces where an entry vanishes mid-scan) logs a skip and returns an empty sub-tree so the rest renders:Unexpected errors still propagate (still a 500), so genuine failures aren't hidden.
2. Livereload — keep watching on permission errors
Both watchers (directory and file-pattern) now detect permission errors, log one friendly line, and leave the watcher running:
Genuinely fatal errors keep the existing teardown + guidance (e.g. the
EMFILEhint).GET /api/filetree🚫 Error ...+ stack trace + "Livereload will be disabled"🔒 ...info lineVerification
Tested by launching against a real folder containing an unreadable sub-directory (
compose/data/timescale→Permission denied):GET /api/filetree→ HTTP 200; tree renders all top-level entries;timescaleabsent, rest intacterror/🚫/ stack trace / "disabled" linesnpm test— 123 passed (13 suites), incl. new regression testsnpm run lint— clean (30 files)New tests
test/unit/server/routes/filetree.test.ts—readdirSyncthrowsEACCES→ endpoint returns 200 with the rest of the tree.test/unit/server/watcher.test.ts—EACCESerror event → friendly log, noclose/unwatch, nologger.error(for both directory and file-pattern watchers).Notes
npx mdtscontinues to "just work".--globpath already avoidedreaddirSync.🤖 Generated with Claude Code
Summary by CodeRabbit
EACCESpermission errors.