Skip to content

Renaming: Security fix — replace AppleScript with fs.rename - #26734

Merged
raycastbot merged 20 commits into
raycast:mainfrom
TurboCoder13:fix/1-renaming-applescript-to-fs-rename
Apr 6, 2026
Merged

raycastbot merged 20 commits into
raycast:mainfrom
TurboCoder13:fix/1-renaming-applescript-to-fs-rename

Conversation

@TurboCoder13

@TurboCoder13 TurboCoder13 commented Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

🤖 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 osascript commands with only " → \" escaping:

const escapedFilePath = file.replaceAll('"', '\\"');
await runAppleScript(`
  tell application "Finder"
    set theItem to POSIX file "${escapedFilePath}" as alias
    set name of theItem to "${escapedNewName}"
  end tell
`);

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 osascript process 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/catch around 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

  • AppleScript → fs.rename() — eliminates process spawning and shell injection across all 3 commands (Rename File(s), Replace File(s) Characters, Advanced Batch Rename)
  • Per-file error handling — each file renamed independently with individual success/failure tracking
  • Conflict detection — checks for duplicate target names and existing files before renaming; refuses to overwrite
  • Path traversal protection — validates new filenames can't escape the parent directory
  • Filename validation — checks macOS constraints (reserved names, length limits, invalid characters)
  • Single-file rename fix — the form was blank when only 1 file was selected (original bug)
  • Empty replace guard — prevents replacing all characters with nothing (would create empty filename)
  • Test suite — 83 tests covering the core file operations, validation, error handling, and logging

What did NOT change

  • Same commands — Rename File(s), Replace File(s) Characters, and Advanced Batch Rename keep their exact names and entry points
  • Same UI — identical form fields, same user workflow
  • No new runtime dependencies — fs.rename() is built-in Node.js (Vitest added as devDependency only)
  • No version bump — keeping 1.0.1

Addressing reviewer feedback from #25499

Feedback This PR
Keep existing commands as top-level entries ✅ All 3 commands unchanged — same name, title, mode
Split the PR up ✅ This is part 1 of 8 — security fix only (28 files vs 118)
Trim dependencies ✅ Zero new runtime dependencies

Follow-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

  • I read the extension guidelines
  • I read the documentation about publishing
  • I ran npm run build and tested the distribution build in Raycast
  • I checked that files in the assets folder are used by the extension
  • I checked that assets used in the README are outside the metadata folder

@raycastbot raycastbot added extension fix / improvement Label for PRs with extension's fix improvements extension: renaming Issues related to the renaming extension labels Mar 29, 2026
@raycastbot

raycastbot commented Mar 29, 2026 •

Copy link
Copy Markdown
Collaborator

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 commands
BRANCH="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 dev

We're currently experiencing a high volume of incoming requests. As a result, the initial review may take up to 10-15 business days.

@TurboCoder13

TurboCoder13 commented Mar 29, 2026 •

Copy link
Copy Markdown
Contributor Author

File Breakdown

Category Count Description
Implementation 15 Commands, lib modules, types (9 new, 5 modified, 1 deleted)
Tests 9 5 test files + 4 helpers (mocks, fixtures, setup)
Config 3 package.json, package-lock.json, vitest.config.ts
Docs 1 CHANGELOG.md
Total 28

Distribution

Implementation ████████████████████████████████████████  53.6%
Tests          ████████████████████████                  32.1%
Config         ████████                                  10.7%
Docs           ███                                        3.6%

Deleted

File Reason
src/utils.tsx AppleScript runner — no longer needed

New (core library)

File Purpose
src/lib/paths.ts Shared path helpers — validatePathTraversal() (symlink-safe via realpath), normalizePath(), isSamePath()
src/lib/files.ts Single-file operations — getFileInfo(), fileExists(), renameFile()
src/lib/batch.ts Batch orchestration — batchRename() (two-phase temp-rename for within-batch conflicts, Phase 3 overwrite guard), checkConflicts()
src/lib/errors.ts Structured error hierarchy (FileNotFoundError, ConflictError, PathTraversalError, etc.) with user-friendly messages
src/lib/validation.ts validateFilename() for macOS constraints (reserved names, / and null chars, UTF-8 byte length)
src/lib/constants.ts MAX_FILENAME_LENGTH
src/lib/logger.ts Module-scoped structured logging with log levels
src/types/enums.ts ErrorCode enum
src/types/index.ts FileInfo, RenameResult, RenameOperation, ValidationResult interfaces

