Repository navigation
Renaming: Security fix — replace AppleScript with fs.rename - #26734
raycastbot merged 20 commits into
Conversation
|
Thank you for your contribution! 🎉 🔔 @theodaguier @pernielsentikaer @ridemountainpig you might want to have a look. You can use this guide to learn how to check out the Pull Request locally in order to test it. 📋 Quick checkout commandsBRANCH="fix/1-renaming-applescript-to-fs-rename"
FORK_URL="https://github.com/TurboCoder13/extensions.git"
EXTENSION_NAME="renaming"
REPO_NAME="extensions"
git clone -n --depth=1 --filter=tree:0 -b $BRANCH $FORK_URL
cd $REPO_NAME
git sparse-checkout set --no-cone "extensions/$EXTENSION_NAME"
git checkout
cd "extensions/$EXTENSION_NAME"
npm install && npm run devWe're currently experiencing a high volume of incoming requests. As a result, the initial review may take up to 10-15 business days. |
File Breakdown
DistributionDeleted
New (core library)
Modified (commands + components)
Modified (config + docs)
New (test infrastructure + tests)
|
Greptile SummaryThis PR eliminates the AppleScript-based rename implementation across all three commands ( Key changes:
Minor findings:
Confidence Score: 5/5Safe to merge — all remaining findings are P2 style suggestions that do not affect correctness or security All new findings are P2: a confusing (but not incorrect) error message in replace.tsx and an unnecessary jsdom environment in vitest.config.ts. The core security fix (AppleScript → fs.rename), the two-phase batch mechanism, conflict detection, path traversal protection, and per-file error handling are all well-implemented and covered by integration tests. Issues raised in previous review rounds are addressed in this revision. extensions/renaming/src/replace.tsx (misleading error for / in newCharacter), extensions/renaming/vitest.config.ts (jsdom vs node environment) Important Files Changed
Prompt To Fix All With AIThis is a comment left during a code review.
Path: extensions/renaming/src/replace.tsx
Line: 59-69
Comment:
**Misleading error when `/` or null is used as replacement character**
When `newCharacter` contains `/` or a null byte, the resulting filenames are caught downstream by `validatePathTraversal` (or `validateFilename`), which surfaces a security-sounding "Path traversal detected" message. For example, replacing `-` with `/` in `my-file.txt` would produce `my/file.txt`; `join(dirname(...), "my/file.txt")` resolves to a different directory, and `checkConflicts` reports traversal rather than the real problem.
Adding a simple upfront guard mirrors the existing `replaceCharacter === ""` guard and gives a much clearer error:
```suggestion
if (replaceCharacter === "") {
await showToast({
style: Toast.Style.Failure,
title: "Nothing to replace",
message: "Please enter a character to replace",
});
return;
}
if (newCharacter.includes("/") || newCharacter.includes("\0")) {
await showToast({
style: Toast.Style.Failure,
title: "Invalid replacement character",
message: "Replacement cannot contain / or null characters",
});
return;
}
```
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: extensions/renaming/vitest.config.ts
Line: 6
Comment:
**`jsdom` environment is unnecessary for pure Node.js file-system tests**
All tests in `batch.test.ts`, `files.test.ts`, `validation.test.ts`, `errors.test.ts`, and `logger.test.ts` exclusively use Node.js built-ins (`fs/promises`, `os`, `path`) and have no DOM interaction. Using `jsdom` loads a full browser environment, which adds non-trivial startup overhead and can mask environment-specific issues.
```suggestion
environment: "node",
```
How can I resolve this? If you propose a fix, please make it concise.Reviews (9): Last reviewed commit: "fix(renaming): remove dead code, unused ..." | Re-trigger Greptile |
…liability - Replace shell-injectable AppleScript with native Node.js fs.rename() - Add per-file error handling with individual success/failure tracking - Add conflict detection to prevent overwriting existing files - Add filename validation (macOS compatibility) - Add path traversal protection - Keep existing commands: Rename File(s) and Replace File(s) Characters Closes #1
- Replace console.log/console.error with structured log.rename calls
for consistent logging across the extension
- Add empty replaceCharacter guard in replace.tsx to prevent
replaceAll("", x) from inserting characters between every character
- Add Vitest config with jsdom environment and Raycast API mocks - Add test fixtures for files and metadata - Add tests for files.ts (batchRename, conflict detection, getFileInfo) - Add tests for errors.ts (error hierarchy, user-friendly messages) - Add tests for validation.ts (filename validation, separator validation) - Add tests for logger.ts (structured logging, log levels)
Remove enums, interfaces, constants, and fixtures that are scaffolding for later PRs (case transform, history, presets, AI, templates). Keeps only ErrorCode, FileInfo, RenameResult, RenameOperation, ValidationResult, and the two constants files.ts actually imports.
Add changelog entry with {PR_MERGE_DATE} placeholder per Raycast
contribution guidelines.
The form was empty when only one file was selected because fields were gated behind files.length > 1. Now shows form for 1+ files, hides batch-only options (preserve name toggle, index separator) for single file.
Prevent rename when character replacement would produce an empty filename (e.g., replacing all characters with nothing). Shows a toast warning instead of attempting the rename.
- Show New Name field for single file even if preserveName cache is stale - Default log level to WARN in production (was DEBUG) - Add continue after duplicate-target conflict to skip redundant existence check
Add missing docstrings to index.tsx and replace.tsx. Normalize existing docstrings to a consistent style: single sentence describing what the file does, no filler like "for the renaming extension".
a41e68d to
d687413
Compare
|
@greptile please do a full review. |
- Fix isDotfile condition: extname returns "" for dotfiles like .gitignore, not the full name. Comment and condition corrected. - Guard against replace removing entire base name (e.g. replacing "abc" with "" in abc.txt would produce ".txt" — now blocked).
|
@greptile please do full review of the PR |
|
@greptile, please do a final, full PR review of all changes |
… base name - Replace vulnerable runAppleScript in advanced-rename.tsx with batchRename()/checkConflicts() from lib/files.ts, eliminating the last shell injection vector - Add empty base name guard in index.tsx to prevent single-file rename from producing hidden dotfiles (e.g., "document.txt" → ".txt") - Use getUserFriendlyErrorMessage for consistent error reporting
The callback is used to show toast progress updates (async), but was typed as synchronous void and not awaited, causing fire-and-forget behavior where toasts could lag behind actual operations.
|
@greptile, please do a final, full PR review of all changes |
The emptyBases guard only checked files with extensions, so submitting an empty name for extensionless files or directories fell through to checkConflicts and produced a misleading path-traversal error. Rewrite the guard to derive the base name from the operation and check it uniformly for all file types.
|
@greptile, please do a fresh review of this PR |
When two sibling operations are at the same path depth (e.g. A→B and B→C), the temp-moved file must land at its final path before another operation occupies the original slot. Otherwise a Phase 2 failure leaves the original file stranded at a hidden .tmp_rename_ path with no way for the user to find it. Sort needsTemp operations first within the existing depth-descending order so temp files are always resolved before their slots are reused.
…enames Phase 3 used fs.rename() to restore temp files on failure, but on POSIX that silently overwrites the target. If another operation successfully claimed the original slot, the restore would destroy its data. Check occupiedPaths before restoring. Add tests for content preservation through chain renames, three-way rotations, and partial failure scenarios that exercise both the Phase 2 ordering fix and the Phase 3 overwrite guard.
…or handling - Resolve symlinks via realpath() in path traversal validation so a symlinked parent directory cannot bypass the same-directory check - Replace statSync with async stat in useFileSelection hook to avoid blocking the event loop; surface actual error in toast message - Add originalIndex tiebreaker to Phase 2 sort for deterministic execution order when depth and temp priority are equal - Use structured logger instead of console.error in rule application - Wrap onProgress callback in try-catch so a failing progress toast cannot abort the entire batch rename
Extract single 427-line files.ts into four modules by responsibility: - paths.ts: shared path helpers (validatePathTraversal, normalizePath, isSamePath) - files.ts: single-file operations (getFileInfo, fileExists, renameFile, generateUniqueFilename, deduplicatePaths) - batch.ts: batch orchestration and conflict detection (batchRename, checkConflicts) - scan.ts: directory scanning (scanDirectoryForFiles, scanDirectoryRecursive) Split monolithic files.test.ts into files.test.ts (17 tests) and batch.test.ts (15 tests) mirroring the source split. Also apply CodeRabbit review fixes: normalize realpath results for case-insensitive comparison in paths.ts, use isSamePath for directory rename child fixup in batch.ts.
|
@greptile, would you do another review please? |
…che bug - Remove scan.ts (scanDirectoryForFiles, scanDirectoryRecursive), generateUniqueFilename, deduplicatePaths, and MAX_UNIQUE_FILENAME_ATTEMPTS — all unused in this PR, can be added back when needed - Remove @testing-library/react and @testing-library/jest-dom devDeps — no React component tests exist in this PR - Reset preserveName to false when a single file is loaded so the cached state from a previous multi-file invocation doesn't silently ignore user input in the New Name field
|
Okay, @greptile - please do 1 more review for me of this PR. |
|
Published to the Raycast Store: |
|
🎉 🎉 🎉 We've rewarded your Raycast account with some credits. You will soon be able to exchange them for some swag. |
🤖 Disclosure
This fix was developed with AI assistance (Claude Code, Codex and CodeRabbitAI), with my guidance on architecture, requirements, and testing. All code was reviewed and validated by me, including manual testing in Raycast.
Description
This is Part 1 of 8 in the incremental rewrite of the Renaming extension, split from the original #25499 based on reviewer feedback.
This PR focuses exclusively on the critical security and reliability fix — replacing the AppleScript-based rename implementation with native Node.js
fs.rename(). No new features, no new dependencies, no UI changes.Why this change
1. Shell injection vulnerability
Filenames were interpolated directly into
osascriptcommands with only"→\"escaping:This is insufficient — filenames containing other shell metacharacters could inject arbitrary AppleScript commands. A targeted fix was merged upstream (ad9f7d6), but this PR eliminates the entire attack surface by using
fs.rename()directly.2. Batch failures
The original spawned a separate
osascriptprocess for each file. Starting around ~90 files, renames would time out and silently skip files with no indication of which succeeded or failed.fs.rename()eliminates this entirely.3. No error recovery
A single
try/catcharound the entire loop meant a mid-batch failure left files in an inconsistent state. This PR adds per-file error handling and conflict detection.What changed
fs.rename()— eliminates process spawning and shell injection across all 3 commands (Rename File(s),Replace File(s) Characters,Advanced Batch Rename)What did NOT change
Rename File(s),Replace File(s) Characters, andAdvanced Batch Renamekeep their exact names and entry pointsfs.rename()is built-in Node.js (Vitest added as devDependency only)Addressing reviewer feedback from #25499
name,title,modeFollow-up PRs will add features incrementally: case transformation, regex replace, undo history, presets, clipboard rename, AI smart rename, and a hub command — each as a separate, reviewable PR.
Screencast
The UI is unchanged — same form, same workflow. Screenshots in
metadata/folder.Checklist
npm run buildand tested the distribution build in Raycastassetsfolder are used by the extension