示例工程 62-workspace-shell-sandbox

62-workspace-shell-sandbox/app/main/index.ts

typescript · 11 KB

import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { CH, type Check, type RunReq, type Snapshot } from "../shared/ipc";
import {
  ALLOWLIST,
  OUTPUT_CAP,
  ROOT,
  SCENARIOS,
  SHELL_TIMEOUT_MS,
  SYMLINKS,
  resolveInWorkspace,
  runShell,
  scenarioById,
  type SandboxResult,
} from "../shared/sandbox";

app.setName("Workspace Sandbox 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(), `sandbox62-${process.pid}`) : "";
if (tempData) app.setPath("userData", tempData);

let win: BrowserWindow | null = null;
let audit: SandboxResult[] = [];
let seq = 0;

function log(kind: string, detail: string): void {
  process.stdout.write(
    `${JSON.stringify({ evt: "sandbox", kind, detail, at: Date.now() })}\n`,
  );
}

function broadcast(): void {
  if (win && !win.isDestroyed()) {
    win.webContents.send("sandbox:changed", { at: Date.now() });
  }
}

function find(id: string): SandboxResult | undefined {
  return audit.find((entry) => entry.scenarioId === id);
}

function checks(): Check[] {
  const inside = find("path-inside");
  const outside = find("path-outside");
  const absolute = find("path-absolute");
  const symlink = find("path-symlink");
  const tests = find("shell-tests");
  const status = find("shell-status");
  const blocked = find("shell-blocked");
  const metachar = find("shell-metachar");
  const timeout = find("shell-timeout");
  const truncated = find("shell-truncate");
  return [
    {
      id: "inside",
      label: "工作区内相对路径允许",
      pass: inside?.status === "ok" && inside.code === "OK",
      detail: inside?.code ?? "未运行",
    },
    {
      id: "outside",
      label: "../ 越界被拒绝",
      pass: outside?.code === "OUTSIDE",
      detail: outside?.code ?? "未运行",
    },
    {
      id: "absolute",
      label: "绝对路径被拒绝",
      pass: absolute?.code === "ABSOLUTE",
      detail: absolute?.code ?? "未运行",
    },
    {
      id: "symlink",
      label: "符号链接逃逸被识别",
      pass: symlink?.code === "SYMLINK_ESCAPE",
      detail: symlink?.code ?? "未运行",
    },
    {
      id: "tests",
      label: "白名单命令可执行",
      pass: tests?.status === "ok" && tests.code === "OK",
      detail: tests?.code ?? "未运行",
    },
    {
      id: "status",
      label: "git status 可执行",
      pass: status?.status === "ok",
      detail: status?.code ?? "未运行",
    },
    {
      id: "blocked",
      label: "rm -rf / 被拒绝",
      pass: blocked?.code === "COMMAND_NOT_ALLOWED",
      detail: blocked?.code ?? "未运行",
    },
    {
      id: "metachar",
      label: "分号拼接被拒绝",
      pass: metachar?.code === "SHELL_METACHAR",
      detail: metachar?.code ?? "未运行",
    },
    {
      id: "timeout",
      label: "超时单独标记",
      pass: timeout?.status === "timeout",
      detail: timeout?.code ?? "未运行",
    },
    {
      id: "truncated",
      label: "输出超限被截断",
      pass: truncated?.status === "truncated",
      detail: truncated?.code ?? "未运行",
    },
  ];
}

function snapshot(): Snapshot {
  const list = checks();
  const passed = list.filter((check) => check.pass).length;
  return {
    platform: process.platform,
    electronVersion: process.versions.electron,
    nodeVersion: process.versions.node,
    root: ROOT,
    symlinks: { ...SYMLINKS },
    allowlist: [...ALLOWLIST],
    timeoutMs: SHELL_TIMEOUT_MS,
    outputCap: OUTPUT_CAP,
    scenarios: SCENARIOS.map((scenario) => ({ ...scenario })),
    audit: audit.map((entry) => ({ ...entry })),
    checks: list,
    score: Math.round((passed / list.length) * 100),
  };
}

function assertRunReq(value: unknown): asserts value is RunReq {
  if (typeof value !== "object" || value === null) throw new Error("BAD_REQ");
  const request = value as RunReq;
  if (typeof request.scenarioId !== "string") {
    throw new Error("BAD_SCENARIO");
  }
  if (!scenarioById(request.scenarioId)) throw new Error("UNKNOWN_SCENARIO");
}

function run(scenarioId: string): SandboxResult {
  const scenario = scenarioById(scenarioId);
  if (!scenario) throw new Error("UNKNOWN_SCENARIO");
  const started = Date.now();
  seq += 1;
  const base = {
    seq,
    at: started,
    scenarioId: scenario.id,
    kind: scenario.kind,
    label: scenario.label,
    input: scenario.input,
  };

  let result: SandboxResult;
  if (scenario.kind === "path") {
    const resolved = resolveInWorkspace(scenario.input);
    result = {
      ...base,
      status: resolved.ok ? "ok" : "blocked",
      code: resolved.code,
      detail: resolved.ok
        ? resolved.resolved
        : `${resolved.detail} · ${resolved.resolved}`,
      durationMs: Date.now() - started,
    };
  } else {
    const shell = runShell(scenario.input);
    result = {
      ...base,
      status: shell.status,
      code: shell.code,
      detail: shell.output
        ? shell.output.slice(0, 120).replace(/\n/g, " ⏎ ")
        : shell.code,
      durationMs: shell.durationMs,
    };
  }

  audit = [...audit, result].slice(-40);
  log("result", `${scenario.id} ${result.status} ${result.code}`);
  broadcast();
  return result;
}

function resolvePreload(): string {
  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(): BrowserWindow {
  const window = new BrowserWindow({
    width: 1100,
    height: 900,
    show: false,
    title: "工作区与 Shell 沙箱",
    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", "sandbox ui loaded");
  });
  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: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function evalRenderer<T>(
  window: BrowserWindow,
  code: string,
): Promise<T> {
  let lastCaught: unknown = null;
  for (let attempt = 0; attempt < 3; attempt += 1) {
    try {
      return (await window.webContents.executeJavaScript(code)) as T;
    } catch (caught) {
      lastCaught = caught;
      await delay(150);
    }
  }
  throw lastCaught instanceof Error
    ? lastCaught
    : new Error(String(lastCaught));
}

async function waitForRenderer(window: BrowserWindow): Promise<void> {
  for (let attempt = 0; attempt < 160; attempt += 1) {
    if (window.isDestroyed()) return;
    try {
      const ready = await evalRenderer<boolean>(
        window,
        "typeof window.__demo === 'function'",
      );
      if (ready) return;
    } catch {
      // 页面仍在加载。
    }
    await delay(100);
  }
  throw new Error("renderer did not become ready");
}

type DemoState = {
  score: number;
  checks: number;
  passed: number;
  scenarios: number;
  audit: number;
  inside: boolean;
  outside: boolean;
  absolute: boolean;
  symlink: boolean;
  blocked: boolean;
  metachar: boolean;
  timeout: boolean;
  truncated: boolean;
};

async function runSmoke(window: BrowserWindow): Promise<void> {
  try {
    await waitForRenderer(window);
    await delay(500);
    await waitForRenderer(window);
    const state = await evalRenderer<DemoState>(window, "window.__demo()");
    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          state.score === 100 &&
          state.checks === 10 &&
          state.passed === 10 &&
          state.scenarios === 10 &&
          state.audit >= 10 &&
          state.inside &&
          state.outside &&
          state.absolute &&
          state.symlink &&
          state.blocked &&
          state.metachar &&
          state.timeout &&
          state.truncated,
        ...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: BrowserWindow,
  dir: string,
  file: string,
): Promise<void> {
  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: BrowserWindow): Promise<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/62-workspace-shell-sandbox",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    await waitForRenderer(window);
    await delay(500);
    await waitForRenderer(window);

    await evalRenderer(window, `window.__prepareShots("workspace")`);
    await delay(800);
    await capture(window, dir, "62-01-workspace.png");

    await evalRenderer(window, `window.__prepareShots("shell")`);
    await delay(500);
    await capture(window, dir, "62-02-shell.png");

    await evalRenderer(window, `window.__prepareShots("audit")`);
    await delay(500);
    await capture(window, dir, "62-03-audit.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.run, (_event, raw: unknown) => {
  assertRunReq(raw);
  const entry = run(raw.scenarioId);
  return { entry, snapshot: snapshot() };
});

ipcMain.handle(CH.reset, () => {
  audit = [];
  seq = 0;
  broadcast();
  return snapshot();
});

app.whenReady().then(() => {
  log("load", `${SCENARIOS.length} scenarios`);
  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();
});