
Product
Rust Support Now in Beta
Socket's Rust support is moving to Beta: all users can scan Cargo projects and generate SBOMs, including Cargo.toml-only crates, with Rust-aware supply chain checks.
electron-channel-doctor
Advanced tools
Advanced Script Doctor: Surgical code cleanup + Electron IPC channel management + Security vulnerability detection. Remove unused code, fix missing channels, and detect IPC security issues with AI-powered analysis.
Advanced Code Housekeeping & Surgical Cleanup Tool
Plus: Automate Electron IPC invoke channel management & Security Vulnerability Detection
What started as a simple IPC channel manager has evolved into a comprehensive code housekeeping powerhouse that can perform surgical code cleanup with precision, now with advanced security vulnerability detection!
Automatically detect and surgically remove:
Get instant insights:
Protect your Electron app from critical security issues:
Based on 2024 security research and real CVEs:
electronAPI.invoke()
calls in your code# Global installation (recommended)
npm install -g electron-channel-doctor
# Or use with npx (no installation needed)
npx electron-channel-doctor
# Comprehensive health analysis
electron-channel-doctor health
# Focus on specific file types
electron-channel-doctor health --source "src/**/*.js" --css "styles/**/*.css"
# Get detailed verbose output
electron-channel-doctor health --verbose
# Export as JSON for CI/CD
electron-channel-doctor health --json > health-report.json
Example Output:
๐ฉบ Script Doctor: Performing comprehensive health checkup...
๐ฅ Overall Health Score: 67/100
๐ Code Health Summary:
Unused Functions: 12
Unused Imports: 8
Unused CSS Classes: 23
Dead Code Paths: 3
Duplicate Code Blocks: 2
Complex Functions: 5
Missing IPC Channels: 1
Unused IPC Channels: 4
๐ก Recommendations:
๐จ Remove 12 unused functions to reduce bundle size
โ ๏ธ Code health needs improvement. Consider running surgery.
๐ฏ Recommended Next Steps:
1. Run surgical cleanup
Command: npx electron-channel-doctor surgery
Automatically remove unused code with backup
# Full surgical cleanup (with automatic backup)
electron-channel-doctor surgery
# See what would be removed (dry run)
electron-channel-doctor surgery --dry-run
# Selective surgery (only specific operations)
electron-channel-doctor surgery --operations "unused-functions,unused-imports"
# Disable backup (NOT recommended)
electron-channel-doctor surgery --no-backup
# Verbose surgery with detailed output
electron-channel-doctor surgery --verbose
Version 2.3.0+ introduces Safe Mode - a complete rewrite of the code modification engine that uses AST-based transformations instead of regex patterns.
# Safe mode is ON by default
electron-channel-doctor surgery
# Explicitly enable safe mode features
electron-channel-doctor surgery --conservative --max-changes 10
Safe Mode Features:
# โ ๏ธ WARNING: May break your code!
electron-channel-doctor surgery --no-safe-mode
# Disable ALL safety features (VERY DANGEROUS!)
electron-channel-doctor surgery --no-safe-mode --no-backup --no-validate-syntax
Legacy Mode Issues:
Example of Legacy Mode Destruction:
// BEFORE (Working code)
const logger = require('../../utils/debugLogger');
return number.toString().padStart(2, '0');
// AFTER (Broken by legacy mode)
const logger = require('../../utils/debugLogger'function showTwoDigits(number) {
return number.toString().padStart(2, '0'}
$ electron-channel-doctor surgery --dry-run
๐ฅ Script Doctor: Preparing for surgical code cleanup...
๐ก๏ธ Using SAFE MODE with:
โ
AST-based modifications
โ
Syntax validation
โ
Conservative changes
โ
Automatic backups
๐ Safe Surgery Preview:
๐ Expected Results:
Files to be analyzed: 45
Files to be modified: 12
Syntax errors prevented: 3
Safety score: 95/100
โ ๏ธ Potential Issues:
- src/utils/helpers.js: Parse error: Unexpected token (Skipping file)
- src/legacy/old-code.js: Too many changes needed (15 > 10 limit)
๐ก Run without --dry-run to perform actual surgery
Example Surgery Output:
๐ฅ Script Doctor: Preparing for surgical code cleanup...
๐ Created backup in: .electron-channel-doctor-backups/backup-2024-01-15T10-30-00
๐ง Run 'sh .electron-channel-doctor-backups/backup-2024-01-15T10-30-00/RESTORE.sh' to restore if needed
๐ช Removing 12 unused functions...
๐ฆ Removing 8 unused imports...
๐จ Removing 23 unused CSS classes...
๐ Removing 3 dead code paths...
๐ Surgery completed successfully!
๐ Surgery Statistics:
Files Modified: 15
Lines Removed: 247
Functions Removed: 12
Imports Removed: 8
CSS Classes Removed: 23
Dead Code Removed: 3
Estimated Bundle Size Reduction: 8.7 KB
โ ๏ธ Post-Surgery Recommendations:
๐งช Run your test suite to ensure no functionality was broken
๐๏ธ Test your build process to verify everything still works
๐ Bundle size reduced by ~8.7 KB! Consider measuring actual improvement.
# Generate JSON health report
electron-channel-doctor report --format json --output health-report.json
# Generate Markdown report
electron-channel-doctor report --format markdown --output HEALTH.md
# Output to console
electron-channel-doctor report
# Full security scan with all vulnerability types
electron-channel-doctor security
# Verbose output showing all issues (including low severity)
electron-channel-doctor security --verbose
# Export security report
electron-channel-doctor security --output security-report.json
# Custom file patterns
electron-channel-doctor security \
--main "main.js,electron/**/*.js" \
--renderer "src/**/*.js,renderer/**/*.js" \
--preload "preload.js"
Example Security Scan Output:
๐ Security Analyzer: Scanning for Electron IPC vulnerabilities...
๐ก๏ธ Security Score: 45/100
๐ Vulnerability Summary:
๐จ Critical: 3
โ ๏ธ High: 2
โก Medium: 4
๐ก Low: 1
๐จ CRITICAL Vulnerabilities:
[insecure-node-integration] nodeIntegration enabled - major security risk
File: main.js (line 12)
Fix: Set nodeIntegration: false and use contextBridge
Reference: Enables attacks like CVE-2022-29247
[missing-context-bridge] Preload script not using contextBridge API
File: preload.js
Fix: Use contextBridge.exposeInMainWorld for secure IPC
[dangerous-api-exposure] IPC handler 'file-operation' exposes dangerous API: fs
File: main.js (line 45)
Fix: Never expose Node.js system APIs directly via IPC
Reference: Common attack vector in Electron apps
โ ๏ธ HIGH Vulnerabilities:
[unvalidated-ipc-handler] IPC handler 'get-user-data' lacks input validation
File: main.js (line 67)
Fix: Add input validation to prevent injection attacks
Reference: Related to CVE-2022-29247
๐ก๏ธ Security Recommendations:
๐จ Fix critical vulnerabilities immediately
Critical vulnerabilities can lead to RCE or data theft
๐จ Disable nodeIntegration and enable contextIsolation
This is the most important security configuration
๐ Security Resources:
โข https://www.electronjs.org/docs/latest/tutorial/security
โข https://github.com/electron/electron/security/advisories
โข OWASP Electron Security Guidelines
# Check for IPC channel issues
electron-channel-doctor check
# Auto-fix missing channels
electron-channel-doctor fix
# List all channels
electron-channel-doctor list
# See what would be fixed (dry run)
electron-channel-doctor fix --dry-run
Your codebase might have:
// unused-helper.js - ENTIRE FILE UNUSED
function calculateTax(amount) { return amount * 0.1; }
function formatCurrency(num) { return '$' + num; }
// main.js
import { calculateTax, formatCurrency } from './unused-helper.js';
import { moment } from 'moment'; // UNUSED IMPORT
function processOrder(order) {
// Dead code after return
return order.total;
console.log('This never executes'); // DEAD CODE
const tax = calculateTax(order.total); // UNREACHABLE
}
// Duplicate code block in multiple files
if (user.isLoggedIn && user.hasPermission) {
showDashboard();
updateUserActivity();
logAnalytics('dashboard_view');
}
// styles.css
.old-button { color: red; } /* UNUSED CSS CLASS */
.deprecated-modal { display: none; } /* UNUSED CSS CLASS */
// unused-helper.js - FILE REMOVED ENTIRELY โ๏ธ
// main.js
function processOrder(order) {
return order.total; // Clean and simple!
}
// Duplicate code extracted to reusable function โจ
function showUserDashboard(user) {
if (user.isLoggedIn && user.hasPermission) {
showDashboard();
updateUserActivity();
logAnalytics('dashboard_view');
}
}
// styles.css - UNUSED CLASSES REMOVED โ๏ธ
/* Only the CSS you actually use remains */
Result:
Your project gets a 0-100 health score based on:
Score Range | Health Status | Meaning |
---|---|---|
90-100 | ๐ Excellent | Professional-grade codebase |
70-89 | ๐ Good | Minor improvements needed |
50-69 | โ ๏ธ Needs Work | Surgery recommended |
0-49 | ๐จ Critical | Immediate attention required |
Scoring factors:
# Custom file patterns
electron-channel-doctor health \
--source "src/**/*.{js,jsx,ts,tsx}" \
--css "styles/**/*.{css,scss,sass}" \
--html "templates/**/*.html"
# Custom preload path (for IPC features)
electron-channel-doctor health --preload "main/preload.js"
# Control backup behavior
electron-channel-doctor surgery --no-backup # DANGEROUS!
# Selective operations
electron-channel-doctor surgery --operations "unused-functions,dead-code-paths"
Create .channel-doctor.json
:
{
\"preloadPath\": \"electron/preload.js\",
\"jsPattern\": \"src/**/*.{js,jsx,ts,tsx}\",
\"cssPattern\": \"styles/**/*.{css,scss,sass}\",
\"htmlPattern\": \"templates/**/*.html\",
\"ignorePatterns\": [
\"**/node_modules/**\",
\"**/dist/**\",
\"**/test/**\",
\"**/*.min.js\"
]
}
name: Code Health Check
on: [push, pull_request]
jobs:
health-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm install -g electron-channel-doctor
# Health check (fails if score < 70)
- run: |
SCORE=$(electron-channel-doctor health --json | jq '.healthScore')
echo \"Health Score: $SCORE\"
if [ \"$SCORE\" -lt 70 ]; then
echo \"โ Health score too low: $SCORE/100\"
exit 1
fi
# Generate and upload health report
- run: electron-channel-doctor report --format markdown --output HEALTH.md
- uses: actions/upload-artifact@v3
with:
name: health-report
path: HEALTH.md
{
\"scripts\": {
\"health\": \"electron-channel-doctor health\",
\"security\": \"electron-channel-doctor security\",
\"surgery\": \"electron-channel-doctor surgery --dry-run\",
\"cleanup\": \"electron-channel-doctor surgery\",
\"health-report\": \"electron-channel-doctor report --format markdown --output HEALTH.md\",
\"security-report\": \"electron-channel-doctor security --output security-report.json\",
\"precommit\": \"electron-channel-doctor health --json | jq -e '.healthScore >= 70'\",
\"security-check\": \"electron-channel-doctor security --json | jq -e '.summary.critical == 0'\"
}
}
const {
ChannelDoctor,
UnusedCodeDetector,
CodeSurgeon,
SafeCodeSurgeon, // NEW: AST-based safe surgeon
SecurityAnalyzer,
checkHealth,
performSurgery,
generateHealthReport,
analyzeSecurity
} = require('electron-channel-doctor');
// Quick health check
const healthReport = await checkHealth({
jsPattern: 'src/**/*.js',
cssPattern: 'styles/**/*.css'
});
console.log(`Health Score: ${healthReport.healthScore}/100`);
// Perform surgery (uses Safe Mode by default)
if (healthReport.healthScore < 70) {
const surgeryReport = await performSurgery({
safeMode: true, // Default: true
validateSyntax: true, // Default: true
conservative: true, // Default: true
maxChangesPerFile: 10, // Default: 10
operations: ['unused-functions', 'unused-imports']
});
console.log(`Removed ${surgeryReport.summary.totalLinesRemoved} lines`);
console.log(`Safety score: ${surgeryReport.summary.safetyScore}/100`);
}
// Direct usage of SafeCodeSurgeon (NEW)
const safeSurgeon = new SafeCodeSurgeon({
projectRoot: process.cwd(),
dryRun: false,
validateSyntax: true,
conservative: true,
maxChangesPerFile: 5,
verbose: true
});
const analysisReport = await doctor.performHealthCheckup();
const safeReport = await safeSurgeon.performSafeSurgery(analysisReport);
if (safeReport.errors.length > 0) {
console.error('Some files could not be safely modified:');
safeReport.errors.forEach(err => {
console.error(`- ${err.file}: ${err.error}`);
});
}
// Security analysis
const securityReport = await analyzeSecurity({
mainProcess: ['main.js', 'electron/**/*.js'],
rendererProcess: ['src/**/*.js', 'renderer/**/*.js']
});
if (securityReport.summary.critical > 0) {
console.error('Critical security vulnerabilities found!');
process.exit(1);
}
// Advanced usage with custom configuration
const doctor = new ChannelDoctor({
jsPattern: 'src/**/*.{js,tsx}',
verbose: true
});
const analysis = await doctor.performHealthCheckup();
// Choose between safe and legacy surgery
const surgery = await doctor.performCodeSurgery({
safeMode: true, // Use AST-based safe mode (recommended)
// safeMode: false, // Use regex-based legacy mode (dangerous)
});
const security = await doctor.analyzeSecurityVulnerabilities();
"Reduced our bundle size by 15% in one command!"
- React developer who used Script Doctor on a legacy codebase
"Found 47 unused functions we didn't even know existed"
- Team lead who ran health check on 6-month-old project
"The health scoring system helps us maintain code quality over time"
- DevOps engineer using it in CI/CD pipeline
As of version 2.2.1, Electron Channel Doctor uses a dependency injection pattern for file system operations, making it highly testable and maintainable:
const { ChannelDoctor, FileSystem, MockFileSystem } = require('electron-channel-doctor');
// Production usage (uses real file system)
const doctor = new ChannelDoctor({
projectRoot: '/path/to/project',
jsPattern: 'src/**/*.js'
});
// Testing usage (uses mock file system)
const mockFiles = {
'/test/project/src/app.js': `electronAPI.invoke('test-channel');`,
'/test/project/electron/preload.js': `const validInvokeChannels = ['test-channel'];`
};
const testDoctor = new ChannelDoctor({
projectRoot: '/test/project',
fs: new MockFileSystem(mockFiles) // Inject mock file system
});
// Real file system (default)
const fs = new FileSystem();
await fs.readFile('/path/to/file.js');
const files = fs.findFiles('src/**/*.js', '/project/root', ['node_modules/**']);
// Mock file system (for testing)
const mockFs = new MockFileSystem({
'/project/src/app.js': 'console.log("Hello World");',
'/project/src/utils.js': 'export const helper = () => {};'
});
await mockFs.readFile('/project/src/app.js'); // Returns mock content
const files = mockFs.findFiles('src/**/*.js', '/project'); // Returns matching mock files
const {
ChannelDoctor,
SecurityAnalyzer,
UnusedCodeDetector,
MockFileSystem
} = require('electron-channel-doctor');
// Create custom file system for testing
const mockFiles = {
'/project/main.js': `
const { BrowserWindow } = require('electron');
const win = new BrowserWindow({
webPreferences: { nodeIntegration: true } // Security issue!
});
`,
'/project/src/app.js': `
electronAPI.invoke('get-user-data');
electronAPI.invoke('missing-channel');
`,
'/project/electron/preload.js': `
const { contextBridge } = require('electron');
const validInvokeChannels = ['get-user-data'];
`
};
// All analyzers support dependency injection
const mockFs = new MockFileSystem(mockFiles);
const channelAnalysis = await new ChannelDoctor({
projectRoot: '/project',
fs: mockFs
}).analyze();
const securityAnalysis = await new SecurityAnalyzer({
projectRoot: '/project',
fs: mockFs
}).analyze();
const unusedCodeAnalysis = await new UnusedCodeDetector({
projectRoot: '/project',
fs: mockFs
}).analyzeProject();
If you're building on top of Electron Channel Doctor, you can easily test your extensions:
// test/my-extension.test.js
const { MockFileSystem } = require('electron-channel-doctor');
describe('My Extension', () => {
test('should detect custom patterns', async () => {
const mockFiles = {
'/project/custom.js': 'myCustomAPI.call("test");'
};
const mockFs = new MockFileSystem(mockFiles);
const result = await myExtension.analyze({
projectRoot: '/project',
fs: mockFs // Use mock instead of real file system
});
expect(result.patterns).toContain('test');
});
});
The MockFileSystem
class provides comprehensive file system mocking:
**/*.js
, src/**/*.{js,ts}
, etc.const mockFs = new MockFileSystem({
'/project/src/app.js': 'console.log("app");',
'/project/src/utils/helper.js': 'export const help = () => {};',
'/project/test/app.test.js': 'describe("app", () => {});'
});
// Supports complex glob patterns
const jsFiles = mockFs.findFiles('src/**/*.js', '/project');
// Returns: ['/project/src/app.js', '/project/src/utils/helper.js']
const allFiles = mockFs.findFiles('**/*.{js,ts}', '/project', ['test/**']);
// Returns: ['/project/src/app.js', '/project/src/utils/helper.js']
// (excludes test directory)
We welcome contributions! This tool has huge potential for expansion:
Ideas for contributors:
git clone https://github.com/LFarmbot/electron-channel-doctor.git
cd electron-channel-doctor
npm install
npm test
MIT License - see LICENSE file for details.
This tool was born from real frustration with messy codebases and the manual work of cleaning them up. We believe every developer deserves:
Found this helpful? โญ Star the repo and share with your team!
๐ฉบ Keep your code healthy - your future self will thank you!
FAQs
Advanced Script Doctor: Surgical code cleanup + Electron IPC channel management + Security vulnerability detection. Remove unused code, fix missing channels, and detect IPC security issues with AI-powered analysis.
The npm package electron-channel-doctor receives a total of 6 weekly downloads. As such, electron-channel-doctor popularity was classified as not popular.
We found that electron-channel-doctor demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.ย It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket's Rust support is moving to Beta: all users can scan Cargo projects and generate SBOMs, including Cargo.toml-only crates, with Rust-aware supply chain checks.
Product
Socket Fix 2.0 brings targeted CVE remediation, smarter upgrade planning, and broader ecosystem support to help developers get to zero alerts.
Security News
Socket CEO Feross Aboukhadijeh joins Risky Business Weekly to unpack recent npm phishing attacks, their limited impact, and the risks if attackers get smarter.