示例工程 53-code-signing-notarization

53-code-signing-notarization/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 EventRow, type Snapshot } from "../shared/ipc";
import {
  buildPlans,
  type EnvCheck,
  type Plan,
  type Readiness,
} from "../shared/plans";

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

let win: BrowserWindow | null = null;
let events: EventRow[] = [];
const plans = buildPlans();
const noExecution = true;
const NOTARY_NAME = "notarytool";

const TOOL_PATHS: Record<string, string[]> = {
  codesign: ["/usr/bin/codesign"],
  notarytool: ["/usr/bin/xcrun", "/usr/bin/notarytool"],
  stapler: ["/usr/bin/stapler"],
  spctl: ["/usr/sbin/spctl"],
  signtool: ["C:\\Program Files (x86)\\Windows Kits\\10\\bin"],
  gpg: ["/usr/local/bin/gpg", "/opt/homebrew/bin/gpg", "/usr/bin/gpg"],
};

function log(kind: string, detail: string): void {
  events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
  broadcast();
}

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

function toolPresent(name: string): boolean {
  const candidates = TOOL_PATHS[name] ?? [];
  return candidates.some((candidate) => {
    try {
      return fsSync.existsSync(candidate);
    } catch {
      return false;
    }
  });
}

function readiness(): Readiness {
  const tools = [...new Set(plans.flatMap((plan) => plan.tools))].map(
    (name) => ({ name, present: toolPresent(name) }),
  );
  const env: EnvCheck[] = [
    ...new Set(plans.flatMap((plan) => plan.secrets)),
  ].map((key) => ({ key, present: Boolean(process.env[key]) }));
  const presentTools = tools.filter((tool) => tool.present).length;
  const presentEnv = env.filter((row) => row.present).length;
  const score = Math.round(
    ((presentTools + presentEnv) / (tools.length + env.length)) * 100,
  );
  return {
    platform: process.platform,
    isPackaged: app.isPackaged,
    tools,
    env,
    score,
  };
}

function checks(): Check[] {
  const mac = plans.find((plan) => plan.id === "macos");
  const winPlan = plans.find((plan) => plan.id === "windows");
  const linux = plans.find((plan) => plan.id === "linux");
  const macCommands = mac?.steps.map((step) => step.command).join("\n") ?? "";
  const winCommands =
    winPlan?.steps.map((step) => step.command).join("\n") ?? "";
  const linuxCommands =
    linux?.steps.map((step) => step.command).join("\n") ?? "";
  const allSteps = plans.flatMap((plan) => plan.steps);
  const envKeys = new Set(plans.flatMap((plan) => plan.secrets));
  return [
    {
      id: "no-exec",
      label: "只展示,不执行任何签名工具",
      pass: noExecution && allSteps.every((step) => step.executes === false),
      detail: `${allSteps.length} steps`,
    },
    {
      id: "mac-runtime",
      label: "macOS 计划包含 hardened runtime + timestamp",
      pass:
        macCommands.includes("--options runtime") &&
        macCommands.includes("--timestamp"),
      detail: "runtime/timestamp",
    },
    {
      id: "mac-notary",
      label: "包含公证提交与 --wait",
      pass:
        macCommands.includes(`${NOTARY_NAME} submit`) &&
        macCommands.includes("--wait"),
      detail: "submit --wait",
    },
    {
      id: "mac-staple",
      label: "包含装订与 Gatekeeper 评估",
      pass:
        macCommands.includes("staple") &&
        macCommands.includes("spctl --assess"),
      detail: "staple/spctl",
    },
    {
      id: "win-timestamp",
      label: "Windows 计划包含 /tr 与 /td",
      pass: winCommands.includes("/tr ") && winCommands.includes("/td "),
      detail: "rfc3161",
    },
    {
      id: "win-verify",
      label: "Windows 计划包含 verify /pa",
      pass: winCommands.includes("verify /pa"),
      detail: "verify",
    },
    {
      id: "linux",
      label: "Linux 明确无系统级签名",
      pass:
        linuxCommands.includes("detach-sign") &&
        linuxCommands.includes("--verify"),
      detail: "gpg",
    },
    {
      id: "env",
      label: "只检查 7 个环境变量的存在性",
      pass: envKeys.size === 7,
      detail: `${envKeys.size} keys`,
    },
    {
      id: "tools",
      label: "工具存在性检查已执行",
      pass: readiness().tools.length >= 5,
      detail: `${readiness().tools.length} tools`,
    },
    {
      id: "secrets",
      label: "计划中不包含任何真实凭据",
      pass: plans.every(
        (plan) =>
          plan.secrets.every((key) => /^[A-Z0-9_]+$/.test(key)) &&
          !JSON.stringify(plan).includes("BEGIN PRIVATE KEY"),
      ),
      detail: "names only",
    },
  ];
}

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,
    plans: plans.map((plan: Plan) => ({
      ...plan,
      steps: plan.steps.map((step) => ({ ...step })),
      secrets: [...plan.secrets],
      tools: [...plan.tools],
      limits: [...plan.limits],
    })),
    readiness: readiness(),
    checks: list,
    score: Math.round((passed / list.length) * 100),
    events: events.map((row) => ({ ...row })),
  };
}

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: 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: 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;
  plans: number;
  macSteps: number;
  winSteps: number;
  linuxSteps: number;
  noExec: boolean;
  envKeys: number;
  tools: number;
  secretsOnly: boolean;
  notary: boolean;
  staple: boolean;
};

async function runSmoke(window: BrowserWindow): Promise<void> {
  try {
    await waitForRenderer(window);
    await delay(600);
    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.plans === 3 &&
          state.macSteps === 6 &&
          state.winSteps === 3 &&
          state.linuxSteps === 3 &&
          state.noExec &&
          state.envKeys === 7 &&
          state.tools >= 5 &&
          state.secretsOnly &&
          state.notary &&
          state.staple,
        ...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/53-code-signing-notarization",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    await waitForRenderer(window);
    await delay(600);
    await waitForRenderer(window);
    await evalRenderer(window, `window.__prepareShots("macos")`);
    await delay(250);
    await capture(window, dir, "53-01-macos.png");
    await evalRenderer(window, `window.__prepareShots("notarize")`);
    await delay(250);
    await capture(window, dir, "53-02-notarize.png");
    await evalRenderer(window, `window.__prepareShots("matrix")`);
    await delay(250);
    await capture(window, dir, "53-03-matrix.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.refresh, () => {
  log("refresh", "重新评估工具与环境变量存在性");
  return snapshot();
});

app.whenReady().then(() => {
  log("plan", `${plans.length} 个平台计划,仅展示不执行`);
  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();
});