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

离线实测 BrowserWindow 安全配置审计、CSP 指令解析、XSS 转义与 IPC 最小权限校验

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-security.mjs
explore-security.mjs190 行
function auditWebPreferences(prefs) {
  const issues = [];
  if (prefs.contextIsolation !== true) issues.push('contextIsolation_disabled');
  if (prefs.nodeIntegration !== false) issues.push('nodeIntegration_enabled');
  if (prefs.sandbox !== true) issues.push('sandbox_disabled');
  if (!prefs.preload) issues.push('missing_preload');
  return { safe: issues.length === 0, issues };
}

function caseWebPreferencesIsolationSandboxAudit() {
  const hardened = auditWebPreferences({
    contextIsolation: true,
    nodeIntegration: false,
    sandbox: true,
    preload: '/app/preload.js',
  });
  const risky = auditWebPreferences({
    contextIsolation: false,
    nodeIntegration: true,
    sandbox: false,
    preload: '',
  });
  const actual = {
    hardenedSafe: hardened.safe,
    hardenedIssues: hardened.issues.length,
    riskySafe: risky.safe,
    riskyIssues: risky.issues,
  };
  const expected = {
    hardenedSafe: true,
    hardenedIssues: 0,
    riskySafe: false,
    riskyIssues: ['contextIsolation_disabled', 'nodeIntegration_enabled', 'sandbox_disabled', 'missing_preload'],
  };
  return { name: 'web_preferences_isolation_sandbox_audit', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}

function parseCsp(content) {
  const directives = {};
  for (const part of content.split(';')) {
    const tokens = part.trim().split(/\s+/).filter(Boolean);
    if (tokens.length > 0) directives[tokens[0]] = tokens.slice(1);
  }
  return directives;
}

function escapeHtml(raw) {
  return raw
    .replaceAll('&', '&')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}

function caseCspPolicyParserAndXssGuard() {
  const cspText = `
    default-src 'self';
    script-src 'self';
    style-src 'self' 'unsafe-inline';
    img-src 'self' data:;
    connect-src 'self' https://api.example.com;
  `;
  const directives = parseCsp(cspText);
  const canConnectApi = directives['connect-src'].includes('https://api.example.com');
  const blocksRemoteScript = directives['script-src'].length === 1 && directives['script-src'][0] === "'self'";
  const escaped = escapeHtml('<img src=x onerror="alert(1)">');

  const actual = {
    directiveCount: Object.keys(directives).length,
    defaultSrc: directives['default-src'],
    blocksRemoteScript,
    canConnectApi,
    escapedPayload: escaped,
  };
  const expected = {
    directiveCount: 5,
    defaultSrc: ["'self'"],
    blocksRemoteScript: true,
    canConnectApi: true,
    escapedPayload: '&lt;img src=x onerror=&quot;alert(1)&quot;&gt;',
  };
  return { name: 'csp_policy_parser_and_xss_guard', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}

function validateIpcRequest(senderUrl, data) {
  if (!senderUrl.startsWith('file://') && !senderUrl.startsWith('app://')) {
    return { allowed: false, reason: 'untrusted_sender' };
  }
  if (typeof data !== 'string' || data.length === 0 || data.length > 100) {
    return { allowed: false, reason: 'invalid_input' };
  }
  if (data.includes('..') || /[;&|`]/.test(data)) {
    return { allowed: false, reason: 'injection_risk' };
  }
  return { allowed: true, sanitized: data.trim() };
}

function isSafeExternalUrl(rawUrl) {
  try {
    const parsed = new URL(rawUrl);
    return parsed.protocol === 'https:' || parsed.protocol === 'mailto:';
  } catch {
    return false;
  }
}

function caseIpcSenderAndInputValidation() {
  const ok = validateIpcRequest('file:///app/index.html', 'note-alpha');
  const badOrigin = validateIpcRequest('https://evil.example/page.html', 'note-alpha');
  const badLen = validateIpcRequest('file:///app/index.html', 'a'.repeat(101));
  const badTraversal = validateIpcRequest('file:///app/index.html', '../etc/passwd');

  const actual = {
    okAllowed: ok.allowed,
    badOriginReason: badOrigin.reason,
    badLenReason: badLen.reason,
    badTraversalReason: badTraversal.reason,
    httpsExternalAllowed: isSafeExternalUrl('https://www.electronjs.org/docs/latest/tutorial/security'),
    fileExternalAllowed: isSafeExternalUrl('file:///C:/Windows/System32/calc.exe'),
    jsExternalAllowed: isSafeExternalUrl('javascript:alert(1)'),
  };
  const expected = {
    okAllowed: true,
    badOriginReason: 'untrusted_sender',
    badLenReason: 'invalid_input',
    badTraversalReason: 'injection_risk',
    httpsExternalAllowed: true,
    fileExternalAllowed: false,
    jsExternalAllowed: false,
  };
  return { name: 'ipc_sender_and_input_validation', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}

function caseLeastPrivilegePreloadContract() {
  const allowedChannels = new Set(['get-data']);
  const invoked = [];
  const ipcRendererMock = {
    invoke: (channel, payload) => {
      if (!allowedChannels.has(channel)) throw new Error(`blocked:${channel}`);
      invoked.push(channel);
      return { channel, payload, ok: true };
    },
  };

  const mainWorld = {};
  const exposeInMainWorld = (key, api) => {
    mainWorld[key] = Object.freeze({ ...api });
  };

  exposeInMainWorld('api', {
    getData: () => ipcRendererMock.invoke('get-data', null),
  });

  const result = mainWorld.api.getData();
  let blockedRawAccess = false;
  try {
    ipcRendererMock.invoke('exec-shell', 'whoami');
  } catch (err) {
    blockedRawAccess = err.message === 'blocked:exec-shell';
  }

  const actual = {
    exposedKeys: Object.keys(mainWorld.api),
    isFrozen: Object.isFrozen(mainWorld.api),
    hasRawIpcRenderer: 'ipcRenderer' in mainWorld.api,
    getDataOk: result.ok,
    blockedRawAccess,
    invoked,
  };
  const expected = {
    exposedKeys: ['getData'],
    isFrozen: true,
    hasRawIpcRenderer: false,
    getDataOk: true,
    blockedRawAccess: true,
    invoked: ['get-data'],
  };
  return { name: 'least_privilege_preload_contract', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}

const cases = [
  caseWebPreferencesIsolationSandboxAudit(),
  caseCspPolicyParserAndXssGuard(),
  caseIpcSenderAndInputValidation(),
  caseLeastPrivilegePreloadContract(),
];

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

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

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

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

下载课程关联工程包:Electron

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

下载课程关联工程包:Electron

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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