蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

在 Node.js v24 隔离沙箱与事件总线上实测主渲职责、三种 IPC 模式与 contextBridge 白名单

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-core-concepts.mjs
explore-core-concepts.mjs184 行
import { EventEmitter } from 'node:events';
import os from 'node:os';
import path from 'node:path';
import vm from 'node:vm';

function makeCase(name, expected, actual) {
  return {
    name,
    passed: JSON.stringify(actual) === JSON.stringify(expected),
    expected,
    actual,
  };
}

const cases = [];

// Case 1: Main process app module & BrowserWindow configuration contract
{
  let appUserModelId = null;
  const app = {
    isPackaged: false,
    setAppUserModelId(id) {
      appUserModelId = id;
    },
    getPath(name) {
      if (name === 'userData') {
        return path.join(os.homedir(), '.demo-electron-userdata');
      }
      return os.homedir();
    },
  };
  app.setAppUserModelId('com.bluesky.electron.demo');

  const winOpts = {
    width: 1024,
    height: 768,
    resizable: true,
    webPreferences: {
      preload: './preload.js',
      nodeIntegration: false,
    },
  };
  const userDataPath = app.getPath('userData');
  const nativeModules = ['Menu', 'MenuItem', 'Tray', 'Dialog', 'Notification', 'shell'];

  const expected = {
    dimensions: [1024, 768],
    resizable: true,
    nodeIntegration: false,
    appUserModelId: 'com.bluesky.electron.demo',
    isPackaged: false,
    userDataEndsCorrectly: true,
    nativeModuleCount: 6,
  };
  const actual = {
    dimensions: [winOpts.width, winOpts.height],
    resizable: winOpts.resizable,
    nodeIntegration: winOpts.webPreferences.nodeIntegration,
    appUserModelId,
    isPackaged: app.isPackaged,
    userDataEndsCorrectly: path.basename(userDataPath) === '.demo-electron-userdata',
    nativeModuleCount: nativeModules.length,
  };
  cases.push(makeCase('main_process_app_and_window_config', expected, actual));
}

// Case 2: Multi-window independent renderer isolation
{
  const windows = [
    { id: 1, title: 'Main', source: 'loadFile:index.html', open: true },
    { id: 2, title: 'Docs', source: 'loadURL:https://example.com', open: true },
  ];
  windows[0].open = false;

  const ctx = vm.createContext({});
  const rendererCheck = vm.runInContext(
    `({ hasFs: typeof fs !== 'undefined', hasRequire: typeof require !== 'undefined' })`,
    ctx,
  );

  const expected = {
    remainingOpenIds: [2],
    remainingSource: 'loadURL:https://example.com',
    hasFs: false,
    hasRequire: false,
  };
  const actual = {
    remainingOpenIds: windows.filter((w) => w.open).map((w) => w.id),
    remainingSource: windows[1].source,
    ...rendererCheck,
  };
  cases.push(makeCase('multi_renderer_isolation_and_limits', expected, actual));
}

// Case 3: Three IPC modes (one-way send/on, reply, invoke/handle) + best practices
{
  const ipcMain = new EventEmitter();
  const ipcRenderer = new EventEmitter();
  const handlers = new Map();

  let oneWayReceived = null;
  ipcMain.on('ping', (_event, arg) => {
    oneWayReceived = arg;
  });
  ipcMain.emit('ping', {}, 'hello from renderer');

  let repliedVersion = null;
  ipcRenderer.on('getVersionResponse', (_event, version) => {
    repliedVersion = version;
  });
  ipcMain.on('getVersion', (event) => {
    event.reply('getVersionResponse', '1.2.3');
  });
  ipcMain.emit('getVersion', {
    reply: (ch, data) => ipcRenderer.emit(ch, {}, data),
  });

  handlers.set('get-app-path', () => '/mock/userData');
  handlers.set('user:getData', (_event, req) => {
    if (!req || typeof req.uid !== 'number') {
      throw new TypeError('invalid uid');
    }
    return JSON.parse(JSON.stringify({ uid: req.uid, role: 'member' }));
  });
  const invoke = async (channel, ...args) => handlers.get(channel)({}, ...args);

  const appPath = await invoke('get-app-path');
  const userData = await invoke('user:getData', { uid: 7 });

  const expected = {
    oneWayReceived: 'hello from renderer',
    repliedVersion: '1.2.3',
    invokedPath: '/mock/userData',
    structuredUser: { uid: 7, role: 'member' },
    namespacedChannelValid: true,
  };
  const actual = {
    oneWayReceived,
    repliedVersion,
    invokedPath: appPath,
    structuredUser: userData,
    namespacedChannelValid: /^[a-z]+:[a-zA-Z]+$/.test('user:getData'),
  };
  cases.push(makeCase('ipc_three_patterns_verified', expected, actual));
}

// Case 4: Preload contextBridge whitelist & sandbox mode isolation
{
  const ipcInvoke = async (channel) => {
    if (channel === 'getVersion') return '2.0.0';
    throw new Error('blocked');
  };

  // Preload exposes only whitelisted method under contextIsolation: true & sandbox: true
  const bridgeAPI = Object.freeze({
    getAppVersion: () => ipcInvoke('getVersion'),
  });

  const sandboxRealm = { window: { electronAPI: bridgeAPI } };
  const ctx = vm.createContext(sandboxRealm);
  const versionPromise = vm.runInContext('window.electronAPI.getAppVersion()', ctx);
  const directNodeBlocked = vm.runInContext(
    `(() => { try { require('fs'); return false; } catch (e) { return e.name === 'ReferenceError'; } })()`,
    ctx,
  );
  const exposedKeys = vm.runInContext('Object.keys(window.electronAPI)', ctx);

  const expected = {
    appVersion: '2.0.0',
    directNodeBlocked: true,
    exposedKeys: ['getAppVersion'],
    sandboxEnforced: true,
  };
  const actual = {
    appVersion: await versionPromise,
    directNodeBlocked,
    exposedKeys,
    sandboxEnforced: true,
  };
  cases.push(makeCase('preload_context_bridge_and_sandbox', expected, actual));
}

console.log(JSON.stringify({ version: process.version, cases }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Node.js v24.22.3 本地运行环境。

入口文件:projects/electron-core-concepts-lab/explore-core-concepts.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-core-concepts.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Electron

课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a1081.zip

下载课程关联工程包:Electron

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1082.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习