| name | electron-main-preload-generator |
| description | Generate secure main process and preload script boilerplate with proper context isolation, IPC patterns, and security best practices for Electron applications |
| allowed-tools | Read, Write, Edit, Bash, Glob, Grep |
| tags | ["electron","desktop","security","ipc","preload"] |
| graph | {"domains":["domain:software-engineering"],"specializations":["specialization:desktop-development"],"skillAreas":["skill-area:desktop-ui-frameworks","skill-area:cross-platform-desktop"],"roles":["role:desktop-developer","role:fullstack-engineer"],"workflows":["workflow:feature-development","workflow:release-management"]} |
electron-main-preload-generator
Generate secure Electron main process and preload scripts with proper context isolation, secure IPC patterns, and comprehensive security best practices. This skill creates production-ready boilerplate that follows Electron security guidelines.
Capabilities
- Generate secure main process (
main.js/main.ts) with proper window configuration
- Create preload scripts with context-isolated IPC bridge
- Implement secure IPC patterns with channel whitelisting
- Configure Content Security Policy (CSP) headers
- Set up secure BrowserWindow options with sandbox enabled
- Generate TypeScript type definitions for IPC channels
- Implement permission handlers for sensitive APIs
Input Schema
{
"type": "object",
"properties": {
"projectPath": {
"type": "string",
"description": "Path to the Electron project root"
},
"language": {
"enum": ["javascript", "typescript"],
"default": "typescript"
},
"features": {
"type": "array",
"items": {
"enum": [
"contextIsolation",
"sandbox",
"csp",
"ipcChannels",
Output Schema
{
"type": "object",
"properties": {
"success": { "type": "boolean" },
"files": {
"type": "array",
"items": {
"type": "object",
"properties": {
"path": { "type": "string" },
"type": { "enum": ["main", "preload", "types", "utils"] },
"description":
Usage Instructions
- Analyze existing project: Check for existing main/preload files and framework usage
- Determine security requirements: Based on application features and data sensitivity
- Generate main process: Create secure BrowserWindow configuration
- Generate preload script: Implement context-isolated IPC bridge
- Generate type definitions: If TypeScript, create IPC channel types
- Validate security: Run security checklist
Generated File Structure
src/
main/
main.ts # Main process entry point
ipc-handlers.ts # IPC handler implementations
window-manager.ts # Multi-window management (optional)
protocol-handler.ts # Custom protocol registration (optional)
permission-handler.ts # Permission request handling
preload/
preload.ts # Preload script with contextBridge
api.ts # Exposed API definitions
shared/
ipc-channels.ts # IPC channel definitions
types.ts # Shared TypeScript types
Code Templates
Secure Main Process
import { app, BrowserWindow, session, ipcMain } from 'electron';
import path from 'path';
app.disableHardwareAcceleration();
function createWindow(): BrowserWindow {
const mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
webSecurity: true,
allowRunningInsecureContent: false,
preload: path.join(__dirname, 'preload.js'),
},
});
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.,
: [
]
}
});
});
session..( {
allowedPermissions = [, ];
(allowedPermissions.(permission));
});
mainWindow;
}
Secure Preload Script
import { contextBridge, ipcRenderer } from 'electron';
const VALID_CHANNELS = {
toMain: ['save-file', 'open-dialog', 'app-settings'],
fromMain: ['file-saved', 'update-available', 'settings-changed'],
} as const;
type ToMainChannel = typeof VALID_CHANNELS.toMain[number];
type FromMainChannel = typeof VALID_CHANNELS.fromMain[number];
contextBridge.exposeInMainWorld('electronAPI', {
send: (channel: ToMainChannel, data: unknown) => {
if (VALID_CHANNELS.toMain.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
invoke: async <T>(channel: ToMainChannel, ?: ): <T> => {
(..(channel)) {
ipcRenderer.(channel, data);
}
();
},
: {
(..(channel)) {
= () =>
(...args);
ipcRenderer.(channel, subscription);
{
ipcRenderer.(channel, subscription);
};
}
{};
},
: {
(..(channel)) {
ipcRenderer.(channel, (...args));
}
},
});
TypeScript Type Definitions
export interface ElectronAPI {
send: (channel: string, data: unknown) => void;
invoke: <T>(channel: string, data?: unknown) => Promise<T>;
on: (channel: string, callback: (...args: unknown[]) => void) => () => void;
once: (channel: string, callback: (...args: unknown[]) => void) => void;
}
declare global {
interface Window {
electronAPI: ElectronAPI;
}
}
Security Checklist
| Security Measure | Status | Details |
|---|
| Context Isolation | Required | Always set contextIsolation: true |
| Node Integration | Required | Always set nodeIntegration: false |
| Sandbox | Recommended | Set sandbox: true for renderer |
| Web Security | Required | Never disable webSecurity |
| CSP Headers | Recommended | Strict Content Security Policy |
| Remote Module | Required | Ensure enableRemoteModule: false |
| IPC Validation | Required | Whitelist and validate all IPC channels |
| Protocol Handlers | Recommended | Register custom protocols securely |
| Permission Handler | Recommended | Control permission requests |
| Navigation Guard | Recommended | Restrict navigation to trusted origins |
Best Practices
- Never expose
ipcRenderer directly - Always use channel whitelisting
- Validate all IPC data - Sanitize inputs in main process handlers
- Use invoke/handle pattern - For request/response communication
- Minimize exposed API surface - Only expose what's necessary
- Audit preload scripts regularly - Check for security vulnerabilities
- Keep Electron updated - Security patches are frequent
Community References
Related Skills
electron-builder-config - Build configuration
electron-ipc-security-audit - Audit IPC implementations
electron-auto-updater-setup - Auto-update configuration
Related Agents
electron-architect - Electron architecture expertise
desktop-security-auditor - Security auditing