Modified (commands + components)

File Changes
src/index.tsx Replaced AppleScript with batchRename(), added conflict check, empty base name guard for extensionless files, reset preserveName cache for single-file mode
src/replace.tsx Replaced AppleScript with batchRename(), added conflict check, added empty filename guard
src/advanced-rename.tsx Rewired from AppleScript/runAppleScript to batchRename()/checkConflicts() from lib/batch
src/lib/hooks.ts Switched from synchronous statSync to async stat, removed runAppleScript import
src/lib/rules.ts Added logger import, wrapped rule application in try/catch with logging

Modified (config + docs)

File Changes
package.json Added TurboCoder13 to contributors, added Vitest devDependencies and test scripts
package-lock.json Lockfile updated for new devDependencies
CHANGELOG.md Added security fix entry

New (test infrastructure + tests)

File Purpose
vitest.config.ts Vitest config with jsdom, Raycast API mock aliases, v8 coverage
src/__tests__/setup.ts Global mock setup
src/__tests__/__mocks__/@raycast/api.ts Comprehensive Raycast API mock
src/__tests__/__mocks__/@raycast/utils.ts Raycast utils mock
src/__tests__/fixtures/files.ts Mock FileInfo objects
src/__tests__/files.test.ts 13 tests — getFileInfo, fileExists, renameFile
src/__tests__/batch.test.ts 15 tests — checkConflicts, batchRename (chain renames, rotations, partial failure, temp restore)
src/__tests__/errors.test.ts 13 tests — error hierarchy, getUserFriendlyErrorMessage
src/__tests__/validation.test.ts 23 tests — filename validation, separator validation
src/__tests__/logger.test.ts 19 tests — structured logging, log levels, module tagging

@greptile-apps

greptile-apps Bot commented Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR eliminates the AppleScript-based rename implementation across all three commands (Rename File(s), Replace File(s) Characters, and Advanced Rename) and replaces it with native fs.rename(), addressing the shell-injection vulnerability and batch-size timeout issues described in the PR description. The change is well-scoped: no new runtime dependencies, no UI changes, and a solid test suite (83 tests) covering the core file operations, conflict detection, and the two-phase temp-rename mechanism.

Key changes:

  • src/lib/batch.ts — new orchestrator with checkConflicts and batchRename; the two-phase temp-rename approach correctly handles within-batch conflicts (e.g. shift-down numbering, name swaps, circular rotations), and Phase 3 gracefully handles stranded temp files
  • src/lib/files.ts — atomic single-file rename with pre-checks (source existence, target existence, path traversal, filename validation)
  • src/lib/validation.ts — macOS filename constraints (length in UTF-8 bytes, / and null chars, reserved names)
  • src/lib/paths.ts — symlink-safe path traversal guard via realpath
  • src/lib/logger.ts — environment-gated log level (DEBUG in development, WARN in production)
  • src/index.tsx / src/replace.tsx / src/advanced-rename.tsx — per-file error tracking, emptyBases guards, and conflict detection added before each rename

Minor findings:

  • replace.tsx: when newCharacter contains / or null, the user receives a "path traversal detected" error rather than a plain "invalid character" message — a pre-check matching the existing replaceCharacter === "" guard would clarify this
  • vitest.config.ts: environment: "jsdom" loads a full browser simulation for tests that only use Node.js fs APIs; "node" would be lighter and semantically correct

Confidence Score: 5/5

Safe 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

