示例工程 52-ci-matrix-smoke

52-ci-matrix-smoke/app/.tsc/main/index.js

javascript · 12 KB

import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { CH, } from "../shared/ipc";
import { RULES, scoreFindings, scanWorkflow, summarize } from "../shared/rules";
app.setName("CI Matrix 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(), `ci52-${process.pid}`) : "";
if (tempData)
    app.setPath("userData", tempData);
const appRoot = app.getAppPath();
const fixtureRoot = path.join(appRoot, "fixtures");
const FILES = ["good.yml", "bad.yml", "fork.yml"];
let win = null;
let events = [];
let workflows = [];
let expected = { match: false, checked: 0, mismatches: [] };
function log(kind, detail) {
    events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
    broadcast();
}
function broadcast() {
    if (win && !win.isDestroyed()) {
        win.webContents.send("ci:event", { at: Date.now() });
    }
}
function readExpected() {
    try {
        const raw = fsSync.readFileSync(path.join(fixtureRoot, "expected.json"), "utf8");
        const parsed = JSON.parse(raw);
        if (typeof parsed !== "object" || parsed === null)
            return {};
        return parsed;
    }
    catch {
        return {};
    }
}
function loadWorkflows() {
    workflows = FILES.map((file) => {
        const text = fsSync.readFileSync(path.join(fixtureRoot, file), "utf8");
        const { findings, flags } = scanWorkflow(text);
        const counts = summarize(findings);
        return {
            id: file.replace(".yml", ""),
            file,
            name: /^name:\s*(.+)$/m.exec(text)?.[1]?.trim() ?? file,
            flags,
            findings,
            score: scoreFindings(findings),
            high: counts.high,
            medium: counts.medium,
        };
    });
    const want = readExpected();
    const mismatches = [];
    for (const file of FILES) {
        const report = workflows.find((row) => row.file === file);
        const actual = [
            ...new Set((report?.findings ?? []).map((row) => row.ruleId)),
        ].sort();
        const expectedIds = [...(want[file] ?? [])].sort();
        if (actual.join(",") !== expectedIds.join(",")) {
            mismatches.push(`${file}: want [${expectedIds}] got [${actual}]`);
        }
    }
    expected = {
        match: mismatches.length === 0,
        checked: FILES.length,
        mismatches,
    };
    log("scan", `${workflows.reduce((sum, row) => sum + row.findings.length, 0)} 命中 · expected ${expected.match ? "match" : "mismatch"}`);
}
function byId(id) {
    return workflows.find((row) => row.id === id);
}
function checks() {
    const good = byId("good");
    const bad = byId("bad");
    const fork = byId("fork");
    const all = workflows.flatMap((row) => row.findings);
    const echo = workflows.filter((row) => row.flags.secretEcho).length;
    return [
        {
            id: "rules",
            label: "规则集加载完整(10 条)",
            pass: RULES.length === 10,
            detail: `${RULES.length} rules`,
        },
        {
            id: "good",
            label: "安全 workflow 0 命中",
            pass: good?.findings.length === 0,
            detail: String(good?.findings.length ?? -1),
        },
        {
            id: "bad",
            label: "坏 workflow 命中 9 条",
            pass: bad?.findings.length === 9,
            detail: String(bad?.findings.length ?? -1),
        },
        {
            id: "fork",
            label: "fork workflow 命中 10 条",
            pass: fork?.findings.length === 10,
            detail: String(fork?.findings.length ?? -1),
        },
        {
            id: "prt",
            label: "pull_request_target 被判高危",
            pass: fork?.findings.some((row) => row.ruleId === "R10" && row.severity === "high") === true,
            detail: fork?.findings.some((row) => row.ruleId === "R10")
                ? "R10"
                : "missing",
        },
        {
            id: "echo",
            label: "两处 secret echo 被标出",
            pass: echo === 2,
            detail: String(echo),
        },
        {
            id: "matrix",
            label: "安全 workflow 覆盖 3 个 OS",
            pass: good?.flags.oses.length === 3,
            detail: String(good?.flags.oses.length ?? 0),
        },
        {
            id: "flags",
            label: "安全 workflow 的 xvfb/cache/artifact/timeout 齐全",
            pass: good?.flags.xvfb === true &&
                good.flags.cache &&
                good.flags.frozen &&
                good.flags.artifact &&
                good.flags.timeout &&
                good.flags.permissions &&
                good.flags.nodePinned,
            detail: good
                ? `${good.flags.xvfb}/${good.flags.cache}/${good.flags.artifact}`
                : "missing",
        },
        {
            id: "expected",
            label: "检测结果与 expected.json 一致",
            pass: expected.match,
            detail: `${expected.checked} 文件 / ${expected.mismatches.length} 差异`,
        },
        {
            id: "high",
            label: "高危总数 3",
            pass: all.filter((row) => row.severity === "high").length === 3,
            detail: String(all.filter((row) => row.severity === "high").length),
        },
    ];
}
function snapshot() {
    const list = checks();
    const passed = list.filter((check) => check.pass).length;
    const all = workflows.flatMap((row) => row.findings);
    return {
        platform: process.platform,
        electronVersion: process.versions.electron,
        nodeVersion: process.versions.node,
        workflows: workflows.map((row) => ({
            ...row,
            findings: row.findings.map((finding) => ({ ...finding })),
            flags: { ...row.flags, oses: [...row.flags.oses] },
        })),
        rules: RULES.map((rule) => ({ ...rule })),
        expected: { ...expected, mismatches: [...expected.mismatches] },
        checks: list,
        score: Math.round((passed / list.length) * 100),
        totals: {
            findings: all.length,
            high: all.filter((row) => row.severity === "high").length,
            medium: all.filter((row) => row.severity === "medium").length,
            echo: workflows.filter((row) => row.flags.secretEcho).length,
        },
        events: events.map((row) => ({ ...row })),
    };
}
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: "CI 矩阵实验室",
        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(() => ({ action: "deny" }));
    contents.on("will-navigate", (event, url) => {
        if (!url.startsWith("file://"))
            event.preventDefault();
    });
    contents.on("will-attach-webview", (event) => event.preventDefault());
    window.once("ready-to-show", () => window.show());
    contents.once("did-finish-load", () => {
        if (!window.isDestroyed() && !window.isVisible())
            window.show();
        log("ready", "CI 矩阵界面已加载");
    });
    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 lastCaught = null;
    for (let attempt = 0; attempt < 3; attempt += 1) {
        try {
            return (await window.webContents.executeJavaScript(code));
        }
        catch (caught) {
            lastCaught = caught;
            await delay(150);
        }
    }
    throw lastCaught instanceof Error
        ? lastCaught
        : new Error(String(lastCaught));
}
async function waitForRenderer(window) {
    for (let attempt = 0; attempt < 160; attempt += 1) {
        if (window.isDestroyed())
            return;
        try {
            const ready = await evalRenderer(window, "typeof window.__demo === '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(600);
        await waitForRenderer(window);
        const state = await evalRenderer(window, "window.__demo()");
        process.stdout.write(`${JSON.stringify({
            evt: "smoke",
            ok: state.score === 100 &&
                state.checks === 10 &&
                state.passed === 10 &&
                state.goodFindings === 0 &&
                state.badFindings === 9 &&
                state.forkFindings === 10 &&
                state.high === 3 &&
                state.echo === 2 &&
                state.matrix === 3 &&
                state.expectedMatch &&
                state.mismatches === 0 &&
                state.workflows === 3 &&
                state.prt,
            ...state,
        })}\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/52-ci-matrix-smoke");
        fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
        await waitForRenderer(window);
        await delay(600);
        await waitForRenderer(window);
        await evalRenderer(window, `window.__prepareShots("good")`);
        await delay(250);
        await capture(window, dir, "52-01-good.png");
        await evalRenderer(window, `window.__prepareShots("bad")`);
        await delay(250);
        await capture(window, dir, "52-02-bad.png");
        await evalRenderer(window, `window.__prepareShots("fork")`);
        await delay(250);
        await capture(window, dir, "52-03-fork.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.scan, () => {
    loadWorkflows();
    return snapshot();
});
ipcMain.handle(CH.refresh, () => {
    loadWorkflows();
    log("refresh", "重新扫描 workflow fixtures");
    return snapshot();
});
app.whenReady().then(() => {
    loadWorkflows();
    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