electron-main-preload-generator
Generate secure main process and preload script boilerplate with proper context isolation, IPC patterns, and security best practices for Electron applications
What this skill does
# 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
```json
{
"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",
"permissionHandler",
"protocolHandler",
"deepLinking",
"autoUpdater",
"tray",
"multiWindow"
]
},
"default": ["contextIsolation", "sandbox", "csp", "ipcChannels"]
},
"ipcChannels": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" },
"direction": { "enum": ["toMain", "toRenderer", "bidirectional"] },
"description": { "type": "string" },
"requestSchema": { "type": "object" },
"responseSchema": { "type": "object" }
},
"required": ["name", "direction"]
},
"description": "Define IPC channels for the application"
},
"windowConfig": {
"type": "object",
"properties": {
"width": { "type": "number", "default": 1200 },
"height": { "type": "number", "default": 800 },
"minWidth": { "type": "number" },
"minHeight": { "type": "number" },
"frame": { "type": "boolean", "default": true },
"transparent": { "type": "boolean", "default": false },
"titleBarStyle": { "enum": ["default", "hidden", "hiddenInset", "customButtonsOnHover"] }
}
},
"cspPolicy": {
"type": "object",
"properties": {
"defaultSrc": { "type": "array", "items": { "type": "string" } },
"scriptSrc": { "type": "array", "items": { "type": "string" } },
"styleSrc": { "type": "array", "items": { "type": "string" } },
"imgSrc": { "type": "array", "items": { "type": "string" } },
"connectSrc": { "type": "array", "items": { "type": "string" } }
}
}
},
"required": ["projectPath"]
}
```
## Output Schema
```json
{
"type": "object",
"properties": {
"success": { "type": "boolean" },
"files": {
"type": "array",
"items": {
"type": "object",
"properties": {
"path": { "type": "string" },
"type": { "enum": ["main", "preload", "types", "utils"] },
"description": { "type": "string" }
}
}
},
"securityChecklist": {
"type": "array",
"items": {
"type": "object",
"properties": {
"check": { "type": "string" },
"status": { "enum": ["implemented", "recommended", "optional"] },
"details": { "type": "string" }
}
}
},
"warnings": { "type": "array", "items": { "type": "string" } }
},
"required": ["success", "files"]
}
```
## Usage Instructions
1. **Analyze existing project**: Check for existing main/preload files and framework usage
2. **Determine security requirements**: Based on application features and data sensitivity
3. **Generate main process**: Create secure BrowserWindow configuration
4. **Generate preload script**: Implement context-isolated IPC bridge
5. **Generate type definitions**: If TypeScript, create IPC channel types
6. **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
```typescript
import { app, BrowserWindow, session, ipcMain } from 'electron';
import path from 'path';
// Security: Disable remote module (deprecated but check)
app.disableHardwareAcceleration(); // Optional: for headless environments
function createWindow(): BrowserWindow {
const mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
// Security settings
nodeIntegration: false, // Never enable in production
contextIsolation: true, // Always enable
sandbox: true, // Enable sandbox
webSecurity: true, // Keep enabled
allowRunningInsecureContent: false,
preload: path.join(__dirname, 'preload.js'),
},
});
// Content Security Policy
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Content-Security-Policy': [
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"
]
}
});
});
// Permission handling
session.defaultSession.setPermissionRequestHandler((webContents, permission, callback) => {
const allowedPermissions = ['clipboard-read', 'notifications'];
callback(allowedPermissions.includes(permission));
});
return mainWindow;
}
```
### Secure Preload Script
```typescript
import { contextBridge, ipcRenderer } from 'electron';
// Define allowed channels
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];
// Expose protected methods via contextBridge
contextBridge.exposeInMainWorld('electronAPI', {
// Send to main process (one-way)
send: (channel: ToMainChannel, data: unknown) => {
if (VALID_CHANNELS.toMain.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
// Invoke main process and wait for response
invoke: async <T>(channel: ToMainChannel, data?: unknown): Promise<T> => {
if (VALID_CHANNELS.toMain.includes(channel)) {
return ipcRenderer.invoke(channel, data);
}
throw new Error(`Invalid channel: ${channel}`);
},
// Subscribe to main process events
on: (channel: FromMainChannel, callback: (...args: unknown[]) => void) => {
if (VALID_CHANNELS.fromMain.includes(channel)) {
const subscription = (_event: Electron.IpcRendererEvent, ...args: unknown[]) =>
callback(...args);
ipcRenderer.on(channel, subscription);
// Return unsubscribe function
return () => {
ipcRenderer.removeListener(channel, subscription);
};
}
return () => {};
},
// One-time listener
once: (channel: FromMainChannel, callback: (...args: unknown[]) => void) => {
if (VALID_CHANNELS.fromMain.includes(channel)) {
ipcRenderer.once(channel, (_event, ...args) => callback(...args));
}
},
});
```
### TypeScript Type Definitions
```typescript
// types/electron-api.d.ts
export interface ElectronAPI {
send: (channel: string, dataRelated in Security
mac-ops
IncludedComprehensive macOS workstation operations — diagnose kernel panics, identify failing drives, audit launchd startup items, decode wake reasons, triage TCC permission denials, manage APFS snapshots, recover from no-boot. Use for: Mac is slow, slow bootup, won't boot, kernel panic, kernel_task hot, mds_stores CPU, photoanalysisd, cloudd, login loop, gray screen, sleep wake failure, drive failing, IO errors, APFS snapshots eating space, Time Machine local snapshots, Spotlight indexing, launchd, LaunchAgent, LaunchDaemon, login items, TCC permissions, Full Disk Access, Screen Recording denied, Gatekeeper, quarantine, com.apple.quarantine, app is damaged, helper tool, /Library/PrivilegedHelperTools, pmset, wake reasons, dark wake, sysdiagnose, panic.ips, DiagnosticReports, configuration profile, MDM profile, remote diagnostics over SSH.
a11y-audit
IncludedRun accessibility audits on web projects combining automated scanning (axe-core, Lighthouse) with WCAG 2.1 AA compliance mapping, manual check guidance, and structured reporting. Output is configurable: markdown report only, markdown plus machine-readable JSON, or markdown plus issue tracker integration. Use this skill whenever the user mentions "accessibility audit", "a11y audit", "WCAG audit", "accessibility check", "compliance scan", or asks to check a web project for accessibility issues. Also trigger when the user wants to verify WCAG conformance or map findings to a specific standard (CAN-ASC-6.2, EN 301 549, ADA/AODA).
erpclaw
IncludedAI-native ERP system with self-extending OS. Full accounting, invoicing, inventory, purchasing, tax, billing, HR, payroll, advanced accounting (ASC 606/842, intercompany, consolidation), and financial reporting. 413 actions across 14 domains, 43 expansion modules. Constitutional guardrails, adversarial audit, schema migration. Double-entry GL, immutable audit trail, US GAAP.
assess
IncludedAssesses and rates quality 0-10 across multiple dimensions (correctness, maintainability, security, performance, testability, simplicity) with pros/cons analysis. Compares against project conventions and prior decisions from memory. Produces structured evaluation reports with actionable improvement suggestions. Use when evaluating code, designs, architectures, or comparing alternative approaches.
spring-boot-security-jwt
IncludedProvides JWT authentication and authorization patterns for Spring Boot 3.5.x covering token generation with JJWT, Bearer/cookie authentication, database/OAuth2 integration, and RBAC/permission-based access control using Spring Security 6.x. Use when implementing authentication or authorization in Spring Boot applications.
code-hardcode-audit
IncludedDetect hardcoded values, magic numbers, and leaked secrets. TRIGGERS - hardcode audit, magic numbers, PLR2004, secret scanning.