import { app, BrowserWindow, ipcMain } from "electron"; import crypto from "node:crypto"; import fsSync from "node:fs"; import os from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; import { assertCspRequest, assertNavigateRequest, CH, isAllowedNavigation, } from "../shared/ipc"; app.setName("CSP Integrity Lab"); const isSmoke = process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1"; const isShots = process.argv.includes("--shots"); const tempData = isSmoke || isShots ? path.join(os.tmpdir(), `integrity-${isSmoke ? "smoke" : "shots"}-${process.pid}`) : ""; if (tempData) app.setPath("userData", tempData); const appRoot = app.getAppPath(); const resourceDir = path.join(appRoot, "resources"); const workspace = path.join(app.getPath("userData"), "workspace"); let win = null; let events = []; let csp = { policy: "", violations: [], results: [] }; let attempts = []; let integrity = { manifestVersion: 0, good: { fileName: "notice.txt", expected: "", actual: "", ok: false }, tampered: null, }; let packaging = { isPackaged: false, appPath: "", asar: false, fusesVerified: false, note: "", }; const flags = { navigationGuard: false, windowOpenDenied: false, webviewBlocked: false, }; function log(kind, detail) { events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40); broadcast(); } function broadcast() { if (win && !win.isDestroyed()) { win.webContents.send("integrity:event", { at: Date.now() }); } } function sha256(filePath) { return crypto .createHash("sha256") .update(fsSync.readFileSync(filePath)) .digest("hex"); } function verifyIntegrity() { const manifestPath = path.join(resourceDir, "manifest.json"); const noticePath = path.join(resourceDir, "notice.txt"); try { const manifest = JSON.parse(fsSync.readFileSync(manifestPath, "utf8")); const expected = manifest.files?.["notice.txt"] ?? ""; const actual = sha256(noticePath); const good = { fileName: "notice.txt", expected, actual, ok: expected !== "" && expected === actual, }; const tamperedPath = path.join(workspace, "notice.tampered.txt"); if (!fsSync.existsSync(tamperedPath)) { const original = fsSync.readFileSync(noticePath, "utf8"); fsSync.writeFileSync(tamperedPath, `${original}\n攻击者追加的一行\n`, "utf8"); } const tamperedActual = sha256(tamperedPath); return { manifestVersion: manifest.version ?? 0, good, tampered: { fileName: "notice.tampered.txt", expected, actual: tamperedActual, ok: expected === tamperedActual, }, }; } catch (error) { log("integrity-error", error instanceof Error ? error.message : String(error)); return integrity; } } function policyVerdicts() { const current = win && !win.isDestroyed() ? win.webContents.getURL() : ""; const rows = [ ["应用自身", current], ["允许站点", "https://docs.xwrt.dev/ch46"], ["Electron 文档", "https://www.electronjs.org/docs"], ["http 降级", "http://docs.xwrt.dev/"], ["javascript", "javascript:alert(1)"], ["file 读取", "file:///etc/passwd"], ["未知主机", "https://evil.example/"], ]; return rows.map(([label, url]) => { const verdict = isAllowedNavigation(url, current); return { label, url: url || "(none)", allowed: verdict.allowed, reason: verdict.reason, observed: "policy", }; }); } function readExactVersions() { try { const pkg = JSON.parse(fsSync.readFileSync(path.join(appRoot, "package.json"), "utf8")); const deps = Object.entries(pkg.devDependencies ?? {}); const loose = deps.filter(([, version]) => !/^\d+\.\d+\.\d+$/.test(version)); return { pass: deps.length > 0 && loose.length === 0, detail: deps.length === 0 ? "no devDependencies" : loose.length === 0 ? `${deps.length} 个精确版本` : loose.map(([name]) => name).join(","), }; } catch (error) { return { pass: false, detail: error instanceof Error ? error.message : "READ_FAILED", }; } } function checks() { const policy = csp.policy; const versions = readExactVersions(); return [ { id: "default-src", label: "CSP default-src 'self'", pass: /default-src\s+'self'/.test(policy), detail: policy ? "present" : "missing", }, { id: "script-src", label: "script-src 'self' 且无 unsafe-inline", pass: /script-src\s+'self'/.test(policy) && !/script-src[^;]*unsafe-inline/.test(policy), detail: /script-src\s+'self'/.test(policy) ? "self" : "missing", }, { id: "unsafe-eval", label: "全策略无 unsafe-eval", pass: policy !== "" && !policy.includes("unsafe-eval"), detail: policy.includes("unsafe-eval") ? "present" : "absent", }, { id: "connect-src", label: "connect-src 无通配符", pass: (() => { const directives = policy.match(/connect-src([^;]*)/)?.[1] ?? ""; const scoped = directives.trim().length > 0; const wildcard = /(^|\s)\*(\s|$)/.test(directives.replace(/:\*/g, "")); return scoped && !wildcard; })(), detail: /connect-src\s+[^;]+/.test(policy) ? "scoped" : "missing", }, { id: "navigation", label: "will-navigate 白名单已安装", pass: flags.navigationGuard, detail: String(flags.navigationGuard), }, { id: "window-open", label: "setWindowOpenHandler 拒绝新窗口", pass: flags.windowOpenDenied, detail: String(flags.windowOpenDenied), }, { id: "webview", label: "will-attach-webview 被阻止", pass: flags.webviewBlocked, detail: String(flags.webviewBlocked), }, { id: "integrity", label: "资源哈希与清单一致", pass: integrity.good.ok, detail: integrity.good.ok ? "match" : "mismatch", }, { id: "tamper", label: "被篡改副本被拒绝", pass: integrity.tampered !== null && !integrity.tampered.ok, detail: integrity.tampered ? String(!integrity.tampered.ok) : "missing", }, { id: "versions", label: "依赖使用精确版本", pass: versions.pass, detail: versions.detail, }, ]; } function snapshot() { const list = checks(); const passed = list.filter((check) => check.pass).length; return { platform: process.platform, electronVersion: process.versions.electron, nodeVersion: process.versions.node, checks: list, score: Math.round((passed / list.length) * 100), csp: { policy: csp.policy, violations: csp.violations.map((row) => ({ ...row })), results: csp.results.map((row) => ({ ...row })), }, navigation: { policy: policyVerdicts(), attempts: attempts.map((row) => ({ ...row })), }, integrity: { manifestVersion: integrity.manifestVersion, good: { ...integrity.good }, tampered: integrity.tampered ? { ...integrity.tampered } : null, }, packaging, events: events.map((row) => ({ ...row })), }; } async function probeCsp() { if (!win || win.isDestroyed()) return csp; try { const result = (await win.webContents.executeJavaScript("window.__runCspProbes()")); csp = { policy: String(result.policy ?? ""), violations: Array.isArray(result.violations) ? result.violations : [], results: Array.isArray(result.results) ? result.results : [], }; log("csp", `违规 ${csp.violations.length} 条 · 探针 ${csp.results.filter((row) => row.blocked).length}/${csp.results.length} 被拦`); } catch (error) { log("csp-error", error instanceof Error ? error.message : String(error)); } broadcast(); return csp; } async function attemptNavigation(url) { if (!win || win.isDestroyed()) return; const current = win.webContents.getURL(); const verdict = isAllowedNavigation(url, current); const before = current; try { await win.webContents.executeJavaScript(`location.assign(${JSON.stringify(url)})`); } catch (error) { log("navigate-script", error instanceof Error ? error.message : String(error)); } await new Promise((resolve) => setTimeout(resolve, 300)); const after = win.isDestroyed() ? "(destroyed)" : win.webContents.getURL(); const row = { label: "location.assign", url, allowed: verdict.allowed, reason: verdict.reason, observed: before === after ? "blocked" : `navigated:${after}`, }; attempts = [row, ...attempts].slice(0, 20); log("navigate", `${verdict.allowed ? "允许" : "拦截"} ${url}`); broadcast(); } function resolvePreload() { const candidates = [ path.join(__dirname, "preload.cjs"), path.join(__dirname, "../preload/index.cjs"), path.join(__dirname, "preload.js"), ]; return (candidates.find((candidate) => fsSync.existsSync(candidate)) ?? candidates[0] ?? ""); } function createWindow() { const window = new BrowserWindow({ width: 1100, height: 860, show: false, title: "CSP 与导航完整性实验室", backgroundColor: "#ffffff", webPreferences: { preload: resolvePreload(), contextIsolation: true, sandbox: true, nodeIntegration: false, webSecurity: true, allowRunningInsecureContent: false, experimentalFeatures: false, webviewTag: false, spellcheck: false, backgroundThrottling: true, }, }); const contents = window.webContents; contents.setWindowOpenHandler(({ url }) => { attempts = [ { label: "window.open", url, allowed: false, reason: "WINDOW_OPEN_DENIED", observed: "blocked", }, ...attempts, ].slice(0, 20); log("window-open", `拒绝 ${url}`); return { action: "deny" }; }); flags.windowOpenDenied = true; contents.on("will-navigate", (event, url) => { const appFile = pathToFileURL(appRoot).href; if (url.startsWith(appFile)) return; if (url.startsWith("file://") && url.includes("/renderer/")) return; if (MAIN_WINDOW_VITE_DEV_SERVER_URL && url.startsWith(MAIN_WINDOW_VITE_DEV_SERVER_URL)) { return; } const verdict = isAllowedNavigation(url, contents.getURL()); if (!verdict.allowed) { event.preventDefault(); log("navigation", `拦截 ${url} · ${verdict.reason}`); } }); flags.navigationGuard = true; contents.on("will-attach-webview", (event) => { event.preventDefault(); log("webview", "拒绝 attach webview"); }); flags.webviewBlocked = true; window.once("ready-to-show", () => window.show()); contents.once("did-finish-load", () => { if (!window.isDestroyed() && !window.isVisible()) window.show(); log("ready", "CSP 与完整性界面已加载"); setTimeout(() => { void probeCsp(); }, 150); }); if (MAIN_WINDOW_VITE_DEV_SERVER_URL) { void window.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL); } else { void window.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`)); } win = window; return window; } function delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function evalRenderer(window, code) { let lastError = null; for (let attempt = 0; attempt < 3; attempt += 1) { try { return (await window.webContents.executeJavaScript(code)); } catch (caught) { lastError = caught; await delay(200); } } throw lastError instanceof Error ? lastError : new Error(String(lastError)); } async function waitForRenderer(window) { for (let attempt = 0; attempt < 160; attempt += 1) { if (window.isDestroyed()) return; try { const ready = await evalRenderer(window, "typeof window.__smoke === 'function'"); if (ready) return; } catch { // 页面仍在加载。 } await delay(100); } throw new Error("renderer did not become ready"); } async function runSmoke(window) { try { await waitForRenderer(window); await delay(1000); await waitForRenderer(window); const result = await evalRenderer(window, "window.__smoke()"); process.stdout.write(`${JSON.stringify({ evt: "smoke", ok: result.score === 100 && result.checks === 10 && result.passed === 10 && result.violations >= 3 && result.blockedProbes === 4 && result.policyRows === 7 && result.policyAllowed === 3 && result.attempts >= 2 && result.observedBlocked >= 2 && result.currentUrl.length > 0 && result.integrityOk && !result.tamperedOk && result.manifestVersion === 1 && result.events >= 4, ...result, })}\n`); app.quit(); } catch (caught) { process.stdout.write(`${JSON.stringify({ evt: "smoke", ok: false, message: String(caught) })}\n`); app.exit(1); } } async function capture(window, dir, file) { const image = await window.webContents.capturePage(); if (image.isEmpty()) throw new Error(`empty capture: ${file}`); const png = image.toPNG(); fsSync.writeFileSync(path.join(dir, file), png); fsSync.writeFileSync(path.join(dir, "raw", file), png); } async function runShots(window) { try { const dir = path.resolve(process.cwd(), "../../../docs/assets/images/46-csp-navigation-integrity"); fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true }); await waitForRenderer(window); await delay(1000); await waitForRenderer(window); await probeCsp(); await evalRenderer(window, `window.__prepareShots("csp")`); await delay(400); await capture(window, dir, "46-01-csp.png"); await evalRenderer(window, `window.__prepareShots("navigation")`); await delay(700); await capture(window, dir, "46-02-navigation.png"); await evalRenderer(window, `window.__prepareShots("integrity")`); await delay(400); await capture(window, dir, "46-03-integrity.png"); app.quit(); } catch (caught) { process.stdout.write(`${JSON.stringify({ evt: "shots-error", message: String(caught) })}\n`); app.exit(1); } } ipcMain.handle(CH.snapshot, () => snapshot()); ipcMain.handle(CH.runCsp, async (_event, raw) => { assertCspRequest(raw); await probeCsp(); return snapshot(); }); ipcMain.handle(CH.navigate, async (_event, raw) => { assertNavigateRequest(raw); await attemptNavigation(raw.url); return snapshot(); }); ipcMain.handle(CH.tamper, () => { integrity = verifyIntegrity(); log("tamper", integrity.tampered && !integrity.tampered.ok ? "篡改副本被拒绝" : "异常"); return snapshot(); }); ipcMain.handle(CH.refresh, async () => { await probeCsp(); integrity = verifyIntegrity(); log("refresh", "重新检查 CSP / 导航 / 完整性"); return snapshot(); }); app.whenReady().then(() => { fsSync.mkdirSync(workspace, { recursive: true }); integrity = verifyIntegrity(); packaging = { isPackaged: app.isPackaged, appPath: appRoot, asar: appRoot.endsWith(".asar"), fusesVerified: false, note: app.isPackaged ? "打包态可继续校验 ASAR 与 fuses(见第 54/48 章)" : "开发态无 ASAR,fuses 未读取;本章只验证 CSP/导航/哈希", }; const window = createWindow(); if (isSmoke) { void runSmoke(window); } else if (isShots) { void runShots(window); } app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } else { win?.show(); win?.focus(); } }); }); app.on("will-quit", () => { if (tempData) { try { fsSync.rmSync(tempData, { recursive: true, force: true }); } catch { // 清理失败不影响退出。 } } }); app.on("window-all-closed", () => { if (process.platform !== "darwin") app.quit(); }); //# sourceMappingURL=index.js.map