示例工程 12-ipc-anti-patterns

12-ipc-anti-patterns/insecure-ipc-patterns/main/index.ts

typescript · 3.3 KB

// ⚠️ INSECURE DEMO — 仅用于演示攻击面,禁止照抄
import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import path from "node:path";

const isSmoke =
  process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";

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] ??
    ""
  );
}

// ⚠️ 反模式 1:一个通道接受任意“子通道”。
ipcMain.handle("ipc:any", (_event, channel: unknown, payload: unknown) => {
  if (channel === "env:all") return { ...process.env };
  if (channel === "fs:read") {
    // ⚠️ 反模式 2:任意路径直接读。
    const file = (payload as { path?: string } | undefined)?.path ?? "";
    return fsSync.readFileSync(file, "utf8").length;
  }
  return { echoed: channel };
});

function createWindow(show: boolean): BrowserWindow {
  const win = new BrowserWindow({
    width: 640,
    height: 420,
    show,
    webPreferences: {
      preload: resolvePreload(),
      contextIsolation: true,
      sandbox: true,
      nodeIntegration: false,
      webSecurity: true,
      allowRunningInsecureContent: false,
      experimentalFeatures: false,
      webviewTag: false,
      spellcheck: false,
      backgroundThrottling: true,
    },
  });
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    void win.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    void win.loadFile(
      path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
    );
  }
  return win;
}

async function runSmoke(): Promise<void> {
  const win = createWindow(false);
  await win.webContents.executeJavaScript(
    `new Promise((resolve) => {
      const started = Date.now();
      const tick = () => {
        if (window.ipc) resolve(true);
        else if (Date.now() - started > 3000) resolve(false);
        else setTimeout(tick, 20);
      };
      tick();
    })`,
  );
  const result = (await win.webContents.executeJavaScript(
    `(async () => {
      const env = await window.ipc.invoke("ipc:any", "env:all");
      const fileBytes = await window.ipc.invoke("ipc:any", "fs:read", { path: "/etc/hosts" });
      const unknown = await window.ipc.invoke("ipc:any", "totally:unknown");
      return {
        rawBridge: typeof window.ipc.invoke === "function",
        envKeys: Object.keys(env).length,
        fileBytes,
        unknownAccepted: unknown?.echoed === "totally:unknown",
      };
    })()`,
  )) as {
    rawBridge: boolean;
    envKeys: number;
    fileBytes: number;
    unknownAccepted: boolean;
  };
  process.stdout.write(
    `${JSON.stringify({
      evt: "smoke",
      ok:
        result.rawBridge &&
        result.envKeys > 0 &&
        result.fileBytes > 0 &&
        result.unknownAccepted,
      ...result,
    })}\n`,
  );
  app.quit();
}

app.whenReady().then(() => {
  if (isSmoke) {
    void runSmoke().catch((error) => {
      process.stdout.write(
        `${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`,
      );
      app.exit(1);
    });
  } else {
    createWindow(true);
  }
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});