示例工程 60-tool-registry-approval

60-tool-registry-approval/app/main/index.ts

typescript · 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, type Check, type RunReq, type Snapshot } from "../shared/ipc";
import {
  SCENARIOS,
  TOOLS,
  needsApproval,
  runScenario,
  scenarioById,
  type ApprovalDecision,
  type AuditEntry,
  type Risk,
} from "../shared/tools";

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

let win: BrowserWindow | null = null;
let audit: AuditEntry[] = [];
let seq = 0;
let running = false;
const grants = new Set<string>();

const DECISIONS: ApprovalDecision[] = [
  "auto",
  "deny",
  "allow-once",
  "allow-session",
  "use-grant",
];

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

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

function approvedBy(entry: AuditEntry): AuditEntry["approvedBy"] {
  if (entry.decision === "auto") return "auto";
  if (entry.decision === "policy") return "policy";
  if (entry.decision === "allow-once" || entry.decision === "allow-session") {
    return "user";
  }
  if (entry.decision === "grant") return "auto";
  return "none";
}

function checks(): Check[] {
  const find = (
    scenarioId: string,
    decision?: AuditEntry["decision"],
  ): AuditEntry | undefined =>
    audit.find(
      (entry) =>
        entry.scenarioId === scenarioId &&
        (decision ? entry.decision === decision : true),
    );
  const read = find("read-config");
  const denied = find("write-notes", "deny");
  const once = find("write-notes", "allow-once");
  const grant = find("write-notes", "grant");
  const exec = find("run-tests", "use-grant");
  const invalid = find("bad-args");
  const timeout = find("slow-tool");
  const outside = find("outside");
  return [
    {
      id: "registry",
      label: "注册表 5 个工具",
      pass: TOOLS.length === 5,
      detail: String(TOOLS.length),
    },
    {
      id: "schema",
      label: "每个工具都有字段与超时",
      pass: TOOLS.every((tool) => tool.fields.length > 0 && tool.timeoutMs > 0),
      detail: TOOLS.map((tool) => tool.fields.length).join("/"),
    },
    {
      id: "read-auto",
      label: "只读操作自动允许",
      pass: read?.status === "ok" && read.decision === "auto",
      detail: read?.summary ?? "未运行",
    },
    {
      id: "write-deny",
      label: "拒绝写入后不执行",
      pass: denied?.status === "denied" && denied.summary === "USER_DENIED",
      detail: denied?.summary ?? "未运行",
    },
    {
      id: "write-once",
      label: "once 授权只执行一次",
      pass: once?.status === "ok" && once.decision === "allow-once",
      detail: once?.summary ?? "未运行",
    },
    {
      id: "grant-reuse",
      label: "session 授权可复用",
      pass: grant?.status === "ok" && grant.decision === "grant",
      detail: grant?.summary ?? "未运行",
    },
    {
      id: "exec-approval",
      label: "exec 即使有会话也不自动放行",
      pass:
        exec?.status === "approval-required" && exec.decision === "use-grant",
      detail: exec?.status ?? "未运行",
    },
    {
      id: "invalid",
      label: "缺参在审批前被拒",
      pass: invalid?.status === "invalid" && invalid.decision === "policy",
      detail: invalid?.summary ?? "未运行",
    },
    {
      id: "timeout",
      label: "超时单独标记",
      pass: timeout?.status === "timeout",
      detail: timeout?.summary ?? "未运行",
    },
    {
      id: "outside",
      label: "越界路径由策略拒绝",
      pass:
        outside?.status === "denied" &&
        outside.summary === "PATH_OUTSIDE_WORKSPACE",
      detail: outside?.summary ?? "未运行",
    },
  ];
}

function snapshot(): Snapshot {
  const list = checks();
  const passed = list.filter((check) => check.pass).length;
  const risks: Record<Risk, number> = {
    read: 0,
    write: 0,
    exec: 0,
    network: 0,
  };
  for (const tool of TOOLS) risks[tool.risk] += 1;
  return {
    platform: process.platform,
    electronVersion: process.versions.electron,
    nodeVersion: process.versions.node,
    tools: TOOLS.map((tool) => ({
      ...tool,
      needsApproval: needsApproval(tool),
    })),
    scenarios: SCENARIOS.map((scenario) => ({
      ...scenario,
      args: { ...scenario.args },
    })),
    grants: [...grants],
    audit: audit.map((entry) => ({ ...entry })),
    checks: list,
    score: Math.round((passed / list.length) * 100),
    risks,
  };
}

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");
  if (!DECISIONS.includes(request.decision)) {
    throw new Error("BAD_DECISION");
  }
}

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function execute(request: RunReq): Promise<AuditEntry> {
  if (running) throw new Error("RUN_IN_PROGRESS");
  running = true;
  try {
    const result = await runScenario(request, { grants, sleep });
    seq += 1;
    const entry: AuditEntry = {
      ...result,
      seq,
      at: Date.now(),
      approvedBy: "none",
    };
    entry.approvedBy = approvedBy(entry);
    audit = [...audit, entry].slice(-40);
    log(
      "result",
      `${entry.scenarioId} ${entry.status} decision=${entry.decision}`,
    );
    return entry;
  } finally {
    running = false;
    broadcast();
  }
}

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: "工具注册表与审批",
    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", "tool registry 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;
  tools: number;
  scenarios: number;
  audit: number;
  grants: number;
  readAuto: boolean;
  writeDenied: boolean;
  grantReuse: boolean;
  execApproval: boolean;
  invalid: boolean;
  timeout: boolean;
  outside: 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.tools === 5 &&
          state.scenarios === 6 &&
          state.audit >= 9 &&
          state.grants === 1 &&
          state.readAuto &&
          state.writeDenied &&
          state.grantReuse &&
          state.execApproval &&
          state.invalid &&
          state.timeout &&
          state.outside,
        ...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/60-tool-registry-approval",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    await waitForRenderer(window);
    await delay(500);
    await waitForRenderer(window);

    await evalRenderer(window, `window.__prepareShots("registry")`);
    await delay(2400);
    await capture(window, dir, "60-01-registry.png");

    await evalRenderer(window, `window.__prepareShots("approval")`);
    await delay(400);
    await capture(window, dir, "60-02-approval.png");

    await evalRenderer(window, `window.__prepareShots("audit")`);
    await delay(700);
    await capture(window, dir, "60-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, async (_event, raw: unknown) => {
  assertRunReq(raw);
  const entry = await execute(raw);
  return { entry, snapshot: snapshot() };
});

ipcMain.handle(CH.reset, () => {
  audit = [];
  seq = 0;
  grants.clear();
  log("reset", "audit + grants cleared");
  broadcast();
  return snapshot();
});

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