Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
feat(skills): Add electron-base skill for secure desktop apps
Jeremy Dawes2b0b3d8349e0
diff --git a/skills/electron-base/.claude-plugin/plugin.json b/skills/electron-base/.claude-plugin/plugin.jsonnew file mode 100644index 00000000..344cde2a--- /dev/null+++ b/skills/electron-base/.claude-plugin/plugin.json@@ -0,0 +1,12 @@+{+ "name": "electron-base",+ "description": "Build secure desktop applications with Electron 33, Vite, React, and TypeScript. Covers type-safe IPC via contextBridge, OAuth with custom protocol handlers, native module compatibility (better-sqlite3, electron-store), and electron-builder packaging. Use when building cross-platform desktop apps, implementing OAuth flows in Electron, handling main/renderer process communication, or packaging with code signing. Prevents: NODE_MODULE_VERSION mismatch, hardcoded encryption keys, context isolation ",+ "version": "1.0.0",+ "author": {+ "name": "Jeremy Dawes",+ "email": "[email protected]"+ },+ "license": "MIT",+ "repository": "https://github.com/jezweb/claude-skills",+ "keywords": []+}diff --git a/skills/electron-base/README.md b/skills/electron-base/README.mdnew file mode 100644index 00000000..4c6b36bf--- /dev/null+++ b/skills/electron-base/README.md@@ -0,0 +1,83 @@+# Electron Base Skill++Production patterns for building secure desktop applications with Electron 33, Vite, React, and TypeScript.++## When to Use++This skill provides guidance for:++- Setting up Electron with Vite and React+- Implementing type-safe IPC via contextBridge+- OAuth authentication with custom protocol handlers+- Native module integration (better-sqlite3, electron-store)+- Packaging with electron-builder++## Auto-Trigger Keywords++### Technologies+- electron+- electron-builder+- electron-store+- vite-plugin-electron+- contextBridge+- preload script+- desktop app+- cross-platform desktop+- native desktop app++### Patterns+- IPC main renderer+- main process+- renderer process+- custom protocol handler+- deep linking electron+- electron OAuth+- electron authentication++### Error Messages+- NODE_MODULE_VERSION mismatch+- Cannot read properties of undefined (reading 'invoke')+- contextBridge is not defined+- State mismatch - possible CSRF attack+- Module did not self-register+- electron-rebuild+- sandbox native module++## Key Features++- **Security-First**: Context isolation, no node integration, machine-derived encryption+- **Type-Safe IPC**: Full TypeScript interface for main/renderer communication+- **OAuth Patterns**: Custom protocol handlers with CSRF protection+- **Native Modules**: Compatibility guidance for better-sqlite3, electron-store+- **Build Ready**: electron-builder configuration with code signing++## Prevents Common Errors++1. Hardcoded encryption keys in electron-store+2. NODE_MODULE_VERSION mismatches+3. Context isolation bypasses+4. OAuth state validation failures+5. Sandbox conflicts with native modules+6. Empty catch blocks masking auth failures+7. Dual auth system maintenance burden+8. Token expiration without refresh++## Templates Included++- `main.ts` - Main process with protocol handlers+- `preload.ts` - Type-safe contextBridge implementation+- `vite.config.ts` - Dual-entry Vite configuration+- `electron-builder.json` - Cross-platform packaging+- `ipc-handlers/auth.ts` - Secure OAuth handler+- `ipc-handlers/store.ts` - electron-store setup++## Dependencies++```+electron@^33.0.0+electron-builder@^25.0.0+electron-store@^10.0.0+vite-plugin-electron@^0.28.0+node-machine-id@^1.1.12 (optional)+better-sqlite3@^11.0.0 (optional)+```diff --git a/skills/electron-base/SKILL.md b/skills/electron-base/SKILL.mdnew file mode 100644index 00000000..9f98022b--- /dev/null+++ b/skills/electron-base/SKILL.md@@ -0,0 +1,654 @@+---+name: electron-base+description: |+ Build secure desktop applications with Electron 33, Vite, React, and TypeScript. Covers type-safe IPC via contextBridge, OAuth with custom protocol handlers, native module compatibility (better-sqlite3, electron-store), and electron-builder packaging.++ Use when building cross-platform desktop apps, implementing OAuth flows in Electron, handling main/renderer process communication, or packaging with code signing. Prevents: NODE_MODULE_VERSION mismatch, hardcoded encryption keys, context isolation bypasses, sandbox conflicts with native modules.+---++# Electron Base Skill++Build secure, modern desktop applications with Electron 33, Vite, React, and TypeScript.++## Quick Start++### 1. Initialize Project++```bash+# Create Vite project+npm create vite@latest my-app -- --template react-ts+cd my-app++# Install Electron dependencies+npm install electron electron-store+npm install -D vite-plugin-electron vite-plugin-electron-renderer electron-builder+```++### 2. Project Structure++```+my-app/+├── electron/+│ ├── main.ts # Main process entry+│ ├── preload.ts # Preload script (contextBridge)+│ └── ipc-handlers/ # Modular IPC handlers+│ ├── auth.ts+│ └── store.ts+├── src/ # React app (renderer)+├── vite.config.ts # Dual-entry Vite config+├── electron-builder.json # Build config+└── package.json+```++### 3. Package.json Updates++```json+{+ "main": "dist-electron/main.mjs",+ "scripts": {+ "dev": "vite",+ "build": "vite build",+ "preview": "electron .",+ "package": "electron-builder"+ }+}+```++---++## Architecture Patterns++### Main vs Renderer Process Separation++```+┌─────────────────────────────────────────────────────────────┐+│ MAIN PROCESS │+│ (Node.js + Electron APIs) │+│ - File system access │+│ - Native modules (better-sqlite3) │+│ - System dialogs │+│ - Protocol handlers │+└─────────────────────┬───────────────────────────────────────┘+ │ IPC (invoke/handle)+ │ Events (send/on)+┌─────────────────────▼───────────────────────────────────────┐+│ PRELOAD SCRIPT │+│ (contextBridge.exposeInMainWorld) │+│ - Type-safe API exposed to renderer │+│ - No direct ipcRenderer exposure │+└─────────────────────┬───────────────────────────────────────┘+ │ window.electron.*+┌─────────────────────▼───────────────────────────────────────┐+│ RENDERER PROCESS │+│ (Browser context - React app) │+│ - No Node.js APIs │+│ - Uses window.electron.* for IPC │+└─────────────────────────────────────────────────────────────┘+```++### Type-Safe IPC Pattern++The preload script exposes a typed API to the renderer:++```typescript+// electron/preload.ts+export interface ElectronAPI {+ auth: {+ startOAuth: (provider: 'google' | 'github') => Promise<void>;+ getSession: () => Promise<Session | null>;+ logout: () => Promise<void>;+ onSuccess: (callback: (session: Session) => void) => () => void;+ onError: (callback: (error: string) => void) => () => void;+ };+ app: {+ getVersion: () => Promise<string>;+ openExternal: (url: string) => Promise<void>;+ };+}++// Expose to renderer+contextBridge.exposeInMainWorld('electron', electronAPI);++// Global type declaration+declare global {+ interface Window {+ electron: ElectronAPI;+ }+}+```++---++## Security Best Practices++### REQUIRED: Context Isolation++Always enable context isolation and disable node integration:++```typescript+// electron/main.ts+const mainWindow = new BrowserWindow({+ webPreferences: {+ preload: join(__dirname, 'preload.cjs'),+ contextIsolation: true, // REQUIRED - isolates preload from renderer+ nodeIntegration: false, // REQUIRED - no Node.js in renderer+ sandbox: false, // May need to disable for native modules+ },+});+```++### NEVER: Hardcode Encryption Keys++```typescript+// WRONG - hardcoded key is a security vulnerability+const store = new Store({+ encryptionKey: 'my-secret-key', // DO NOT DO THIS+});++// CORRECT - derive from machine ID+import { machineIdSync } from 'node-machine-id';++const store = new Store({+ encryptionKey: machineIdSync().slice(0, 32), // Machine-unique key+});+```++### Sandbox Trade-offs++Native modules like `better-sqlite3` require `sandbox: false`. Document this trade-off:++```typescript+webPreferences: {+ sandbox: false, // Required for better-sqlite3 - document security trade-off+}+```++**Modules requiring sandbox: false:**+- better-sqlite3+- node-pty+- native-keymap++**Modules working with sandbox: true:**+- electron-store (pure JS)+- keytar (uses Electron's safeStorage)++---++## OAuth with Custom Protocol Handlers++### 1. Register Protocol (main.ts)++```typescript+// In development, need to pass executable path+if (process.defaultApp) {+ if (process.argv.length >= 2) {+ app.setAsDefaultProtocolClient('myapp', process.execPath, [process.argv[1]]);+ }+} else {+ app.setAsDefaultProtocolClient('myapp');+}+```++### 2. Handle Protocol URL++```typescript+// Single instance lock (required for reliable protocol handling)+const gotTheLock = app.requestSingleInstanceLock();++if (!gotTheLock) {+ app.quit();+} else {+ app.on('second-instance', (_event, commandLine) => {+ const url = commandLine.find((arg) => arg.startsWith('myapp://'));+ if (url) handleProtocolUrl(url);+ if (mainWindow?.isMinimized()) mainWindow.restore();+ mainWindow?.focus();+ });+}++// macOS handles protocol differently+app.on('open-url', (_event, url) => {+ handleProtocolUrl(url);+});++function handleProtocolUrl(url: string) {+ const parsedUrl = new URL(url);++ if (parsedUrl.pathname.includes('/auth/callback')) {+ const token = parsedUrl.searchParams.get('token');+ const state = parsedUrl.searchParams.get('state');+ const error = parsedUrl.searchParams.get('error');++ if (error) {+ mainWindow?.webContents.send('auth:error', error);+ } else if (token && state) {+ handleAuthCallback(token, state)+ .then((session) => mainWindow?.webContents.send('auth:success', session))+ .catch((err) => mainWindow?.webContents.send('auth:error', err.message));+ }+ }+}+```++### 3. State Validation for CSRF Protection++```typescript+// Start OAuth - generate and store state+ipcMain.handle('auth:start-oauth', async (_event, provider) => {+ const state = crypto.randomUUID();+ store.set('pendingState', state);++ const authUrl = `${BACKEND_URL}/api/auth/signin/${provider}?state=${state}`;+ await shell.openExternal(authUrl);+});++// Verify state on callback+export async function handleAuthCallback(token: string, state: string): Promise<Session> {+ const pendingState = store.get('pendingState');++ if (state !== pendingState) {+ throw new Error('State mismatch - possible CSRF attack');+ }++ store.set('pendingState', null);+ // ... rest of auth flow+}+```++---++## Native Module Compatibility++### better-sqlite3++Requires rebuilding for Electron's Node ABI:++```bash+# Install+npm install better-sqlite3++# Rebuild for Electron+npm install -D electron-rebuild+npx electron-rebuild -f -w better-sqlite3+```++**Vite config - externalize native modules:**++```typescript+// vite.config.ts+electron({+ main: {+ entry: 'electron/main.ts',+ vite: {+ build: {+ rollupOptions: {+ external: ['electron', 'better-sqlite3', 'electron-store'],+ },+ },+ },+ },+});+```++### electron-store++Works with sandbox enabled, but encryption key should be machine-derived:++```typescript+import Store from 'electron-store';+import { machineIdSync } from 'node-machine-id';++interface StoreSchema {+ session: Session | null;+ settings: Settings;+}++const store = new Store<StoreSchema>({+ name: 'myapp-data',+ encryptionKey: machineIdSync().slice(0, 32),+ defaults: {+ session: null,+ settings: { theme: 'system' },+ },+});+```++---++## Build and Packaging++### electron-builder.json++```json+{+ "$schema": "https://raw.githubusercontent.com/electron-userland/electron-builder/master/packages/app-builder-lib/scheme.json",+ "appId": "com.yourcompany.myapp",+ "productName": "MyApp",+ "directories": {+ "output": "release"+ },+ "files": [+ "dist/**/*",+ "dist-electron/**/*"+ ],+ "mac": {+ "category": "public.app-category.productivity",+ "icon": "build/icon.icns",+ "hardenedRuntime": true,+ "gatekeeperAssess": false,+ "entitlements": "build/entitlements.mac.plist",+ "entitlementsInherit": "build/entitlements.mac.plist",+ "target": [+ { "target": "dmg", "arch": ["x64", "arm64"] }+ ],+ "protocols": [+ { "name": "MyApp", "schemes": ["myapp"] }+ ]+ },+ "win": {+ "icon": "build/icon.ico",+ "target": [+ { "target": "nsis", "arch": ["x64"] }+ ]+ },+ "linux": {+ "icon": "build/icons",+ "target": ["AppImage"],+ "category": "Office"+ }+}+```++### macOS Entitlements (build/entitlements.mac.plist)++```xml+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.security.cs.allow-jit</key>+ <true/>+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key>+ <true/>+ <key>com.apple.security.cs.disable-library-validation</key>+ <true/>+</dict>+</plist>+```++### Build Commands++```bash+# Development+npm run dev++# Production build+npm run build++# Package for current platform+npm run package++# Package for specific platform+npx electron-builder --mac+npx electron-builder --win+npx electron-builder --linux+```++---++## Known Issues and Prevention++### 1. "Cannot read properties of undefined" in Preload++**Cause:** Accessing window.electron before preload completes.++**Fix:** Use optional chaining or check for existence:++```typescript+// In React component+useEffect(() => {+ if (!window.electron?.auth) return;++ const unsubscribe = window.electron.auth.onSuccess((session) => {+ setSession(session);+ });++ return unsubscribe;+}, []);+```++### 2. NODE_MODULE_VERSION Mismatch++**Cause:** Native module compiled for different Node.js version than Electron uses.++**Fix:**++```bash+# Rebuild native modules for Electron+npx electron-rebuild -f -w better-sqlite3++# Or add to package.json postinstall+"scripts": {+ "postinstall": "electron-rebuild"+}+```++### 3. OAuth State Mismatch++**Cause:** State not persisted or lost between OAuth start and callback.++**Fix:** Use persistent storage (electron-store) not memory:++```typescript+// WRONG - state lost if app restarts+let pendingState: string | null = null;++// CORRECT - persisted storage+const store = new Store({ ... });+store.set('pendingState', state);+```++### 4. Sandbox Conflicts with Native Modules++**Cause:** Sandbox prevents loading native .node files.++**Fix:** Disable sandbox (with documented trade-off) or use pure-JS alternatives:++```typescript+webPreferences: {+ sandbox: false, // Required for better-sqlite3+ // Alternative: Use sql.js (WASM) if sandbox required+}+```++### 5. Dual Auth System Maintenance Burden++**Cause:** Configuring better-auth but using manual OAuth creates confusion.++**Fix:** Choose one approach:+- Use better-auth fully OR+- Use manual OAuth only (remove better-auth)++### 6. Token Expiration Without Refresh++**Cause:** Hardcoded expiration with no refresh mechanism.++**Fix:** Implement token refresh or sliding sessions:++```typescript+// Check expiration with buffer+const session = store.get('session');+const expiresAt = new Date(session.expiresAt);+const bufferMs = 5 * 60 * 1000; // 5 minutes++if (Date.now() > expiresAt.getTime() - bufferMs) {+ await refreshToken(session.token);+}+```++### 7. Empty Catch Blocks Masking Failures++**Cause:** Swallowing errors silently.++**Fix:** Log errors, distinguish error types:++```typescript+// WRONG+try {+ await fetch(url);+} catch {+ // Silent failure - user has no idea what happened+}++// CORRECT+try {+ await fetch(url);+} catch (err) {+ if (err instanceof TypeError) {+ console.error('[Network] Offline or DNS failure:', err.message);+ } else {+ console.error('[Auth] Unexpected error:', err);+ }+ throw err; // Re-throw for caller to handle+}+```++### 8. Hardcoded Encryption Key++**Cause:** Using string literal for encryption.++**Fix:** Derive from machine identifier:++```typescript+import { machineIdSync } from 'node-machine-id';++const store = new Store({+ encryptionKey: machineIdSync().slice(0, 32),+});+```++---++## Vite Configuration++### Full vite.config.ts++```typescript+import { defineConfig } from 'vite';+import react from '@vitejs/plugin-react';+import tailwindcss from '@tailwindcss/vite';+import electron from 'vite-plugin-electron/simple';+import { resolve, dirname } from 'path';+import { fileURLToPath } from 'url';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);++export default defineConfig({+ plugins: [+ react(),+ tailwindcss(),+ electron({+ main: {+ entry: 'electron/main.ts',+ vite: {+ build: {+ outDir: 'dist-electron',+ rollupOptions: {+ external: ['electron', 'better-sqlite3', 'electron-store'],+ output: {+ format: 'es',+ entryFileNames: '[name].mjs',+ },+ },+ },+ },+ },+ preload: {+ input: 'electron/preload.ts',+ vite: {+ build: {+ outDir: 'dist-electron',+ rollupOptions: {+ output: {+ format: 'cjs',+ entryFileNames: '[name].cjs',+ },+ },+ },+ },+ },+ renderer: {},+ }),+ ],+ resolve: {+ alias: {+ '@': resolve(__dirname, 'src'),+ },+ },+ build: {+ outDir: 'dist',+ },+ optimizeDeps: {+ include: ['react', 'react-dom'],+ },+});+```++---++## Dependencies Reference++### Production Dependencies++```json+{+ "dependencies": {+ "electron-store": "^10.0.0",+ "electron-updater": "^6.3.0"+ },+ "optionalDependencies": {+ "better-sqlite3": "^11.0.0",+ "node-machine-id": "^1.1.12"+ }+}+```++### Development Dependencies++```json+{+ "devDependencies": {+ "electron": "^33.0.0",+ "electron-builder": "^25.0.0",+ "electron-rebuild": "^3.2.9",+ "vite-plugin-electron": "^0.28.0",+ "vite-plugin-electron-renderer": "^0.14.0"+ }+}+```++---++## Security Checklist++Before release, verify:++- [ ] `contextIsolation: true` in webPreferences+- [ ] `nodeIntegration: false` in webPreferences+- [ ] No hardcoded encryption keys+- [ ] OAuth state validation implemented+- [ ] No sensitive data in IPC channel names+- [ ] External links open in system browser (`shell.openExternal`)+- [ ] CSP headers configured for production+- [ ] macOS hardened runtime enabled+- [ ] Code signing configured (if distributing)+- [ ] No empty catch blocks masking errors++---++## Related Skills++- **better-auth** - For backend authentication that pairs with Electron OAuth+- **cloudflare-worker-base** - For building backend APIs+- **tailwind-v4-shadcn** - For styling the renderer UIdiff --git a/skills/electron-base/references/security-checklist.md b/skills/electron-base/references/security-checklist.mdnew file mode 100644index 00000000..dec8abfb--- /dev/null+++ b/skills/electron-base/references/security-checklist.md@@ -0,0 +1,224 @@+# Electron Security Checklist++Use this checklist before releasing your Electron application.++## Required Security Settings++### Web Preferences++- [ ] `contextIsolation: true` - Isolates preload script from renderer+- [ ] `nodeIntegration: false` - No Node.js APIs in renderer+- [ ] `sandbox: true` (if possible) - Additional process isolation++```typescript+webPreferences: {+ preload: join(__dirname, 'preload.cjs'),+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true, // Disable only if native modules require it+}+```++### If Sandbox Must Be Disabled++Document why and what native modules require it:++```typescript+webPreferences: {+ sandbox: false, // Required for better-sqlite3 - see security-checklist.md+}+```++**Modules requiring sandbox: false:**+- better-sqlite3+- node-pty+- native-keymap+- Any module with native (.node) bindings++## Encryption and Secrets++- [ ] No hardcoded encryption keys+- [ ] No secrets in source code+- [ ] Encryption keys derived from machine ID++```typescript+// WRONG+const store = new Store({+ encryptionKey: 'my-secret-key',+});++// CORRECT+import { machineIdSync } from 'node-machine-id';++const store = new Store({+ encryptionKey: machineIdSync().slice(0, 32),+});+```++## OAuth and Authentication++- [ ] CSRF protection via state parameter+- [ ] State stored persistently (not in memory)+- [ ] State validated on callback+- [ ] Token expiration handled+- [ ] Refresh token flow implemented (if applicable)++```typescript+// Generate state+const state = crypto.randomUUID();+store.set('pendingState', state);++// Validate on callback+if (state !== store.get('pendingState')) {+ throw new Error('State mismatch - possible CSRF attack');+}+```++## IPC Security++- [ ] No sensitive data in IPC channel names+- [ ] Input validation on all IPC handlers+- [ ] No arbitrary code execution from renderer+- [ ] Limited API surface exposed via contextBridge++```typescript+// CORRECT - specific, validated handlers+ipcMain.handle('auth:get-session', () => {+ // Return only what's needed+ const session = store.get('session');+ return session ? { user: session.user } : null;+});+```++**Never allow arbitrary code execution from renderer:**+- No handlers that execute arbitrary strings+- No file path traversal+- Validate all inputs++## External Links++- [ ] External URLs open in system browser+- [ ] No arbitrary URL navigation in BrowserWindow++```typescript+// Block navigation to external URLs+mainWindow.webContents.setWindowOpenHandler(({ url }) => {+ shell.openExternal(url);+ return { action: 'deny' };+});+```++## Content Security Policy++- [ ] CSP headers configured for production+- [ ] No inline scripts (unless nonce-based)+- [ ] Limited external resource loading++```typescript+// In production, set CSP via session+session.defaultSession.webRequest.onHeadersReceived((details, callback) => {+ callback({+ responseHeaders: {+ ...details.responseHeaders,+ 'Content-Security-Policy': [+ "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'",+ ],+ },+ });+});+```++## Error Handling++- [ ] No empty catch blocks+- [ ] Errors logged with context+- [ ] Sensitive errors not exposed to renderer+- [ ] Network errors vs auth errors distinguished++```typescript+// WRONG+try {+ await fetch(url);+} catch {+ // Silent failure+}++// CORRECT+try {+ await fetch(url);+} catch (err) {+ if (err instanceof TypeError) {+ console.error('[Network] Offline or DNS failure');+ } else {+ console.error('[Auth] Unexpected error:', err);+ }+ throw err;+}+```++## Build and Distribution++### macOS++- [ ] Hardened runtime enabled+- [ ] Code signed with valid certificate+- [ ] Notarized for distribution+- [ ] Entitlements minimized++```json+{+ "mac": {+ "hardenedRuntime": true,+ "gatekeeperAssess": false,+ "entitlements": "build/entitlements.mac.plist",+ "entitlementsInherit": "build/entitlements.mac.plist"+ }+}+```++### Windows++- [ ] Code signed with valid certificate+- [ ] No unnecessary permissions++### All Platforms++- [ ] Auto-update uses HTTPS+- [ ] Update signature verification enabled+- [ ] No development dependencies in production++## Development vs Production++- [ ] DevTools disabled in production+- [ ] Different URLs for dev/prod+- [ ] Environment detection correct++```typescript+const isDev = process.env.NODE_ENV !== 'production' || !app.isPackaged;++if (isDev) {+ mainWindow.loadURL('http://localhost:5173');+ mainWindow.webContents.openDevTools();+} else {+ mainWindow.loadFile(join(__dirname, '../dist/index.html'));+}+```++## Audit Commands++```bash+# Check for known vulnerabilities+npm audit++# Check Electron version for security updates+npx electron --version++# Check electron-builder version+npx electron-builder --version+```++## Security Resources++- [Electron Security Documentation](https://www.electronjs.org/docs/latest/tutorial/security)+- [Electron Security Checklist](https://www.electronjs.org/docs/latest/tutorial/security#checklist-security-recommendations)+- [CVE Database for Electron](https://www.cvedetails.com/vulnerability-list/vendor_id-18218/product_id-43011/Electron-Electron.html)diff --git a/skills/electron-base/rules/electron-base.md b/skills/electron-base/rules/electron-base.mdnew file mode 100644index 00000000..983c961d--- /dev/null+++ b/skills/electron-base/rules/electron-base.md@@ -0,0 +1,184 @@+# Electron Security and Pattern Corrections++## Encryption Key Derivation++Never hardcode encryption keys. Derive from machine identifier.++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `encryptionKey: 'secret'` | `encryptionKey: machineIdSync().slice(0, 32)` |+| `encryptionKey: 'my-app-key'` | Machine-derived key |+| String literal encryption key | `node-machine-id` derivation |++```typescript+// WRONG - hardcoded key+const store = new Store({+ encryptionKey: 'flaredesk-secure-key',+});++// CORRECT - machine-derived+import { machineIdSync } from 'node-machine-id';++const store = new Store({+ encryptionKey: machineIdSync().slice(0, 32),+});+```++## Context Isolation++Always enable context isolation. Never disable it.++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `contextIsolation: false` | `contextIsolation: true` |+| `nodeIntegration: true` | `nodeIntegration: false` with preload |+| Direct `ipcRenderer` in renderer | `contextBridge.exposeInMainWorld` |++```typescript+// WRONG - insecure+webPreferences: {+ contextIsolation: false,+ nodeIntegration: true,+}++// CORRECT - secure+webPreferences: {+ preload: join(__dirname, 'preload.cjs'),+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: false, // Only if needed for native modules+}+```++## Error Handling++Never use empty catch blocks. Always log and distinguish error types.++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `catch { }` | `catch (err) { console.error(err); throw err; }` |+| `catch {}` (empty) | Proper error logging and re-throw |+| Silent error swallowing | Distinguish network vs auth errors |++```typescript+// WRONG - masks failures+try {+ await fetch(url);+} catch {+ // Silent+}++// CORRECT - proper error handling+try {+ await fetch(url);+} catch (err) {+ if (err instanceof TypeError) {+ console.error('[Network] Offline:', err.message);+ } else {+ console.error('[Auth] Error:', err);+ }+ throw err;+}+```++## OAuth State Storage++Store OAuth state persistently, not in memory.++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `let pendingState: string` | `store.set('pendingState', state)` |+| In-memory state storage | electron-store persistence |++```typescript+// WRONG - lost on restart+let pendingState: string | null = null;++// CORRECT - persisted+store.set('pendingState', state);+const pending = store.get('pendingState');+```++## Native Module Externalization++Always externalize Electron and native modules in Vite config.++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Bundling better-sqlite3 | `external: ['better-sqlite3']` |+| Bundling electron | `external: ['electron', ...]` |++```typescript+// vite.config.ts+rollupOptions: {+ external: ['electron', 'better-sqlite3', 'electron-store'],+}+```++## Preload Script Format++Preload scripts must use CommonJS format for Electron compatibility.++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Preload as ESM | Preload as CJS |+| `format: 'es'` for preload | `format: 'cjs'` for preload |++```typescript+// vite.config.ts - preload config+preload: {+ input: 'electron/preload.ts',+ vite: {+ build: {+ rollupOptions: {+ output: {+ format: 'cjs',+ entryFileNames: '[name].cjs',+ },+ },+ },+ },+},+```++## External Links++Open external links in system browser, never in Electron window.++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `window.open(url)` | `shell.openExternal(url)` |+| Opening links in BrowserWindow | System browser via shell |++```typescript+// In main process+mainWindow.webContents.setWindowOpenHandler(({ url }) => {+ shell.openExternal(url);+ return { action: 'deny' };+});++// IPC handler for renderer+ipcMain.handle('app:open-external', (_event, url: string) => {+ shell.openExternal(url);+});+```++## Token Expiration++Implement token refresh or sliding sessions. Never hardcode expiration without refresh.++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Hardcoded 30-day expiration | Expiration with refresh mechanism |+| No expiration handling | Check expiration with buffer |++```typescript+// Check with buffer before expiration+const session = store.get('session');+const expiresAt = new Date(session.expiresAt);+const bufferMs = 5 * 60 * 1000; // 5 minutes++if (Date.now() > expiresAt.getTime() - bufferMs) {+ await refreshToken(session.token);+}+```diff --git a/skills/electron-base/templates/electron-builder.json b/skills/electron-base/templates/electron-builder.jsonnew file mode 100644index 00000000..5218f985--- /dev/null+++ b/skills/electron-base/templates/electron-builder.json@@ -0,0 +1,50 @@+{+ "$schema": "https://raw.githubusercontent.com/electron-userland/electron-builder/master/packages/app-builder-lib/scheme.json",+ "appId": "com.yourcompany.myapp",+ "productName": "MyApp",+ "directories": {+ "output": "release"+ },+ "files": [+ "dist/**/*",+ "dist-electron/**/*"+ ],+ "mac": {+ "category": "public.app-category.productivity",+ "icon": "build/icon.icns",+ "hardenedRuntime": true,+ "gatekeeperAssess": false,+ "entitlements": "build/entitlements.mac.plist",+ "entitlementsInherit": "build/entitlements.mac.plist",+ "target": [+ {+ "target": "dmg",+ "arch": ["x64", "arm64"]+ }+ ],+ "protocols": [+ {+ "name": "MyApp",+ "schemes": ["myapp"]+ }+ ]+ },+ "win": {+ "icon": "build/icon.ico",+ "target": [+ {+ "target": "nsis",+ "arch": ["x64"]+ }+ ]+ },+ "linux": {+ "icon": "build/icons",+ "target": ["AppImage"],+ "category": "Office"+ },+ "nsis": {+ "oneClick": false,+ "allowToChangeInstallationDirectory": true+ }+}diff --git a/skills/electron-base/templates/ipc-handlers/auth.ts b/skills/electron-base/templates/ipc-handlers/auth.tsnew file mode 100644index 00000000..4feed977--- /dev/null+++ b/skills/electron-base/templates/ipc-handlers/auth.ts@@ -0,0 +1,253 @@+/**+ * OAuth Authentication IPC Handler+ *+ * Handles OAuth flow with:+ * - Machine-derived encryption (NOT hardcoded keys)+ * - CSRF protection via state parameter+ * - Proper error handling (no empty catch blocks)+ * - Token expiration with refresh capability+ */++import { ipcMain, shell } from 'electron';+import Store from 'electron-store';+import { machineIdSync } from 'node-machine-id';++// ============================================================================+// CONFIGURATION - Update for your app+// ============================================================================++const BACKEND_URL = 'https://your-api.example.com';++// ============================================================================+// TYPES+// ============================================================================++export interface Session {+ user: {+ id: string;+ email: string;+ name: string | null;+ image: string | null;+ };+ token: string;+ expiresAt: string;+ refreshToken?: string;+}++interface AuthStore {+ session: Session | null;+ pendingState: string | null;+}++// ============================================================================+// SECURE STORE+// ============================================================================++// IMPORTANT: Derive encryption key from machine ID, NEVER hardcode+const store = new Store<AuthStore>({+ name: 'app-auth',+ encryptionKey: machineIdSync().slice(0, 32), // Machine-unique 32-char key+ defaults: {+ session: null,+ pendingState: null,+ },+});++// ============================================================================+// IPC HANDLERS+// ============================================================================++export function setupAuth() {+ // Start OAuth flow+ ipcMain.handle(+ 'auth:start-oauth',+ async (_event, provider: 'google' | 'github') => {+ console.log('[OAuth] Starting flow for:', provider);++ // Generate cryptographically secure state for CSRF protection+ const state = crypto.randomUUID();+ store.set('pendingState', state);++ // Open system browser for OAuth+ const authUrl = `${BACKEND_URL}/api/auth/signin/${provider}?state=${state}`;++ try {+ await shell.openExternal(authUrl);+ console.log('[OAuth] Browser opened successfully');+ } catch (err) {+ console.error('[OAuth] Failed to open browser:', err);+ throw err;+ }+ }+ );++ // Get current session+ ipcMain.handle('auth:get-session', async () => {+ const session = store.get('session');+ if (!session) return null;++ // Check if session is expired (with 5-minute buffer)+ const expiresAt = new Date(session.expiresAt);+ const bufferMs = 5 * 60 * 1000;++ if (Date.now() > expiresAt.getTime() - bufferMs) {+ // Try to refresh if we have a refresh token+ if (session.refreshToken) {+ try {+ const refreshed = await refreshSession(session.refreshToken);+ return refreshed;+ } catch (err) {+ console.error('[Auth] Token refresh failed:', err);+ store.set('session', null);+ return null;+ }+ }++ // No refresh token, session expired+ store.set('session', null);+ return null;+ }++ // Verify session with backend (if online)+ try {+ const response = await fetch(`${BACKEND_URL}/api/me`, {+ headers: {+ Authorization: `Bearer ${session.token}`,+ },+ });++ if (!response.ok) {+ console.warn('[Auth] Session invalid, clearing');+ store.set('session', null);+ return null;+ }++ return session;+ } catch (err) {+ // Network error - return cached session for offline use+ if (err instanceof TypeError) {+ console.log('[Auth] Offline, using cached session');+ return session;+ }++ console.error('[Auth] Unexpected error verifying session:', err);+ throw err;+ }+ });++ // Logout+ ipcMain.handle('auth:logout', async () => {+ const session = store.get('session');++ if (session) {+ try {+ await fetch(`${BACKEND_URL}/api/auth/signout`, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${session.token}`,+ },+ });+ } catch (err) {+ // Log but don't throw - clear local session regardless+ if (err instanceof TypeError) {+ console.log('[Auth] Offline during logout, clearing local session');+ } else {+ console.error('[Auth] Logout request failed:', err);+ }+ }+ }++ store.set('session', null);+ store.set('pendingState', null);+ });+}++// ============================================================================+// OAUTH CALLBACK HANDLER+// ============================================================================++export async function handleAuthCallback(+ token: string,+ state: string+): Promise<Session> {+ const pendingState = store.get('pendingState');++ // CSRF protection - validate state matches+ if (state !== pendingState) {+ throw new Error('State mismatch - possible CSRF attack');+ }++ // Clear pending state immediately+ store.set('pendingState', null);++ // Get user info using the token+ const response = await fetch(`${BACKEND_URL}/api/me`, {+ headers: {+ Authorization: `Bearer ${token}`,+ },+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`Failed to get user info: ${response.status} ${errorText}`);+ }++ const { user, refreshToken } = await response.json();++ // Create session with reasonable expiration+ const session: Session = {+ user,+ token,+ expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(), // 7 days+ refreshToken, // Store refresh token if provided+ };++ store.set('session', session);++ return session;+}++// ============================================================================+// TOKEN REFRESH+// ============================================================================++async function refreshSession(refreshToken: string): Promise<Session> {+ const response = await fetch(`${BACKEND_URL}/api/auth/refresh`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ refreshToken }),+ });++ if (!response.ok) {+ throw new Error(`Token refresh failed: ${response.status}`);+ }++ const { token, user, refreshToken: newRefreshToken, expiresIn } =+ await response.json();++ const session: Session = {+ user,+ token,+ expiresAt: new Date(Date.now() + expiresIn * 1000).toISOString(),+ refreshToken: newRefreshToken || refreshToken,+ };++ store.set('session', session);++ return session;+}++// ============================================================================+// UTILITY EXPORTS+// ============================================================================++export function getStoredSession(): Session | null {+ return store.get('session');+}++export function getSessionToken(): string | null {+ const session = store.get('session');+ return session?.token || null;+}diff --git a/skills/electron-base/templates/ipc-handlers/store.ts b/skills/electron-base/templates/ipc-handlers/store.tsnew file mode 100644index 00000000..ec362a43--- /dev/null+++ b/skills/electron-base/templates/ipc-handlers/store.ts@@ -0,0 +1,102 @@+/**+ * Persistent Storage IPC Handler+ *+ * Provides encrypted storage for app settings and data using electron-store.+ * Uses machine-derived encryption key for security.+ */++import { ipcMain } from 'electron';+import Store from 'electron-store';+import { machineIdSync } from 'node-machine-id';++// ============================================================================+// TYPES+// ============================================================================++export interface Settings {+ theme: 'light' | 'dark' | 'system';+ // Add your app-specific settings here+}++interface AppStore {+ settings: Settings;+ // Add other persisted data types here+ [key: string]: unknown;+}++// ============================================================================+// STORE INITIALIZATION+// ============================================================================++// IMPORTANT: Derive encryption key from machine ID, NEVER hardcode+const store = new Store<AppStore>({+ name: 'app-data',+ encryptionKey: machineIdSync().slice(0, 32), // Machine-unique 32-char key+ defaults: {+ settings: {+ theme: 'system',+ },+ },+ // Optional: Clear storage on corrupted JSON+ clearInvalidConfig: true,+});++// ============================================================================+// IPC HANDLERS+// ============================================================================++export function setupStore() {+ // Generic get+ ipcMain.handle('store:get', (_event, key: string) => {+ return store.get(key);+ });++ // Generic set+ ipcMain.handle('store:set', (_event, key: string, value: unknown) => {+ store.set(key, value);+ });++ // Generic delete+ ipcMain.handle('store:delete', (_event, key: string) => {+ store.delete(key as keyof AppStore);+ });++ // Get settings (typed)+ ipcMain.handle('store:get-settings', () => {+ return store.get('settings');+ });++ // Update settings (partial update)+ ipcMain.handle('store:update-settings', (_event, updates: Partial<Settings>) => {+ const current = store.get('settings');+ store.set('settings', { ...current, ...updates });+ });+}++// ============================================================================+// UTILITY EXPORTS (for use in main process)+// ============================================================================++export function getSettings(): Settings {+ return store.get('settings');+}++export function updateSettings(updates: Partial<Settings>): void {+ const current = store.get('settings');+ store.set('settings', { ...current, ...updates });+}++export function getValue<T>(key: string): T | undefined {+ return store.get(key) as T | undefined;+}++export function setValue<T>(key: string, value: T): void {+ store.set(key, value);+}++export function deleteValue(key: string): void {+ store.delete(key as keyof AppStore);+}++// Export store instance for advanced use cases+export { store };diff --git a/skills/electron-base/templates/main.ts b/skills/electron-base/templates/main.tsnew file mode 100644index 00000000..a6e1d829--- /dev/null+++ b/skills/electron-base/templates/main.ts@@ -0,0 +1,215 @@+/**+ * Electron Main Process+ *+ * This is the entry point for the Electron main process.+ * It handles window creation, protocol registration, and IPC setup.+ */++import { app, BrowserWindow, ipcMain, shell, protocol, dialog } from 'electron';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { setupAuth, handleAuthCallback } from './ipc-handlers/auth';+import { setupStore } from './ipc-handlers/store';++// ES modules equivalent of __dirname+const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);++// ============================================================================+// CONFIGURATION - Update these for your app+// ============================================================================++const PROTOCOL_SCHEME = 'myapp'; // Custom protocol (e.g., myapp://auth/callback)+const DEV_SERVER_URL = 'http://localhost:5173';++// ============================================================================+// PROTOCOL REGISTRATION+// ============================================================================++// Register custom protocol for OAuth callback+if (process.defaultApp) {+ // Development: need to pass executable path+ if (process.argv.length >= 2) {+ app.setAsDefaultProtocolClient(PROTOCOL_SCHEME, process.execPath, [+ process.argv[1],+ ]);+ }+} else {+ // Production: simpler registration+ app.setAsDefaultProtocolClient(PROTOCOL_SCHEME);+}++// ============================================================================+// WINDOW MANAGEMENT+// ============================================================================++let mainWindow: BrowserWindow | null = null;+const isDev = process.env.NODE_ENV !== 'production' || !app.isPackaged;++function createWindow() {+ mainWindow = new BrowserWindow({+ width: 1200,+ height: 800,+ minWidth: 800,+ minHeight: 600,+ webPreferences: {+ preload: join(__dirname, 'preload.cjs'),+ contextIsolation: true, // REQUIRED - isolates preload from renderer+ nodeIntegration: false, // REQUIRED - no Node.js in renderer+ sandbox: false, // Required for better-sqlite3 - document this trade-off+ },+ // macOS title bar styling+ titleBarStyle: 'hiddenInset',+ trafficLightPosition: { x: 16, y: 16 },+ show: false, // Show when ready to prevent flash+ });++ // Show window when ready+ mainWindow.once('ready-to-show', () => {+ mainWindow?.show();+ });++ // Load the app+ if (isDev) {+ mainWindow.loadURL(DEV_SERVER_URL);+ mainWindow.webContents.openDevTools();+ } else {+ mainWindow.loadFile(join(__dirname, '../dist/index.html'));+ }++ // Handle external links - open in system browser+ mainWindow.webContents.setWindowOpenHandler(({ url }) => {+ shell.openExternal(url);+ return { action: 'deny' };+ });++ mainWindow.on('closed', () => {+ mainWindow = null;+ });+}++// ============================================================================+// SINGLE INSTANCE LOCK+// ============================================================================++const gotTheLock = app.requestSingleInstanceLock();++if (!gotTheLock) {+ // Another instance is running - quit this one+ app.quit();+} else {+ // Handle second instance launch (Windows/Linux protocol handling)+ app.on('second-instance', (_event, commandLine) => {+ const url = commandLine.find((arg) =>+ arg.startsWith(`${PROTOCOL_SCHEME}://`)+ );+ if (url) {+ handleProtocolUrl(url);+ }++ // Focus main window+ if (mainWindow) {+ if (mainWindow.isMinimized()) mainWindow.restore();+ mainWindow.focus();+ }+ });+}++// ============================================================================+// PROTOCOL URL HANDLING+// ============================================================================++function handleProtocolUrl(url: string) {+ try {+ const parsedUrl = new URL(url);++ // Handle OAuth callback+ if (+ parsedUrl.pathname === '//auth/callback' ||+ parsedUrl.pathname === '/auth/callback'+ ) {+ const token = parsedUrl.searchParams.get('token');+ const state = parsedUrl.searchParams.get('state');+ const error = parsedUrl.searchParams.get('error');++ if (error) {+ mainWindow?.webContents.send('auth:error', error);+ } else if (token && state) {+ handleAuthCallback(token, state)+ .then((session) => {+ mainWindow?.webContents.send('auth:success', session);+ })+ .catch((err) => {+ console.error('[Auth] Callback error:', err);+ mainWindow?.webContents.send('auth:error', err.message);+ });+ }+ }+ } catch (err) {+ console.error('[Protocol] Failed to parse URL:', err);+ }+}++// macOS handles protocol via open-url event+app.on('open-url', (_event, url) => {+ handleProtocolUrl(url);+});++// ============================================================================+// APP LIFECYCLE+// ============================================================================++app.whenReady().then(() => {+ // Register protocol handler for development+ protocol.handle(PROTOCOL_SCHEME, (request) => {+ handleProtocolUrl(request.url);+ return new Response('', { status: 200 });+ });++ createWindow();++ // Setup IPC handlers+ setupAuth();+ setupStore();++ // macOS: re-create window when dock icon clicked+ app.on('activate', () => {+ if (BrowserWindow.getAllWindows().length === 0) {+ createWindow();+ }+ });+});++// Quit when all windows are closed (except macOS)+app.on('window-all-closed', () => {+ if (process.platform !== 'darwin') {+ app.quit();+ }+});++// ============================================================================+// GENERAL IPC HANDLERS+// ============================================================================++ipcMain.handle('app:get-version', () => {+ return app.getVersion();+});++ipcMain.handle('app:open-external', (_event, url: string) => {+ shell.openExternal(url);+});++ipcMain.handle('dialog:open-directory', async () => {+ if (!mainWindow) return null;++ const result = await dialog.showOpenDialog(mainWindow, {+ properties: ['openDirectory', 'createDirectory'],+ title: 'Select a folder',+ });++ if (result.canceled) {+ return null;+ }++ return result.filePaths[0];+});diff --git a/skills/electron-base/templates/preload.ts b/skills/electron-base/templates/preload.tsnew file mode 100644index 00000000..8b6c7fa0--- /dev/null+++ b/skills/electron-base/templates/preload.ts@@ -0,0 +1,132 @@+/**+ * Electron Preload Script+ *+ * This script runs in a privileged context and exposes a safe, typed API+ * to the renderer process via contextBridge.+ *+ * IMPORTANT: This file must be compiled to CommonJS format (.cjs)+ * because Electron's preload scripts don't support ES modules.+ */++import { contextBridge, ipcRenderer } from 'electron';++// ============================================================================+// TYPE DEFINITIONS+// ============================================================================++export interface Session {+ user: {+ id: string;+ email: string;+ name: string | null;+ image: string | null;+ };+ token: string;+ expiresAt: string;+}++export interface Settings {+ theme: 'light' | 'dark' | 'system';+}++// ============================================================================+// API INTERFACE+// ============================================================================++export interface ElectronAPI {+ // Authentication+ auth: {+ /** Start OAuth flow in system browser */+ startOAuth: (provider: 'google' | 'github') => Promise<void>;+ /** Get current session (null if not authenticated) */+ getSession: () => Promise<Session | null>;+ /** Log out and clear session */+ logout: () => Promise<void>;+ /** Subscribe to auth success events (returns unsubscribe function) */+ onSuccess: (callback: (session: Session) => void) => () => void;+ /** Subscribe to auth error events (returns unsubscribe function) */+ onError: (callback: (error: string) => void) => () => void;+ };++ // Persistent storage+ store: {+ /** Get a value from storage */+ get: <T>(key: string) => Promise<T | undefined>;+ /** Set a value in storage */+ set: <T>(key: string, value: T) => Promise<void>;+ /** Delete a value from storage */+ delete: (key: string) => Promise<void>;+ /** Get settings */+ getSettings: () => Promise<Settings>;+ /** Update settings */+ updateSettings: (settings: Partial<Settings>) => Promise<void>;+ };++ // App utilities+ app: {+ /** Get app version */+ getVersion: () => Promise<string>;+ /** Open URL in system browser */+ openExternal: (url: string) => Promise<void>;+ /** Open directory picker dialog */+ selectDirectory: () => Promise<string | null>;+ };+}++// ============================================================================+// API IMPLEMENTATION+// ============================================================================++const electronAPI: ElectronAPI = {+ auth: {+ startOAuth: (provider) => ipcRenderer.invoke('auth:start-oauth', provider),+ getSession: () => ipcRenderer.invoke('auth:get-session'),+ logout: () => ipcRenderer.invoke('auth:logout'),++ // Event subscriptions with cleanup+ onSuccess: (callback) => {+ const handler = (_event: Electron.IpcRendererEvent, session: Session) =>+ callback(session);+ ipcRenderer.on('auth:success', handler);+ // Return unsubscribe function+ return () => ipcRenderer.removeListener('auth:success', handler);+ },+ onError: (callback) => {+ const handler = (_event: Electron.IpcRendererEvent, error: string) =>+ callback(error);+ ipcRenderer.on('auth:error', handler);+ return () => ipcRenderer.removeListener('auth:error', handler);+ },+ },++ store: {+ get: (key) => ipcRenderer.invoke('store:get', key),+ set: (key, value) => ipcRenderer.invoke('store:set', key, value),+ delete: (key) => ipcRenderer.invoke('store:delete', key),+ getSettings: () => ipcRenderer.invoke('store:get-settings'),+ updateSettings: (settings) =>+ ipcRenderer.invoke('store:update-settings', settings),+ },++ app: {+ getVersion: () => ipcRenderer.invoke('app:get-version'),+ openExternal: (url) => ipcRenderer.invoke('app:open-external', url),+ selectDirectory: () => ipcRenderer.invoke('dialog:open-directory'),+ },+};++// ============================================================================+// EXPOSE TO RENDERER+// ============================================================================++contextBridge.exposeInMainWorld('electron', electronAPI);++// ============================================================================+// GLOBAL TYPE DECLARATION+// ============================================================================++declare global {+ interface Window {+ electron: ElectronAPI;+ }+}diff --git a/skills/electron-base/templates/vite.config.ts b/skills/electron-base/templates/vite.config.tsnew file mode 100644index 00000000..0703870f--- /dev/null+++ b/skills/electron-base/templates/vite.config.ts@@ -0,0 +1,81 @@+/**+ * Vite Configuration for Electron + React+ *+ * This configuration handles:+ * - React app (renderer process)+ * - Electron main process (ES modules)+ * - Preload script (CommonJS - required by Electron)+ * - Native module externalization+ */++import { defineConfig } from 'vite';+import react from '@vitejs/plugin-react';+import tailwindcss from '@tailwindcss/vite';+import electron from 'vite-plugin-electron/simple';+import { resolve, dirname } from 'path';+import { fileURLToPath } from 'url';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);++export default defineConfig({+ plugins: [+ react(),+ tailwindcss(),+ electron({+ // Main process configuration+ main: {+ entry: 'electron/main.ts',+ vite: {+ build: {+ outDir: 'dist-electron',+ rollupOptions: {+ // IMPORTANT: Externalize Electron and native modules+ // These cannot be bundled and must be loaded at runtime+ external: ['electron', 'better-sqlite3', 'electron-store'],+ output: {+ format: 'es',+ entryFileNames: '[name].mjs',+ },+ },+ },+ },+ },++ // Preload script configuration+ // IMPORTANT: Must be CommonJS format (.cjs) for Electron compatibility+ preload: {+ input: 'electron/preload.ts',+ vite: {+ build: {+ outDir: 'dist-electron',+ rollupOptions: {+ output: {+ format: 'cjs',+ entryFileNames: '[name].cjs',+ },+ },+ },+ },+ },++ // Renderer process - uses default Vite build+ renderer: {},+ }),+ ],++ resolve: {+ alias: {+ '@': resolve(__dirname, 'src'),+ },+ },++ build: {+ outDir: 'dist',+ },++ // Ensure React is properly bundled (prevents duplicate React instances)+ optimizeDeps: {+ include: ['react', 'react-dom'],+ },+});