示例工程 45-sandbox-and-permissions

45-sandbox-and-permissions/app/.tsc/main/index.js

javascript · 14 KB

import { app, BrowserWindow, ipcMain, session } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { assertNotificationReq, assertPermissionReq, CH, } from "../shared/ipc";
app.setName("Sandbox Permissions 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(), `sandbox-${isSmoke ? "smoke" : "shots"}-${process.pid}`)
    : "";
if (tempData)
    app.setPath("userData", tempData);
const config = {
    contextIsolation: true,
    sandbox: true,
    nodeIntegration: false,
    webSecurity: true,
    allowRunningInsecureContent: false,
    experimentalFeatures: false,
    webviewTag: false,
};
let win = null;
let allowNotifications = true;
let permissionEntries = [];
let lastDownload = null;
let events = [];
let permissionHandlerInstalled = false;
let downloadHandlerInstalled = false;
let probeInfo = {
    requireType: "unknown",
    processType: "unknown",
    bufferType: "unknown",
    apiKeys: [],
    csp: "",
    probedAt: 0,
};
function log(kind, detail) {
    events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
    broadcast();
}
function broadcast() {
    if (win && !win.isDestroyed()) {
        win.webContents.send("sandbox:event", { at: Date.now() });
    }
}
function decide(permission) {
    return permission === "notifications" && allowNotifications;
}
function record(permission, allowed, source) {
    permissionEntries = [
        { permission, allowed, source, at: Date.now() },
        ...permissionEntries,
    ].slice(0, 30);
    log("permission", `${permission} · ${allowed ? "允许" : "拒绝"} · ${source}`);
}
function checks() {
    const csp = probeInfo.csp;
    return [
        {
            id: "contextIsolation",
            label: "contextIsolation = true",
            pass: config.contextIsolation,
            detail: String(config.contextIsolation),
        },
        {
            id: "sandbox",
            label: "sandbox = true",
            pass: config.sandbox,
            detail: String(config.sandbox),
        },
        {
            id: "nodeIntegration",
            label: "nodeIntegration = false",
            pass: !config.nodeIntegration,
            detail: String(config.nodeIntegration),
        },
        {
            id: "webSecurity",
            label: "webSecurity = true",
            pass: config.webSecurity,
            detail: String(config.webSecurity),
        },
        {
            id: "webview",
            label: "webviewTag = false",
            pass: !config.webviewTag,
            detail: String(config.webviewTag),
        },
        {
            id: "csp",
            label: "CSP default-src 'self' 且无 unsafe-eval",
            pass: csp.includes("default-src 'self'") &&
                csp.includes("script-src 'self'") &&
                !csp.includes("unsafe-eval"),
            detail: csp ? "present" : "missing",
        },
        {
            id: "require",
            label: "渲染进程没有 require",
            pass: probeInfo.requireType === "undefined",
            detail: probeInfo.requireType,
        },
        {
            id: "process",
            label: "渲染进程没有 process",
            pass: probeInfo.processType === "undefined",
            detail: probeInfo.processType,
        },
        {
            id: "buffer",
            label: "渲染进程没有 Buffer",
            pass: probeInfo.bufferType === "undefined",
            detail: probeInfo.bufferType,
        },
        {
            id: "permissionHandler",
            label: "权限请求处理器已安装",
            pass: permissionHandlerInstalled,
            detail: String(permissionHandlerInstalled),
        },
        {
            id: "downloadHandler",
            label: "下载拦截处理器已安装",
            pass: downloadHandlerInstalled,
            detail: String(downloadHandlerInstalled),
        },
    ];
}
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),
        probe: { ...probeInfo },
        permissions: {
            notificationsAllowed: allowNotifications,
            entries: permissionEntries.map((entry) => ({ ...entry })),
        },
        download: lastDownload,
        events: events.map((row) => ({ ...row })),
    };
}
async function probe(window) {
    try {
        const result = await window.webContents.executeJavaScript(`(() => {
      const meta = document.querySelector('meta[http-equiv="Content-Security-Policy"]');
      const api = window.api && typeof window.api === 'object' ? Object.keys(window.api) : [];
      return {
        requireType: typeof window.require,
        processType: typeof window.process,
        bufferType: typeof window.Buffer,
        apiKeys: api,
        csp: meta ? meta.getAttribute('content') || '' : ''
      };
    })()`);
        probeInfo = {
            requireType: String(result.requireType),
            processType: String(result.processType),
            bufferType: String(result.bufferType),
            apiKeys: Array.isArray(result.apiKeys)
                ? result.apiKeys
                : [],
            csp: String(result.csp ?? ""),
            probedAt: Date.now(),
        };
        log("probe", `require ${probeInfo.requireType} · process ${probeInfo.processType} · api ${probeInfo.apiKeys.join(",")}`);
    }
    catch (error) {
        log("probe-error", error instanceof Error ? error.message : String(error));
    }
    broadcast();
}
async function triggerDownload() {
    if (!win)
        return;
    await win.webContents.executeJavaScript(`(() => {
    const link = document.createElement('a');
    link.href = 'data:text/plain,blocked-by-policy';
    link.download = 'evil.txt';
    document.body.appendChild(link);
    link.click();
    link.remove();
    return true;
  })()`);
    await new Promise((resolve) => setTimeout(resolve, 500));
}
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", "沙箱界面已加载");
        void probe(window);
    });
    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(900);
        await waitForRenderer(window);
        const result = await evalRenderer(window, "window.__smoke()");
        process.stdout.write(`${JSON.stringify({
            evt: "smoke",
            ok: result.score === 100 &&
                result.checks === 11 &&
                result.passed === 11 &&
                result.requireType === "undefined" &&
                result.processType === "undefined" &&
                result.bufferType === "undefined" &&
                result.apiKeys === 1 &&
                result.csp.includes("default-src 'self'") &&
                result.notificationResult === "granted" &&
                result.allowedEntries >= 1 &&
                result.deniedEntries >= 2 &&
                result.downloadFilename === "evil.txt" &&
                result.downloadBlocked &&
                result.requireError.includes("not a function") &&
                result.events >= 5,
            ...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/45-sandbox-and-permissions");
        fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
        await waitForRenderer(window);
        await delay(900);
        await waitForRenderer(window);
        await evalRenderer(window, `window.__prepareShots("sandbox")`);
        await delay(300);
        await capture(window, dir, "45-01-sandbox.png");
        await evalRenderer(window, `window.__prepareShots("permissions")`);
        await delay(400);
        await capture(window, dir, "45-02-permissions.png");
        await evalRenderer(window, `window.__prepareShots("download")`);
        await delay(700);
        await capture(window, dir, "45-03-download.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.setNotifications, (_event, raw) => {
    assertNotificationReq(raw);
    allowNotifications = raw.enabled;
    log("policy", `通知权限 ${allowNotifications ? "允许" : "拒绝"}`);
    return snapshot();
});
ipcMain.handle(CH.simulate, (_event, raw) => {
    assertPermissionReq(raw);
    const allowed = decide(raw.permission);
    record(raw.permission, allowed, "simulated");
    return snapshot();
});
ipcMain.handle(CH.download, async () => {
    await triggerDownload();
    return snapshot();
});
ipcMain.handle(CH.probe, async () => {
    if (win)
        await probe(win);
    return snapshot();
});
ipcMain.handle(CH.refresh, async () => {
    if (win)
        await probe(win);
    log("refresh", "刷新沙箱与权限状态");
    return snapshot();
});
app.whenReady().then(() => {
    session.defaultSession.setPermissionRequestHandler((_webContents, permission, callback) => {
        const allowed = decide(permission);
        record(permission, allowed, "request");
        callback(allowed);
    });
    session.defaultSession.setPermissionCheckHandler((_webContents, permission) => decide(permission));
    permissionHandlerInstalled = true;
    session.defaultSession.on("will-download", (event, item) => {
        event.preventDefault();
        lastDownload = {
            filename: item.getFilename(),
            url: item.getURL(),
            bytes: item.getTotalBytes(),
            blocked: true,
            at: Date.now(),
        };
        log("download", `拦截 ${lastDownload.filename}`);
    });
    downloadHandlerInstalled = true;
    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