contract.test.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { mkdtempSync, rmSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, expect, it } from "vitest";
  5. import type { ExecutionShellSelection } from "@zcode/contracts";
  6. import {
  7. exampleCmdExecutedShellCheck,
  8. exampleCmdShellReadOnlyCheck,
  9. } from "../../src/tool/cmd-readonly/contract.example.js";
  10. import { setCmdReadonlyHostForTest } from "../../src/tool/handlers/bash-cmd-readonly-policy.js";
  11. const CMD: ExecutionShellSelection = {
  12. dialect: "cmd",
  13. display: { name: "CMD" },
  14. path: String.raw`C:\Windows\System32\cmd.exe`,
  15. source: "user-config",
  16. };
  17. afterEach(() => setCmdReadonlyHostForTest(undefined));
  18. it("只在 Windows 的 cmd.exe 上按 CMD 语法放行只读命令", () => {
  19. const workingDirectory = mkdtempSync(join(tmpdir(), "zcode-cmd-contract-"));
  20. try {
  21. setCmdReadonlyHostForTest({
  22. platform: "win32",
  23. env: { PATH: String.raw`C:\Windows`, SystemRoot: String.raw`C:\Windows` },
  24. // 只有系统目录和系统 cmd.exe 存在。
  25. realpath: (path) =>
  26. [String.raw`C:\Windows`, CMD.path!].find(
  27. (known) => known.toLowerCase() === path.toLowerCase(),
  28. ),
  29. });
  30. expect(exampleCmdExecutedShellCheck(CMD)).toBe(true);
  31. const context = { bashShellSelection: CMD, workingDirectory };
  32. expect(exampleCmdShellReadOnlyCheck("dir /b", context)).toBe(true);
  33. expect(exampleCmdShellReadOnlyCheck("where node", context)).toBe(true);
  34. expect(exampleCmdShellReadOnlyCheck(String.raw`type # & python x.py`, context)).toBe(false);
  35. setCmdReadonlyHostForTest({ platform: "linux", env: {} });
  36. expect(exampleCmdExecutedShellCheck(CMD)).toBe(false);
  37. expect(exampleCmdShellReadOnlyCheck("dir /b", context)).toBe(false);
  38. } finally {
  39. rmSync(workingDirectory, { force: true, recursive: true });
  40. }
  41. });