示例工程 48-project-security-auditor

48-project-security-auditor/app/.tsc/main/index.js

javascript · 13 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, scanText, scoreFindings, summarize, } from "../shared/rules";
app.setName("Security Auditor");
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(), `audit-${process.pid}`) : "";
if (tempData)
    app.setPath("userData", tempData);
const appRoot = app.getAppPath();
const fixtureRoot = path.join(appRoot, "fixtures");
let win = null;
let events = [];
let projects = [];
let expected = { match: false, checked: 0, mismatches: [] };
let ruleSummaries = summarize([]);
function log(kind, detail) {
    events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
    broadcast();
}
function broadcast() {
    if (win && !win.isDestroyed()) {
        win.webContents.send("audit:event", { at: Date.now() });
    }
}
function listFiles(dir) {
    try {
        return fsSync
            .readdirSync(dir, { withFileTypes: true })
            .filter((entry) => entry.isFile() && entry.name.endsWith(".txt"))
            .map((entry) => entry.name)
            .sort();
    }
    catch {
        return [];
    }
}
function loadProject(folder) {
    const dir = path.join(fixtureRoot, folder);
    const findings = [];
    const files = listFiles(dir).map((file) => {
        const text = fsSync.readFileSync(path.join(dir, file), "utf8");
        const rows = scanText(file, text);
        findings.push(...rows);
        return { file, findings: rows };
    });
    return {
        folder,
        files,
        findingCount: findings.length,
        high: findings.filter((row) => row.severity === "high").length,
        medium: findings.filter((row) => row.severity === "medium").length,
        score: scoreFindings(findings),
    };
}
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 compareExpected(report, expectedMap) {
    const want = expectedMap[report.folder] ?? {};
    const actual = {};
    for (const file of report.files) {
        const ids = [...new Set(file.findings.map((row) => row.ruleId))].sort();
        if (ids.length > 0)
            actual[file.file] = ids;
    }
    const names = [
        ...new Set([...Object.keys(want), ...Object.keys(actual)]),
    ].sort();
    const mismatches = [];
    for (const name of names) {
        const wantIds = [...(want[name] ?? [])].sort();
        const actualIds = actual[name] ?? [];
        if (wantIds.join(",") !== actualIds.join(",")) {
            mismatches.push(`${name}: want [${wantIds}] got [${actualIds}]`);
        }
    }
    return { match: mismatches.length === 0, checked: names.length, mismatches };
}
function checks() {
    const bad = projects.find((row) => row.folder === "bad");
    const clean = projects.find((row) => row.folder === "clean");
    const allFindings = projects.flatMap((row) => row.files.flatMap((file) => file.findings));
    const high = allFindings.filter((row) => row.severity === "high").length;
    const medium = allFindings.filter((row) => row.severity === "medium").length;
    const commentFlagged = allFindings.some((row) => row.evidence.includes("注释里的"));
    return [
        {
            id: "rules",
            label: "规则集加载完整(11 条)",
            pass: RULES.length === 11,
            detail: `${RULES.length} rules`,
        },
        {
            id: "bad-count",
            label: "不安全样本命中 11 条",
            pass: bad?.findingCount === 11,
            detail: String(bad?.findingCount ?? 0),
        },
        {
            id: "clean-count",
            label: "安全样本 0 命中",
            pass: clean?.findingCount === 0,
            detail: String(clean?.findingCount ?? 0),
        },
        {
            id: "expected",
            label: "检测结果与 expected.json 一致",
            pass: expected.match,
            detail: `${expected.checked} 文件 / ${expected.mismatches.length} 差异`,
        },
        {
            id: "high",
            label: "高危 9 条",
            pass: high === 9,
            detail: String(high),
        },
        {
            id: "medium",
            label: "中危 2 条",
            pass: medium === 2,
            detail: String(medium),
        },
        {
            id: "comments",
            label: "注释行不被误报",
            pass: !commentFlagged,
            detail: commentFlagged ? "false-positive" : "skipped",
        },
        {
            id: "hints",
            label: "每条发现都有修复提示",
            pass: allFindings.length > 0 &&
                allFindings.every((row) => row.hint.trim().length > 0),
            detail: `${allFindings.length} findings`,
        },
        {
            id: "clean-score",
            label: "安全样本得分 100",
            pass: clean?.score === 100,
            detail: String(clean?.score ?? 0),
        },
        {
            id: "bad-score",
            label: "不安全样本得分 20",
            pass: bad?.score === 20,
            detail: String(bad?.score ?? 0),
        },
    ];
}
function scanAll() {
    projects = [loadProject("bad"), loadProject("clean")];
    expected = compareExpected(projects[0], readExpected());
    const allFindings = projects.flatMap((row) => row.files.flatMap((file) => file.findings));
    ruleSummaries = summarize(allFindings);
    log("scan", `${projects[0]?.findingCount ?? 0} 命中 / ${projects[1]?.findingCount ?? 0} clean · expected ${expected.match ? "match" : "mismatch"}`);
}
function snapshot() {
    const list = checks();
    const passed = list.filter((check) => check.pass).length;
    const bad = projects.find((row) => row.folder === "bad");
    const clean = projects.find((row) => row.folder === "clean");
    const allFindings = projects.flatMap((row) => row.files.flatMap((file) => file.findings));
    return {
        platform: process.platform,
        electronVersion: process.versions.electron,
        nodeVersion: process.versions.node,
        projects: projects.map((row) => ({
            ...row,
            files: row.files.map((file) => ({
                ...file,
                findings: file.findings.map((finding) => ({ ...finding })),
            })),
        })),
        ruleSummaries: ruleSummaries.map((row) => ({ ...row })),
        totals: {
            findings: allFindings.length,
            high: allFindings.filter((row) => row.severity === "high").length,
            medium: allFindings.filter((row) => row.severity === "medium").length,
            badScore: bad?.score ?? 0,
            cleanScore: clean?.score ?? 0,
        },
        expected: {
            ...expected,
            mismatches: [...expected.mismatches],
        },
        checks: list,
        score: Math.round((passed / list.length) * 100),
        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: "安全审计员",
        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", "审计界面已加载");
    });
    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(700);
        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.badFindings === 11 &&
                state.cleanFindings === 0 &&
                state.high === 9 &&
                state.medium === 2 &&
                state.expectedMatch &&
                state.mismatches === 0 &&
                !state.commentFlagged &&
                state.badScore === 20 &&
                state.cleanScore === 100 &&
                state.ruleHits === 11 &&
                state.projects === 2,
            ...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/48-project-security-auditor");
        fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
        await waitForRenderer(window);
        await delay(700);
        await waitForRenderer(window);
        await evalRenderer(window, `window.__prepareShots("findings")`);
        await delay(300);
        await capture(window, dir, "48-01-findings.png");
        await evalRenderer(window, `window.__prepareShots("rules")`);
        await delay(300);
        await capture(window, dir, "48-02-rules.png");
        await evalRenderer(window, `window.__prepareShots("clean")`);
        await delay(300);
        await capture(window, dir, "48-03-clean.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, () => {
    scanAll();
    return snapshot();
});
ipcMain.handle(CH.refresh, () => {
    scanAll();
    log("refresh", "重新扫描 fixtures");
    return snapshot();
});
app.whenReady().then(() => {
    scanAll();
    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