workspace-hook-script-entry.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. import { mkdtempSync } from "node:fs";
  2. import { mkdir, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import { createConfig, createConfigWithPluginMigrations } from "../src/config/index.js";
  7. import {
  8. buildWorkspaceHookBundleSnapshot,
  9. identifyWorkspaceHookScriptPath,
  10. readWorkspaceHookProjectSources,
  11. readWorkspaceHookScriptState,
  12. readWorkspaceHookScriptStates,
  13. resolveWorkspaceHookRuntimeRoot,
  14. type WorkspaceHookDefinition,
  15. } from "@zcode/shared/workspace-hook-discovery";
  16. /**
  17. * D24(ZP-20261110-06):Trust 绑定直接入口脚本内容。
  18. * 修复前 declaration digest 不含脚本内容,声明不变、只换脚本时旧 Trust 继续放行。
  19. */
  20. const roots: string[] = [];
  21. function makeRoot(): string {
  22. const root = mkdtempSync(join(tmpdir(), "zcode-hook-script-entry-"));
  23. roots.push(root);
  24. return root;
  25. }
  26. afterEach(async () => {
  27. await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  28. });
  29. async function writeHooks(workspace: string, hooks: WorkspaceHookDefinition[]): Promise<void> {
  30. await mkdir(join(workspace, ".git"), { recursive: true });
  31. await mkdir(join(workspace, ".zcode"), { recursive: true });
  32. await writeFile(
  33. join(workspace, ".zcode", "config.json"),
  34. JSON.stringify({ hooks: { enabled: true, events: { SessionStart: [{ hooks }] } } }),
  35. "utf8",
  36. );
  37. }
  38. async function snapshotOf(workspace: string) {
  39. const { sources } = await readWorkspaceHookProjectSources({ workingDirectory: workspace });
  40. const scriptStates = await readWorkspaceHookScriptStates({ workspacePath: workspace, sources });
  41. return buildWorkspaceHookBundleSnapshot({
  42. workspaceIdentity: workspace,
  43. workspacePath: workspace,
  44. sources,
  45. runtimeRoot: resolveWorkspaceHookRuntimeRoot([...sources.map((source) => source.hooks)]),
  46. scriptStates,
  47. })!;
  48. }
  49. describe("identifyWorkspaceHookScriptPath", () => {
  50. // 识别结果与平台有关(Windows 上 command 不识别):这里固定按 POSIX 断言,Windows 用例单独传 "win32",
  51. // 保证同一份断言在 Windows CI 上也成立。
  52. const command = (value: string, shell?: true | string) =>
  53. identifyWorkspaceHookScriptPath(
  54. {
  55. type: "command",
  56. command: value,
  57. ...(shell === undefined ? {} : { shell }),
  58. },
  59. "linux",
  60. );
  61. const processHook = (value: string, args?: string[]) =>
  62. identifyWorkspaceHookScriptPath(
  63. { type: "process", command: value, ...(args ? { args } : {}) },
  64. "linux",
  65. );
  66. it.each([
  67. ["./scripts/x.sh", "scripts/x.sh"],
  68. ["scripts/x.sh --log=out.log", "scripts/x.sh"],
  69. ["bash .zcode/hook.sh", ".zcode/hook.sh"],
  70. ["bash hook.sh", "hook.sh"],
  71. ["node .zcode/audit.mjs --log=.zcode/audit.log", ".zcode/audit.mjs"],
  72. ["python3 tools/check.py arg", "tools/check.py"],
  73. ['"$CLAUDE_PROJECT_DIR"/hooks/x.sh', "hooks/x.sh"],
  74. ['bash "$ZCODE_PROJECT_DIR"/x.sh', "x.sh"],
  75. ])("command %s → %s", (value, expected) => {
  76. expect(command(value)).toBe(expected);
  77. expect(command(value, true)).toBe(expected);
  78. });
  79. it.each([
  80. "echo hello",
  81. "x.sh",
  82. "true",
  83. "cd scripts && ./x.sh",
  84. "./x.sh | tee out.log",
  85. "./x.sh > out.log",
  86. "bash -c ./x.sh",
  87. "node --experimental-strip-types x.ts",
  88. "python -m tool",
  89. "npx some-tool",
  90. "npm run hook",
  91. "'./x.sh'",
  92. "./x.sh $(date)",
  93. "/abs/x.sh",
  94. "../x.sh",
  95. "bash ../x.sh",
  96. "./a/../x.sh",
  97. "${ZCODE_PROJECT_DIR}/../x.sh",
  98. "/bin/bash x.sh",
  99. "bash",
  100. "~/x.sh",
  101. ".\\x.ps1",
  102. ])("command %s 不识别", (value) => {
  103. expect(command(value)).toBeUndefined();
  104. });
  105. // CR SG-01:换行是 shell 的命令分隔符。曾在空白切分时被吞掉,多行命令被误识别为只绑定首行脚本。
  106. it.each(["bash good.sh\nnode other.js", "bash good.sh\r\nnode other.js", "./good.sh\n"])(
  107. "多行命令 %j 不识别",
  108. (value) => {
  109. expect(command(value)).toBeUndefined();
  110. },
  111. );
  112. // 第二轮 CR-01:按 \s 切分会吞掉非 ASCII 空白,shell 不按它们分词,绑定与执行的文件会不同;
  113. // % 会被 cmd.exe 展开。第二轮 SG-01:含 : 的路径在 Windows 上是盘符相对路径或备用数据流。
  114. it.each([
  115. "bash .zcode/check.sh\u00a0run",
  116. "./.zcode/check.sh\u00a0",
  117. "bash\u3000good.sh",
  118. "bash good.sh\varg",
  119. "bash good.sh\farg",
  120. "node .zcode/%OS%.js",
  121. "node C:hook.js",
  122. "node sub/x:y.js",
  123. ])("%j 不识别", (value) => {
  124. expect(command(value)).toBeUndefined();
  125. });
  126. // 第三轮 CR-01:首个 token 可能是 shell 的赋值前缀;cmd.exe 把未加引号的 , = 当分隔符并去掉开头的 @。
  127. // 这些写法曾把赋值或整串当作脚本路径,绑定的文件不是实际执行的文件,或合法 Hook 被误判 missing。
  128. it.each([
  129. "ENV=decoy/ok bash .zcode/h.sh",
  130. "PYTHONPATH=tools/lib python3 tools/check.py",
  131. "node,.zcode/h.js",
  132. "python=.zcode/h.py",
  133. "@scripts/hook.cmd",
  134. "bash @scripts/h.sh",
  135. "bash a,b/h.sh",
  136. ])("赋值前缀与 cmd.exe 分隔写法 %j 不识别", (value) => {
  137. expect(command(value)).toBeUndefined();
  138. });
  139. it("参数中的 --flag=value 不影响识别", () => {
  140. expect(command("scripts/x.sh --log=out/a.log")).toBe("scripts/x.sh");
  141. });
  142. // 第四轮 CR-01:Windows 上 command 经 cmd.exe 执行,它把 / 当开关、先在 cwd 找 node.cmd 等同名程序。
  143. // 不再用字符规则近似 cmd.exe:Windows 上 command 类型一律不识别入口,回到声明级信任(spec §12.9)。
  144. it.each(["scripts/x.sh", "./x.sh", "node .zcode/h.js", "bash .zcode/hook.sh"])(
  145. "Windows 上 command %j 不识别",
  146. (value) => {
  147. expect(
  148. identifyWorkspaceHookScriptPath({ type: "command", command: value }, "win32"),
  149. ).toBeUndefined();
  150. },
  151. );
  152. it("Windows 上 process 解释器写法与带扩展名的直接执行仍识别;无扩展名的直接执行不识别", () => {
  153. const win = (command: string, args?: string[]) =>
  154. identifyWorkspaceHookScriptPath(
  155. { type: "process", command, ...(args ? { args } : {}) },
  156. "win32",
  157. );
  158. expect(win("node", [".zcode/h.js"])).toBe(".zcode/h.js");
  159. expect(win("./tools/check.exe")).toBe("tools/check.exe");
  160. // 无扩展名时 Windows 会按 PATHEXT 补 .cmd/.exe,执行的不是绑定的文件。
  161. expect(win("./tools/check")).toBeUndefined();
  162. });
  163. it.each(["bash +x/h.sh", "./a+b.sh", "bash a@b/h.sh"])(
  164. "脚本 token 超出 [A-Za-z0-9_./-] 的 %j 不识别",
  165. (value) => {
  166. expect(command(value)).toBeUndefined();
  167. },
  168. );
  169. // 第五轮 SG-01:command 里未加引号的目录变量会被 shell 按 cwd 中的空格拆开;${VAR} 先被文本替换,
  170. // cwd 中的 " $ 反引号仍会被 shell 解释。只保留由 shell 在引号内展开的 "$VAR"/ 写法。
  171. // 第五轮需确认项:解释器后的无路径名字可能是子命令(node inspect x.js 加载的是 x.js),须带扩展名。
  172. it.each([
  173. "${ZCODE_PROJECT_DIR}/x.sh",
  174. "$ZCODE_PROJECT_DIR/x.sh",
  175. 'bash "${ZCODE_PROJECT_DIR}"/x.sh',
  176. "bash $CLAUDE_PROJECT_DIR/x.sh",
  177. "bash hook",
  178. "node inspect payload.js",
  179. ])("command %j 不识别", (value) => {
  180. expect(command(value)).toBeUndefined();
  181. });
  182. it("process 解释器后的无路径名字须带扩展名", () => {
  183. expect(processHook("node", ["inspect", "payload.js"])).toBeUndefined();
  184. expect(processHook("bash", ["hook"])).toBeUndefined();
  185. expect(processHook("node", ["hook.mjs"])).toBe("hook.mjs");
  186. });
  187. it("tab 分隔的命令仍可识别", () => {
  188. expect(command("bash\tgood.sh\targ")).toBe("good.sh");
  189. });
  190. it.each([
  191. ["node", ["C:hook.js"]],
  192. ["C:hook.js", []],
  193. ] as const)("process %s %j 含冒号不识别", (file, args) => {
  194. expect(processHook(file, [...args])).toBeUndefined();
  195. });
  196. it("自定义 shell 字符串不识别", () => {
  197. expect(command("./x.sh", "/bin/zsh")).toBeUndefined();
  198. });
  199. it.each([
  200. [["node", [".zcode/audit.mjs", "--log=.zcode/audit.log"]], ".zcode/audit.mjs"],
  201. [["./scripts/x.sh", ["a b"]], "scripts/x.sh"],
  202. [["${ZCODE_PROJECT_DIR}/x.sh", []], "x.sh"],
  203. [["bash", ["${CLAUDE_PROJECT_DIR}/x.sh"]], "x.sh"],
  204. ] as const)("process %j → %s", ([file, args], expected) => {
  205. expect(processHook(file, [...args])).toBe(expected);
  206. });
  207. it.each([
  208. ["node", ["--inspect", "x.js"]],
  209. ["node", []],
  210. ["git", ["status"]],
  211. ["x.sh", []],
  212. ["/usr/bin/x", []],
  213. ["node", ["../x.js"]],
  214. ["node", ["${CLAUDE_PLUGIN_ROOT}/x.js"]],
  215. ] as const)("process %s %j 不识别", (file, args) => {
  216. expect(processHook(file, [...args])).toBeUndefined();
  217. });
  218. });
  219. describe("readWorkspaceHookScriptState", () => {
  220. it("普通文件记录 sha256,不存在记为 missing,目录记为 unverifiable", async () => {
  221. const workspace = makeRoot();
  222. await writeFile(join(workspace, "x.sh"), "echo one\n", "utf8");
  223. await mkdir(join(workspace, "dir"));
  224. const file = await readWorkspaceHookScriptState(workspace, "x.sh");
  225. expect(file).toEqual({ kind: "file", sha256: expect.stringMatching(/^[a-f0-9]{64}$/u) });
  226. expect(await readWorkspaceHookScriptState(workspace, "nope.sh")).toEqual({ kind: "missing" });
  227. expect(await readWorkspaceHookScriptState(workspace, "x.sh/child")).toEqual({
  228. kind: "missing",
  229. });
  230. expect(await readWorkspaceHookScriptState(workspace, "dir")).toEqual({ kind: "unverifiable" });
  231. const aborted = new AbortController();
  232. aborted.abort();
  233. expect(await readWorkspaceHookScriptState(workspace, "x.sh", aborted.signal)).toEqual({
  234. kind: "unverifiable",
  235. });
  236. });
  237. });
  238. describe("workspace hook snapshot 绑定入口脚本(D24)", () => {
  239. it("只改脚本内容时 declaration digest 变化;只改数据文件时不变", async () => {
  240. const workspace = makeRoot();
  241. await writeHooks(workspace, [
  242. // process 写法在所有平台都绑定入口,Windows CI 上同样成立。
  243. { type: "process", command: "bash", args: [".zcode/hook.sh", "--log=.zcode/hook.log"] },
  244. ]);
  245. await writeFile(join(workspace, ".zcode", "hook.sh"), "echo one\n", "utf8");
  246. await writeFile(join(workspace, ".zcode", "hook.log"), "a\n", "utf8");
  247. const before = await snapshotOf(workspace);
  248. expect(before.hooks[0]?.scriptEntry).toEqual({
  249. path: ".zcode/hook.sh",
  250. state: { kind: "file", sha256: expect.any(String) },
  251. });
  252. await writeFile(join(workspace, ".zcode", "hook.log"), "a\nb\n", "utf8");
  253. const dataChanged = await snapshotOf(workspace);
  254. expect(dataChanged.hooks[0]?.hookDeclarationDigest).toBe(before.hooks[0]?.hookDeclarationDigest);
  255. await writeFile(join(workspace, ".zcode", "hook.sh"), "echo two\n", "utf8");
  256. const scriptChanged = await snapshotOf(workspace);
  257. expect(scriptChanged.hooks[0]?.hookDeclarationDigest).not.toBe(
  258. before.hooks[0]?.hookDeclarationDigest,
  259. );
  260. });
  261. it("无法识别入口的声明没有 scriptEntry,digest 与不读脚本时相同", async () => {
  262. const workspace = makeRoot();
  263. await writeHooks(workspace, [{ type: "command", command: "cd .zcode && ./hook.sh" }]);
  264. const { sources } = await readWorkspaceHookProjectSources({ workingDirectory: workspace });
  265. const runtimeRoot = resolveWorkspaceHookRuntimeRoot([...sources.map((s) => s.hooks)]);
  266. const withStates = await snapshotOf(workspace);
  267. const withoutStates = buildWorkspaceHookBundleSnapshot({
  268. workspaceIdentity: workspace,
  269. workspacePath: workspace,
  270. sources,
  271. runtimeRoot,
  272. })!;
  273. expect(withStates.hooks[0]?.scriptEntry).toBeUndefined();
  274. expect(withStates.hooks[0]?.hookDeclarationDigest).toBe(
  275. withoutStates.hooks[0]?.hookDeclarationDigest,
  276. );
  277. });
  278. it("入口不存在记为 missing;文件出现后 digest 变化", async () => {
  279. const workspace = makeRoot();
  280. await writeHooks(workspace, [{ type: "process", command: "sh", args: ["scripts/x.sh"] }]);
  281. const missing = await snapshotOf(workspace);
  282. expect(missing.hooks[0]?.scriptEntry).toEqual({
  283. path: "scripts/x.sh",
  284. state: { kind: "missing" },
  285. });
  286. await mkdir(join(workspace, "scripts"));
  287. await writeFile(join(workspace, "scripts", "x.sh"), "echo hi\n", "utf8");
  288. const created = await snapshotOf(workspace);
  289. expect(created.hooks[0]?.scriptEntry?.state.kind).toBe("file");
  290. expect(created.hooks[0]?.hookDeclarationDigest).not.toBe(
  291. missing.hooks[0]?.hookDeclarationDigest,
  292. );
  293. });
  294. it("未提供 scriptStates 时能识别入口的条目记为 unverifiable,不退回旧 digest", async () => {
  295. const workspace = makeRoot();
  296. await writeHooks(workspace, [{ type: "process", command: "sh", args: ["x.sh"] }]);
  297. await writeFile(join(workspace, "x.sh"), "echo hi\n", "utf8");
  298. const { sources } = await readWorkspaceHookProjectSources({ workingDirectory: workspace });
  299. const snapshot = buildWorkspaceHookBundleSnapshot({
  300. workspaceIdentity: workspace,
  301. workspacePath: workspace,
  302. sources,
  303. runtimeRoot: resolveWorkspaceHookRuntimeRoot([...sources.map((s) => s.hooks)]),
  304. })!;
  305. expect(snapshot.hooks[0]?.scriptEntry).toEqual({
  306. path: "x.sh",
  307. state: { kind: "unverifiable" },
  308. });
  309. });
  310. it("Runtime 异步入口与 Settings 公式得到同一 scriptEntry;同步 createConfig 为 unverifiable", async () => {
  311. const home = makeRoot();
  312. const workspace = makeRoot();
  313. await writeHooks(workspace, [{ type: "process", command: "node", args: ["hook.mjs"] }]);
  314. await writeFile(join(workspace, "hook.mjs"), "console.log(1)\n", "utf8");
  315. const options = {
  316. workingDirectory: workspace,
  317. userConfigPath: join(home, ".zcode", "cli", "config.json"),
  318. env: {},
  319. };
  320. const runtime = (await createConfigWithPluginMigrations(options)).sources.project
  321. .workspaceHookSnapshot!;
  322. const settings = await snapshotOf(workspace);
  323. expect(runtime.hooks[0]?.scriptEntry).toEqual(settings.hooks[0]?.scriptEntry);
  324. expect(runtime.hooks[0]?.scriptEntry?.state.kind).toBe("file");
  325. const sync = createConfig(options).sources.project.workspaceHookSnapshot!;
  326. expect(sync.hooks[0]?.scriptEntry?.state).toEqual({ kind: "unverifiable" });
  327. });
  328. });