Electron主进程预加载脚本生成器 electron-main-preload-generator

这是一个用于生成安全Electron桌面应用程序主进程和预加载脚本的AI工具。它自动化创建符合安全最佳实践的代码样板,包括上下文隔离、IPC通信模式、内容安全策略等核心安全功能。适用于Electron开发者快速构建安全可靠的桌面应用,特别关注应用程序安全性和代码质量。关键词:Electron安全,桌面应用开发,IPC通信,上下文隔离,预加载脚本,代码生成器,安全最佳实践,TypeScript支持,沙箱环境,内容安全策略

前端开发 0 次安装 0 次浏览 更新于 2/25/2026

名称: electron-main-preload-generator description: 为Electron应用程序生成安全的主进程和预加载脚本样板代码,包含正确的上下文隔离、IPC模式和安全最佳实践 允许使用的工具: 读取, 写入, 编辑, Bash, Glob, Grep 标签: [electron, 桌面应用, 安全, ipc, 预加载脚本]

electron-main-preload-generator

生成安全的Electron主进程和预加载脚本,包含正确的上下文隔离、安全的IPC模式和全面的安全最佳实践。此技能创建遵循Electron安全指南的生产就绪样板代码。

功能

  • 生成具有正确窗口配置的安全主进程 (main.js/main.ts)
  • 创建具有上下文隔离IPC桥接的预加载脚本
  • 通过通道白名单实现安全的IPC模式
  • 配置内容安全策略 (CSP) 头部
  • 设置启用沙箱的安全BrowserWindow选项
  • 生成IPC通道的TypeScript类型定义
  • 为敏感API实现权限处理器

输入模式

{
  "type": "object",
  "properties": {
    "projectPath": {
      "type": "string",
      "description": "Electron项目根目录路径"
    },
    "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": "为应用程序定义IPC通道"
    },
    "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"]
}

输出模式

{
  "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"]
}

使用说明

  1. 分析现有项目: 检查现有的主进程/预加载文件和框架使用情况
  2. 确定安全需求: 基于应用程序功能和数据敏感性
  3. 生成主进程: 创建安全的BrowserWindow配置
  4. 生成预加载脚本: 实现上下文隔离的IPC桥接
  5. 生成类型定义: 如果使用TypeScript,创建IPC通道类型
  6. 验证安全性: 运行安全检查清单

生成的文件结构

src/
  main/
    main.ts              # 主进程入口点
    ipc-handlers.ts      # IPC处理器实现
    window-manager.ts    # 多窗口管理(可选)
    protocol-handler.ts  # 自定义协议注册(可选)
    permission-handler.ts # 权限请求处理
  preload/
    preload.ts           # 包含contextBridge的预加载脚本
    api.ts               # 暴露的API定义
  shared/
    ipc-channels.ts      # IPC通道定义
    types.ts             # 共享TypeScript类型

代码模板

安全主进程

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.responseHeaders,
        'Content-Security-Policy': [
          "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"
        ]
      }
    });
  });

  // 权限处理
  session.defaultSession.setPermissionRequestHandler((webContents, permission, callback) => {
    const allowedPermissions = ['clipboard-read', 'notifications'];
    callback(allowedPermissions.includes(permission));
  });

  return mainWindow;
}

安全预加载脚本

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暴露受保护的方法
contextBridge.exposeInMainWorld('electronAPI', {
  // 发送到主进程(单向)
  send: (channel: ToMainChannel, data: unknown) => {
    if (VALID_CHANNELS.toMain.includes(channel)) {
      ipcRenderer.send(channel, data);
    }
  },

  // 调用主进程并等待响应
  invoke: async <T>(channel: ToMainChannel, data?: unknown): Promise<T> => {
    if (VALID_CHANNELS.toMain.includes(channel)) {
      return ipcRenderer.invoke(channel, data);
    }
    throw new Error(`无效通道: ${channel}`);
  },

  // 订阅主进程事件
  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 () => {
        ipcRenderer.removeListener(channel, subscription);
      };
    }
    return () => {};
  },

  // 一次性监听器
  once: (channel: FromMainChannel, callback: (...args: unknown[]) => void) => {
    if (VALID_CHANNELS.fromMain.includes(channel)) {
      ipcRenderer.once(channel, (_event, ...args) => callback(...args));
    }
  },
});

TypeScript类型定义

// types/electron-api.d.ts
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;
  }
}

安全检查清单

安全措施 状态 详情
上下文隔离 必需 始终设置 contextIsolation: true
Node集成 必需 始终设置 nodeIntegration: false
沙箱 推荐 为渲染器设置 sandbox: true
Web安全 必需 永不禁用 webSecurity
CSP头部 推荐 严格的内容安全策略
远程模块 必需 确保 enableRemoteModule: false
IPC验证 必需 白名单并验证所有IPC通道
协议处理器 推荐 安全注册自定义协议
权限处理器 推荐 控制权限请求
导航守卫 推荐 限制导航到受信任的源

最佳实践

  1. 永不直接暴露 ipcRenderer - 始终使用通道白名单
  2. 验证所有IPC数据 - 在主进程处理器中清理输入
  3. 使用invoke/handle模式 - 用于请求/响应通信
  4. 最小化暴露的API表面 - 只暴露必要的部分
  5. 定期审计预加载脚本 - 检查安全漏洞
  6. 保持Electron更新 - 安全补丁频繁发布

社区参考

相关技能

  • electron-builder-config - 构建配置
  • electron-ipc-security-audit - 审计IPC实现
  • electron-auto-updater-setup - 自动更新配置

相关代理

  • electron-architect - Electron架构专业知识
  • desktop-security-auditor - 安全审计