Skip to content

mineclover/url-fileopener

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

27 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

File Opener CLI Tool

A powerful command-line interface for opening local files via custom URL scheme (fileopener://). This tool enables developers to create clickable links that open specific files in their local editor directly from web pages, documentation, or shared links.

npm version License: MIT

✨ Features

  • πŸ”— Custom URL Protocol: Register fileopener:// scheme with your operating system
  • πŸ“ Project Aliases: Map project names to local directory paths
  • πŸ–₯️ Cross-Platform: Works on macOS, Windows, and Linux
  • πŸ”’ Enhanced Security: Whitelist-based path validation with protection against:
    • Path traversal attacks (../, ~/)
    • Absolute path access outside project directories
    • Symbolic link escapes
    • Directory traversal bypass attempts
  • πŸ”„ Dual URL Formats: Supports both modern and legacy URL formats
  • βš™οΈ Configuration Management: Easy project setup and management
  • πŸ›‘οΈ Error Handling: Comprehensive error messages and validation
  • 🎯 Config URL Support: Access configuration via fileopener://config
  • πŸ”§ ES Module Support: Built with modern JavaScript (ES modules)
  • 🧹 Memory Leak Prevention: Automatic process cleanup after file operations
  • πŸ“ Log Management: Automatic log rotation and manual log cleanup
  • 🌐 Web Integration: Compatible with fileopener-redirect-worker for HTTP-to-protocol redirection

πŸš€ Quick Start

Installation

Option 1: Install from npm (Recommended)

# Install globally from npm
npm install -g @context-action/fopen-cli

# Register the protocol with your system
fopen install

Option 2: Install from source

# Clone the repository
git clone <repository-url>
cd url-fileopener

# Install dependencies
pnpm install

# Build the CLI (converts ES modules to CommonJS)
pnpm build

# Register the protocol with your system
node dist/bin-simple.cjs install

Basic Usage

For npm installation:

# 1. Add a project alias
fopen add myproject /path/to/your/project

# 2. Open files using URLs
fopen open "fileopener://myproject/src/index.js"

# 3. List configured projects
fopen list

# 4. Open configuration file
fopen config

# 5. Open config via URL (alternative)
fopen open "fileopener://config"

For source installation:

# 1. Add a project alias
node dist/bin-simple.cjs add myproject /path/to/your/project

# 2. Open files using URLs
node dist/bin-simple.cjs open "fileopener://myproject/src/index.js"

# 3. List configured projects
node dist/bin-simple.cjs list

# 4. Open configuration file
node dist/bin-simple.cjs config

# 5. Open config via URL (alternative)
node dist/bin-simple.cjs open "fileopener://config"

🌐 Web Integration

HTTP to Protocol Redirection

This CLI tool is fully compatible with the fileopener-redirect-worker, a Cloudflare Worker that automatically redirects HTTP URLs to the fileopener:// protocol.

How it works:

  1. HTTP URL: https://your-domain.com/fileopener/myProject/src/readme.md
  2. Automatic Redirect: The worker redirects to fileopener://myProject/src/readme.md
  3. File Opening: Your local CLI tool opens the file in your default editor

Setup with Cloudflare Worker:

# 1. Deploy the redirect worker to Cloudflare
git clone https://github.com/mineclover/fileopener-redirect-worker
cd fileopener-redirect-worker
npm install
npm run deploy

# 2. Configure your domain in wrangler.toml
[[routes]]
pattern = "your-domain.com/fileopener/*"
zone_name = "your-domain.com"

# 3. Use HTTP URLs in your documentation, issues, or web pages
# https://your-domain.com/fileopener/myProject/src/index.js

Benefits:

  • Shareable Links: Create HTTP links that work in browsers and automatically open files locally
  • Documentation Integration: Use in README files, GitHub issues, or web documentation
  • Cross-Platform: Works on any device with a browser, regardless of CLI installation
  • Fallback Support: HTML fallback with manual link for unsupported browsers

Example Usage:

<!-- In your README.md or documentation -->
Check out the main configuration file: 
[src/config.js](https://your-domain.com/fileopener/myProject/src/config.js)

Or view the API documentation:
[docs/api.md](https://your-domain.com/fileopener/myProject/docs/api.md)

Live Demo - Current Project:

This very README file can be opened using the fileopener protocol! Here's how to set it up:

# 1. Register the current project (path is optional - uses current directory)
fopen add url-fileopener

# 2. Open this README file directly
fopen open "fileopener://url-fileopener/README.md"

# 3. Or use the web redirect URL (if you have the worker deployed)
# https://your-domain.com/fileopener/url-fileopener/README.md

Try it yourself:

  • Direct Protocol: fileopener://url-fileopener/README.md βœ… (Tested and working!)
  • Web Redirect: https://your-domain.com/fileopener/url-fileopener/README.md
  • npm Package: @context-action/fopen-cli@1.0.4 βœ… (Tested and working!)

More examples from this project:

  • Source code - Main CLI implementation
  • Package config - Project configuration
  • Build script - Build automation

This demonstrates how you can create clickable links in documentation that automatically open the corresponding files in your local editor!

npm Package Test Results:

The npm package has been thoroughly tested and verified to work correctly:

# βœ… Tested: npm package installation and registration
npx @context-action/fopen-cli@1.0.4 install
# β†’ Protocol registered with correct handler path

# βœ… Tested: project registration with path omission
npx @context-action/fopen-cli@1.0.4 add url-fileopener
# β†’ Uses current directory automatically

# βœ… Tested: file opening with memory leak prevention
npx @context-action/fopen-cli@1.0.4 open "fileopener://url-fileopener/README.md"
# β†’ File opens and process exits cleanly

Key improvements in v1.0.4:

  • βœ… Fixed bin path configuration for npm package
  • βœ… Added memory leak prevention with explicit process exit
  • βœ… Improved child process management with timeout
  • βœ… Enhanced error handling and validation

πŸ“š Commands Reference

fopen install (npm) / node dist/bin-simple.cjs install (source)

Registers the fileopener:// protocol with your operating system and creates the configuration directory.

# npm installation
fopen install

# source installation
node dist/bin-simple.cjs install

Output:

Installing file opener protocol...
Registering protocol: "fileopener"
With command: "node "/path/to/dist/bin/fopen-handler-simple.cjs" "$_URL_""
[SECURITY] Command executed: { ... }
Protocol registration successful!
Configuration directory: ~/.fopen-cli

fopen add <project> [path] (npm) / node dist/bin-simple.cjs add <project> [path] (source)

Adds a new project alias mapping a name to a local directory path.

# npm installation
fopen add myproject /Users/username/projects/my-project
fopen add docs /Users/username/documents
fopen add current-project  # Uses current directory

# source installation
node dist/bin-simple.cjs add myproject /Users/username/projects/my-project
node dist/bin-simple.cjs add docs /Users/username/documents
node dist/bin-simple.cjs add current-project  # Uses current directory

Validation:

  • Checks if the specified path exists
  • Converts relative paths to absolute paths
  • Updates existing project aliases

fopen list

Lists all configured project aliases and their paths.

fopen list

Output:

Configured projects:
  myproject -> /Users/username/projects/my-project
  docs -> /Users/username/documents

fopen remove <project>

Removes a project alias from the configuration.

fopen remove myproject

Output:

Project 'myproject' removed successfully

fopen open <url>

Opens a file using the fileopener:// URL format.

# Modern format
fopen open "fileopener://myproject/src/index.js"

# Legacy format (query parameter)
fopen open "fileopener://myproject?path=src/index.js"

# Files with spaces (URL encoded)
fopen open "fileopener://myproject/file%20with%20spaces.txt"

fopen config

Opens the configuration file in your default editor.

fopen config

fopen clean-logs

Cleans up log files to free disk space. Log files are automatically rotated when they exceed 1MB.

fopen clean-logs

fopen uninstall

Unregisters the protocol from your system.

fopen uninstall

# With cleanup (removes configuration files)
fopen uninstall --clean

πŸ”— URL Formats

Modern Format (Recommended)

fileopener://project-name/path/to/file.ext

Examples:

fileopener://myproject/README.md
fileopener://myproject/src/components/Button.tsx
fileopener://docs/api/reference.md

Legacy Format (Query Parameter)

fileopener://project-name?path=path/to/file.ext

Examples:

fileopener://myproject?path=README.md
fileopener://myproject?path=src/components/Button.tsx

URL Encoding

Special characters in file paths should be URL encoded:

Character Encoded
Space %20
Hash %23
Percent %25

Example:

fileopener://myproject/my%20file%20with%20spaces.txt

βš™οΈ Configuration

Configuration Directory

~/.fopen-cli/
β”œβ”€β”€ config.json          # Project aliases configuration
└── handler.log          # Operation logs (when available)

Configuration File Format

{
  "projects": {
    "myproject": "/Users/username/projects/my-project",
    "docs": "/Users/username/documents",
    "website": "/Users/username/sites/website"
  },
  "version": "1.0.0",
  "lastUpdated": "2025-09-15T03:50:44.475Z"
}

πŸ”’ Security Features

Enhanced Whitelist-Based Security

The tool implements comprehensive security measures to prevent unauthorized file access:

Path Traversal Protection

# ❌ These will be blocked:
fopen open "fileopener://myproject/../../../etc/passwd"
fopen open "fileopener://myproject?path=../sensitive-file.txt"
fopen open "fileopener://myproject?path=~/Documents/private.txt"

Absolute Path Protection

# ❌ These will be blocked:
fopen open "fileopener://myproject?path=/etc/passwd"
fopen open "fileopener://myproject?path=/Users/otheruser/private.txt"

Symbolic Link Protection

The tool resolves symbolic links and ensures they don't escape the project directory boundaries.

Security Violation Messages

When security violations are detected, the tool provides clear error messages:

Security violation: Path traversal attempt detected
Access denied: Security policy violation
Attempted access to: ../etc/passwd
Allowed project path: /path/to/project

File Validation

  • Checks if the target file exists before attempting to open
  • Validates project aliases exist in configuration
  • Ensures resolved paths remain within project boundaries

πŸ“ Log Management

The tool automatically manages log files to prevent disk space issues:

Automatic Log Rotation

  • Log files are automatically rotated when they exceed 1MB
  • Old logs are backed up as handler.log.old
  • Maximum total log size is limited to 2MB (current + backup)

Manual Log Cleanup

# Clean all log files
fopen clean-logs

Log File Locations

  • macOS/Linux: ~/.fopen-cli/handler.log
  • Windows: %USERPROFILE%\.fopen-cli\handler.log

Log Contents

Logs include:

  • URL processing attempts
  • Security violations
  • File opening results
  • Error messages

This ensures the tool doesn't consume excessive disk space while maintaining useful debugging information.

Error Handling

Comprehensive error messages for various scenarios:

  • Non-existent files or projects
  • Invalid URL formats
  • Path traversal attempts
  • Missing configuration

πŸ–₯️ Platform Support

macOS

Uses open command to open files with default applications.

Windows

Uses start command to open files with default applications.

Linux

Uses xdg-open command to open files with default applications.

πŸ“‚ File Opening Behavior

How Files Are Opened

The tool uses platform-specific commands to open files with their default applications:

  • macOS: open /path/to/file - Opens with the default application for that file type
  • Windows: start "" "/path/to/file" - Opens with the default application for that file type
  • Linux: xdg-open /path/to/file - Opens with the default application for that file type

File Type Behavior

Note: The actual behavior may vary depending on your system configuration and installed applications.

Text Files (.js, .ts, .md, .txt, etc.)

  • Expected: Opens in your default text editor (VS Code, Sublime Text, etc.)
  • Purpose: Code review, documentation reading, configuration editing

Executable Files (.exe, .sh, .bat, etc.)

  • Expected: Opens in a text editor or file manager (NOT executed)
  • Security: Files are opened for viewing, not execution
  • Purpose: Script review, configuration inspection

Media Files (.jpg, .mp4, .pdf, etc.)

  • Expected: Opens in the default media viewer/player
  • Purpose: Content review, asset verification

Archive Files (.zip, .tar.gz, etc.)

  • Expected: Opens in the default archive manager
  • Purpose: Archive inspection, file extraction

Security Considerations

The tool is designed with security in mind:

  • No Execution: Executable files (.exe, .sh, .bat) are opened for viewing, not execution
  • Path Validation: All paths are validated to prevent directory traversal attacks
  • Project Boundaries: Files can only be accessed within configured project directories
  • Safe Defaults: Uses system default applications rather than custom execution logic

Troubleshooting File Opening

If files don't open as expected:

  1. Check Default Applications: Verify your system's default applications for the file type
  2. Test with Different Files: Try opening various file types to isolate the issue
  3. System Configuration: Some systems may have different default behaviors
  4. Manual Testing: Test the platform commands directly:
    # macOS
    open /path/to/your/file.js
    
    # Windows
    start "" "C:\path\to\your\file.js"
    
    # Linux
    xdg-open /path/to/your/file.js

Important: The exact behavior depends on your system configuration. The tool provides a safe, standard way to open files without executing potentially dangerous code.

πŸ› οΈ Development

Project Structure

src/
β”œβ”€β”€ bin-simple.js           # Main CLI entry point
└── bin/
    └── fopen-handler-simple.js  # URL handler binary

tests/
β”œβ”€β”€ contract/               # Contract tests (TDD)
└── integration/            # Integration tests

Technology Stack

  • Framework: Pure Node.js (no external frameworks)
  • Protocol Registration: protocol-registry package
  • Configuration: JSON files with atomic operations
  • Testing: Vitest with comprehensive test coverage
  • Build: tsup for JavaScript bundling

Building from Source

# Install dependencies
pnpm install

# Run tests
pnpm test

# Build the project
pnpm build

# Clean build artifacts
pnpm clean

Testing

# Run all tests
pnpm test

# Run specific test suites
pnpm test tests/contract/
pnpm test tests/integration/

πŸ” Troubleshooting

Common Issues

Protocol Not Registered

Problem: URLs don't open or system doesn't recognize fileopener://

Solution:

# Re-register the protocol
fopen uninstall
fopen install

File Not Opening

Problem: File exists but doesn't open

Solutions:

  1. Check project configuration:

    fopen list
    fopen config  # Verify paths in configuration
  2. Verify file path:

    # Test with absolute path first
    fopen open "fileopener://myproject/README.md"
  3. Check for special characters:

    # Use URL encoding for special characters
    fopen open "fileopener://myproject/file%20with%20spaces.txt"

Permission Issues

Problem: Access denied or permission errors

Solutions:

  1. Check directory permissions
  2. Ensure user has read access to project files
  3. Verify configuration directory permissions:
    ls -la ~/.fopen-cli/

Debug Mode

For detailed troubleshooting, check the configuration and logs:

# Open configuration file
fopen config

# Check project listings
fopen list

# Verify file exists
ls -la /path/to/your/project/file.ext

πŸ“– Use Cases

Documentation Links

Create clickable links in documentation that open source files:

Check the [main component](fileopener://myproject/src/components/Main.tsx)
or review the [API implementation](fileopener://myproject/src/api/users.ts).

Code Reviews

Share direct links to specific files during code reviews:

fileopener://project/src/features/authentication/login.ts
fileopener://project/tests/unit/auth.test.ts

Project Navigation

Quick access to frequently used files:

# Open main configuration
fileopener://myproject/package.json

# Open documentation
fileopener://myproject/README.md

# Open entry point
fileopener://myproject/src/index.ts

Integration with Tools

Integrate with development tools, IDEs, or documentation systems to provide direct file access.

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes following the TDD approach
  4. Add tests for new functionality
  5. Ensure all tests pass: pnpm test
  6. Commit your changes: git commit -m 'Add amazing feature'
  7. Push to the branch: git push origin feature/amazing-feature
  8. Open a Pull Request

Development Guidelines

  • Follow Test-Driven Development (TDD)
  • Write tests before implementation
  • Maintain high test coverage
  • Use vanilla JavaScript for simplicity
  • Keep code simple and readable
  • Include comprehensive error handling

πŸ“„ License

MIT License - see the LICENSE file for details.

πŸ”— Related Links


Created with ❀️ using pure Node.js