Filename Overview
extensions/renaming/src/lib/batch.ts New batch rename orchestrator with two-phase temp-rename approach to handle within-batch conflicts (e.g. A→B when B is also a source); correctly sorts needsTemp operations first; Phase 3 acknowledges and handles the known edge case of stranded temp files when a slot is occupied by a competing successful rename
extensions/renaming/src/lib/files.ts New single-file operations module; replaces AppleScript with fs.rename(); includes existence checks, path-traversal guard, and filename validation before each rename; correctly handles dotfiles and directories in getFileInfo
extensions/renaming/src/lib/validation.ts New filename validation module; correctly checks for empty names, invalid chars (/ and null), reserved names (. and ..), only-dots sequences, and UTF-8 byte length against the 255-byte APFS limit
extensions/renaming/src/index.tsx Replaces AppleScript loop with batchRename; adds emptyBases guard, per-file success/failure reporting, and single-file form fix (resets preserveName to false and shows New Name field); generateNewName logic is correct for both single and multi-file cases
extensions/renaming/src/replace.tsx Replaces AppleScript loop with batchRename; adds empty-search-string guard and emptyBases guard; missing upfront guard for / or null in newCharacter causes confusing path-traversal error message instead of a clear invalid-character message
extensions/renaming/src/lib/paths.ts New path utilities; validatePathTraversal resolves symlinks via realpath before comparing directories and has a graceful fallback to resolve() for broken symlinks; normalizePath handles case-insensitive macOS/Windows comparison
extensions/renaming/src/lib/logger.ts New structured logger; log level is correctly environment-gated (DEBUG in development, WARN in production) via NODE_ENV check — the prior concern about DEBUG being the default is resolved in the current code
extensions/renaming/src/advanced-rename.tsx Replaces per-file AppleScript with a single batchRename call; filters out entries with no newName before building operations; correctly threads conflict detection before the rename
extensions/renaming/vitest.config.ts New Vitest configuration; coverage thresholds at 85% are reasonable; jsdom environment is unnecessary overhead for pure Node.js file-system tests — node environment would be more appropriate
extensions/renaming/src/tests/batch.test.ts Comprehensive integration tests for batchRename and checkConflicts; covers shift-down numbering, name swaps, three-way rotations, temp-file cleanup on success, and the acknowledged partial-failure/stranded-temp scenario
Prompt To Fix All With AI
This 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

Comment thread extensions/renaming/src/index.tsx Resolved
Comment thread extensions/renaming/src/lib/logger.ts Resolved
Comment thread extensions/renaming/src/lib/files.ts Resolved
…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".
@TurboCoder13
TurboCoder13 force-pushed the fix/1-renaming-applescript-to-fs-rename branch from a41e68d to d687413 Compare March 29, 2026 11:20
@TurboCoder13

Copy link
Copy Markdown
Contributor Author

@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).
@TurboCoder13

Copy link
Copy Markdown
Contributor Author

@greptile please do full review of the PR

@TurboCoder13

Copy link
Copy Markdown
Contributor Author

@greptile, please do a final, full PR review of all changes

Comment thread extensions/renaming/src/index.tsx Resolved
@TurboCoder13
TurboCoder13 marked this pull request as draft March 30, 2026 05:57
… 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.
@TurboCoder13

Copy link
Copy Markdown
Contributor Author

@greptile, please do a final, full PR review of all changes

Comment thread extensions/renaming/src/index.tsx Resolved
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.
@TurboCoder13

Copy link
Copy Markdown
Contributor Author

@greptile, please do a fresh review of this PR

Comment thread extensions/renaming/src/lib/files.ts Resolved
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.
@TurboCoder13

Copy link
Copy Markdown
Contributor Author

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

Copy link
Copy Markdown
Contributor Author

Okay, @greptile - please do 1 more review for me of this PR.

@TurboCoder13
TurboCoder13 marked this pull request as ready for review March 31, 2026 10:36
@0xdhrv 0xdhrv self-assigned this Apr 6, 2026

@0xdhrv 0xdhrv left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good to me, approved ✅

@raycastbot
raycastbot merged commit 3e434b5 into raycast:main Apr 6, 2026
2 checks passed
@github-actions

github-actions Bot commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

@raycastbot

Copy link
Copy Markdown
Collaborator

🎉 🎉 🎉

We've rewarded your Raycast account with some credits. You will soon be able to exchange them for some swag.

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

Labels

extension fix / improvement Label for PRs with extension's fix improvements extension: renaming Issues related to the renaming extension platform: macOS

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants