hooksService.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import type { ServiceLogger } from "../src/logger/serviceLogger.js";
  6. const originalHome = process.env.HOME;
  7. const tempRoots: string[] = [];
  8. function makeTempRoot(): string {
  9. const root = mkdtempSync(join(tmpdir(), "zcode-hooks-"));
  10. tempRoots.push(root);
  11. return root;
  12. }
  13. async function createHooksServiceInEnv(home: string, options?: { logger?: ServiceLogger }) {
  14. process.env.HOME = home;
  15. vi.resetModules();
  16. const mod = await import("../src/hooks/hooksService.js");
  17. return mod.createHooksService(options);
  18. }
  19. afterEach(() => {
  20. process.env.HOME = originalHome;
  21. vi.resetModules();
  22. while (tempRoots.length > 0) {
  23. const root = tempRoots.pop();
  24. if (root) {
  25. rmSync(root, { recursive: true, force: true });
  26. }
  27. }
  28. });
  29. describe("hooksService", () => {
  30. it("loads hooks from workspace directories before user directories", async () => {
  31. const home = makeTempRoot();
  32. const workspacePath = join(makeTempRoot(), "workspace");
  33. mkdirSync(join(home, ".zcode", "cli"), { recursive: true });
  34. mkdirSync(join(home, ".agents"), { recursive: true });
  35. mkdirSync(join(home, ".claude"), { recursive: true });
  36. mkdirSync(join(workspacePath, ".zcode"), { recursive: true });
  37. mkdirSync(join(workspacePath, ".agents"), { recursive: true });
  38. mkdirSync(join(workspacePath, ".claude"), { recursive: true });
  39. writeFileSync(
  40. join(home, ".zcode", "cli", "config.json"),
  41. JSON.stringify({
  42. hooks: {
  43. enabled: true,
  44. events: {
  45. SessionStart: [
  46. {
  47. matcher: "startup",
  48. hooks: [
  49. { type: "process", command: "node", args: ["user-zcode.mjs"], customFlag: true },
  50. ],
  51. },
  52. ],
  53. },
  54. },
  55. }),
  56. "utf-8",
  57. );
  58. writeFileSync(
  59. join(workspacePath, ".zcode", "config.json"),
  60. JSON.stringify({
  61. hooks: {
  62. enabled: true,
  63. events: {
  64. PreToolUse: [
  65. {
  66. matcher: "Bash",
  67. hooks: [
  68. {
  69. type: "process",
  70. command: "node",
  71. args: ["project-zcode.mjs"],
  72. timeoutMs: 5000,
  73. },
  74. ],
  75. },
  76. ],
  77. },
  78. },
  79. }),
  80. "utf-8",
  81. );
  82. writeFileSync(
  83. join(home, ".agents", "settings.json"),
  84. JSON.stringify({
  85. hooks: {
  86. Stop: [{ hooks: [{ type: "command", command: "echo agents" }] }],
  87. },
  88. }),
  89. "utf-8",
  90. );
  91. writeFileSync(
  92. join(workspacePath, ".claude", "settings.json"),
  93. JSON.stringify({
  94. hooks: {
  95. PostToolUse: [{ matcher: "Write", hooks: [{ type: "command", command: "echo claude" }] }],
  96. },
  97. }),
  98. "utf-8",
  99. );
  100. const service = await createHooksServiceInEnv(home);
  101. const result = await service.loadHooks({ workspacePath });
  102. expect(result.hooksEnabled).toBe(true);
  103. expect(
  104. result.hooks.map(
  105. (hook) => `${hook.location?.source}:${hook.location?.scope}:${hook.command}`,
  106. ),
  107. ).toEqual([
  108. "zcode:project:node",
  109. "claude:project:echo claude",
  110. "zcode:user:node",
  111. "agents:user:echo agents",
  112. ]);
  113. expect(result.hooks[0]).toEqual(expect.objectContaining({ timeout: 5 }));
  114. expect(result.hooks[0]?.location?.directoryPath).toBe(join(workspacePath, ".zcode"));
  115. expect(result.hooks[2]).toEqual(
  116. expect.objectContaining({ args: ["user-zcode.mjs"], custom: { customFlag: true } }),
  117. );
  118. });
  119. it("keeps identical user and project hooks as separate source records", async () => {
  120. const home = makeTempRoot();
  121. const workspacePath = join(makeTempRoot(), "workspace");
  122. const hookConfig = {
  123. hooks: {
  124. enabled: true,
  125. events: {
  126. Stop: [{ hooks: [{ type: "command", command: "echo verify" }] }],
  127. },
  128. },
  129. };
  130. mkdirSync(join(home, ".zcode", "cli"), { recursive: true });
  131. mkdirSync(join(workspacePath, ".zcode"), { recursive: true });
  132. writeFileSync(join(home, ".zcode", "cli", "config.json"), JSON.stringify(hookConfig), "utf-8");
  133. writeFileSync(
  134. join(workspacePath, ".zcode", "config.json"),
  135. JSON.stringify(hookConfig),
  136. "utf-8",
  137. );
  138. const service = await createHooksServiceInEnv(home);
  139. const result = await service.loadHooks({ workspacePath });
  140. expect(result.hooks).toHaveLength(2);
  141. expect(result.hooks.map((hook) => hook.location?.scope)).toEqual(["project", "user"]);
  142. });
  143. it("saves zcode hooks to user and workspace config files", async () => {
  144. const home = makeTempRoot();
  145. const workspacePath = join(makeTempRoot(), "workspace");
  146. mkdirSync(join(home, ".zcode", "cli"), { recursive: true });
  147. writeFileSync(
  148. join(home, ".zcode", "cli", "config.json"),
  149. JSON.stringify({ features: { mcp: true } }),
  150. "utf-8",
  151. );
  152. const service = await createHooksServiceInEnv(home);
  153. await service.saveHooks({
  154. workspacePath,
  155. hooks: [
  156. {
  157. id: "keep-user",
  158. event: "Stop",
  159. type: "process",
  160. command: "node",
  161. args: ["stop.mjs"],
  162. enabled: true,
  163. custom: { extra: "user" },
  164. location: {
  165. source: "zcode",
  166. scope: "user",
  167. directoryPath: join(home, ".zcode", "cli"),
  168. },
  169. },
  170. {
  171. id: "keep-project",
  172. event: "PreToolUse",
  173. type: "process",
  174. command: "node",
  175. enabled: true,
  176. location: {
  177. source: "zcode",
  178. scope: "project",
  179. directoryPath: join(workspacePath, ".zcode"),
  180. projectPath: workspacePath,
  181. },
  182. },
  183. {
  184. id: "skip-agents",
  185. event: "Stop",
  186. type: "command",
  187. command: "echo agents",
  188. enabled: true,
  189. location: {
  190. source: "agents",
  191. scope: "user",
  192. directoryPath: join(home, ".agents"),
  193. },
  194. },
  195. ],
  196. });
  197. const saved = JSON.parse(readFileSync(join(home, ".zcode", "cli", "config.json"), "utf-8"));
  198. expect(saved.features).toEqual({ mcp: true });
  199. expect(saved.hooks.events.Stop).toEqual([
  200. {
  201. hooks: [
  202. { type: "process", command: "node", args: ["stop.mjs"], enabled: true, extra: "user" },
  203. ],
  204. },
  205. ]);
  206. expect(saved.hooks.events.PreToolUse).toBeUndefined();
  207. const projectSaved = JSON.parse(
  208. readFileSync(join(workspacePath, ".zcode", "config.json"), "utf-8"),
  209. );
  210. expect(projectSaved.hooks.events.PreToolUse).toEqual([
  211. {
  212. hooks: [{ type: "process", command: "node", enabled: true }],
  213. },
  214. ]);
  215. });
  216. it("round-trips command hooks with async and shell fields", async () => {
  217. const home = makeTempRoot();
  218. const workspacePath = join(makeTempRoot(), "workspace");
  219. const service = await createHooksServiceInEnv(home);
  220. await service.saveHooks({
  221. workspacePath,
  222. hooks: [
  223. {
  224. id: "command-hook",
  225. event: "SessionStart",
  226. matcher: "startup",
  227. type: "command",
  228. command: "./hooks/session-start.sh",
  229. async: true,
  230. shell: "bash",
  231. statusMessage: "Preparing workspace",
  232. timeout: 12,
  233. enabled: true,
  234. location: {
  235. source: "zcode",
  236. scope: "project",
  237. directoryPath: join(workspacePath, ".zcode"),
  238. projectPath: workspacePath,
  239. },
  240. },
  241. ],
  242. });
  243. const loaded = await service.loadHooks({ workspacePath });
  244. expect(loaded.hooks[0]).toMatchObject({
  245. type: "command",
  246. async: true,
  247. shell: "bash",
  248. statusMessage: "Preparing workspace",
  249. timeout: 12,
  250. enabled: true,
  251. });
  252. });
  253. it("persists a disabled hook in the runtime-readable project config", async () => {
  254. const home = makeTempRoot();
  255. const workspacePath = join(makeTempRoot(), "workspace");
  256. mkdirSync(join(workspacePath, ".zcode"), { recursive: true });
  257. writeFileSync(
  258. join(workspacePath, ".zcode", "config.json"),
  259. JSON.stringify({
  260. hooks: {
  261. enabled: true,
  262. events: {
  263. PreToolUse: [
  264. {
  265. matcher: "Bash",
  266. hooks: [{ type: "process", command: "node", args: ["hook.mjs"] }],
  267. },
  268. ],
  269. },
  270. },
  271. }),
  272. "utf-8",
  273. );
  274. const service = await createHooksServiceInEnv(home);
  275. const initial = await service.loadHooks({ workspacePath });
  276. const hook = initial.hooks[0];
  277. expect(hook).toBeDefined();
  278. await service.saveHooks({
  279. workspacePath,
  280. hooks: initial.hooks.map((item) =>
  281. item.id === hook!.id ? { ...item, enabled: false } : item,
  282. ),
  283. });
  284. const saved = JSON.parse(readFileSync(join(workspacePath, ".zcode", "config.json"), "utf-8"));
  285. expect(saved.hooks.events.PreToolUse[0].hooks[0]).toMatchObject({
  286. type: "process",
  287. command: "node",
  288. args: ["hook.mjs"],
  289. enabled: false,
  290. });
  291. const disabled = await service.loadHooks({ workspacePath });
  292. expect(disabled.hooks[0]).toEqual(expect.objectContaining({ enabled: false }));
  293. expect(disabled.hooksEnabled).toBe(false);
  294. });
  295. it("trust store 不可读时使用可注入 service logger 并保持 fail closed", async () => {
  296. const home = makeTempRoot();
  297. const workspacePath = join(makeTempRoot(), "workspace");
  298. mkdirSync(join(workspacePath, ".zcode"), { recursive: true });
  299. // 修复原因:CR-01 后非法 JSON(如 "{broken")统一走 schema 解析分支(文案"结构不符合
  300. // schema",已由 workspaceHookTrustCorrupt.test.ts 覆盖);本用例验证的是 IO 不可读分支,
  301. // 因此用目录占位 trust store 路径——readFile 对目录稳定返回 EISDIR/EPERM(非 ENOENT),
  302. // 在 macOS/Linux/Windows 上都能触发"不可读"日志分支。
  303. mkdirSync(join(home, ".zcode", "security", "workspace-hook-trust-v1.json"), {
  304. recursive: true,
  305. });
  306. writeFileSync(
  307. join(workspacePath, ".zcode", "config.json"),
  308. JSON.stringify({
  309. hooks: {
  310. enabled: true,
  311. events: {
  312. SessionStart: [{ hooks: [{ type: "command", command: "echo untrusted" }] }],
  313. },
  314. },
  315. }),
  316. "utf-8",
  317. );
  318. const logger = {
  319. debug: vi.fn(),
  320. info: vi.fn(),
  321. warn: vi.fn(),
  322. error: vi.fn(),
  323. };
  324. const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  325. try {
  326. const service = await createHooksServiceInEnv(home, { logger });
  327. const result = await service.loadHooks({ workspacePath });
  328. expect(result.trustStoreCorrupt).toBe(true);
  329. expect(result.hooks[0]?.workspaceHook?.trustState).not.toBe("trusted_persistent");
  330. expect(logger.warn).toHaveBeenCalledWith(
  331. undefined,
  332. "Workspace Hook Trust store 不可读,已 fail-closed 忽略全部持久信任记录",
  333. expect.objectContaining({ path: expect.stringContaining("workspace-hook-trust-v1.json") }),
  334. );
  335. expect(consoleWarn).not.toHaveBeenCalled();
  336. } finally {
  337. consoleWarn.mockRestore();
  338. }
  339. });
  340. });