hooksService.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. import { existsSync, 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("Source user scope does not read or write the anchor workspace config", async () => {
  217. const home = makeTempRoot();
  218. const anchorPath = join(makeTempRoot(), "source-user-anchor");
  219. mkdirSync(join(anchorPath, ".zcode"), { recursive: true });
  220. writeFileSync(
  221. join(anchorPath, ".zcode", "config.json"),
  222. JSON.stringify({
  223. hooks: {
  224. events: { Stop: [{ hooks: [{ type: "command", command: "echo project" }] }] },
  225. },
  226. }),
  227. "utf-8",
  228. );
  229. const service = await createHooksServiceInEnv(home);
  230. const before = readFileSync(join(anchorPath, ".zcode", "config.json"), "utf-8");
  231. await service.saveHooks({
  232. workspacePath: anchorPath,
  233. scope: "user",
  234. hooks: [
  235. {
  236. id: "user-only",
  237. event: "Stop",
  238. type: "command",
  239. command: "echo user",
  240. enabled: true,
  241. location: { source: "zcode", scope: "user", directoryPath: "" },
  242. },
  243. ],
  244. });
  245. const loaded = await service.loadHooks({ workspacePath: anchorPath, scope: "user" });
  246. expect(readFileSync(join(anchorPath, ".zcode", "config.json"), "utf-8")).toBe(before);
  247. expect(existsSync(join(home, ".zcode", "cli", "config.json"))).toBe(true);
  248. expect(loaded.hooks.map((hook) => hook.command)).toEqual(["echo user"]);
  249. });
  250. it("round-trips command hooks with async and shell fields", async () => {
  251. const home = makeTempRoot();
  252. const workspacePath = join(makeTempRoot(), "workspace");
  253. const service = await createHooksServiceInEnv(home);
  254. await service.saveHooks({
  255. workspacePath,
  256. hooks: [
  257. {
  258. id: "command-hook",
  259. event: "SessionStart",
  260. matcher: "startup",
  261. type: "command",
  262. command: "./hooks/session-start.sh",
  263. async: true,
  264. shell: "bash",
  265. statusMessage: "Preparing workspace",
  266. timeout: 12,
  267. enabled: true,
  268. location: {
  269. source: "zcode",
  270. scope: "project",
  271. directoryPath: join(workspacePath, ".zcode"),
  272. projectPath: workspacePath,
  273. },
  274. },
  275. ],
  276. });
  277. const loaded = await service.loadHooks({ workspacePath });
  278. expect(loaded.hooks[0]).toMatchObject({
  279. type: "command",
  280. async: true,
  281. shell: "bash",
  282. statusMessage: "Preparing workspace",
  283. timeout: 12,
  284. enabled: true,
  285. });
  286. });
  287. it("persists a disabled hook in the runtime-readable project config", async () => {
  288. const home = makeTempRoot();
  289. const workspacePath = join(makeTempRoot(), "workspace");
  290. mkdirSync(join(workspacePath, ".zcode"), { recursive: true });
  291. writeFileSync(
  292. join(workspacePath, ".zcode", "config.json"),
  293. JSON.stringify({
  294. hooks: {
  295. enabled: true,
  296. events: {
  297. PreToolUse: [
  298. {
  299. matcher: "Bash",
  300. hooks: [{ type: "process", command: "node", args: ["hook.mjs"] }],
  301. },
  302. ],
  303. },
  304. },
  305. }),
  306. "utf-8",
  307. );
  308. const service = await createHooksServiceInEnv(home);
  309. const initial = await service.loadHooks({ workspacePath });
  310. const hook = initial.hooks[0];
  311. expect(hook).toBeDefined();
  312. await service.saveHooks({
  313. workspacePath,
  314. hooks: initial.hooks.map((item) =>
  315. item.id === hook!.id ? { ...item, enabled: false } : item,
  316. ),
  317. });
  318. const saved = JSON.parse(readFileSync(join(workspacePath, ".zcode", "config.json"), "utf-8"));
  319. expect(saved.hooks.events.PreToolUse[0].hooks[0]).toMatchObject({
  320. type: "process",
  321. command: "node",
  322. args: ["hook.mjs"],
  323. enabled: false,
  324. });
  325. const disabled = await service.loadHooks({ workspacePath });
  326. expect(disabled.hooks[0]).toEqual(expect.objectContaining({ enabled: false }));
  327. expect(disabled.hooksEnabled).toBe(false);
  328. });
  329. it("trust store 不可读时使用可注入 service logger 并保持 fail closed", async () => {
  330. const home = makeTempRoot();
  331. const workspacePath = join(makeTempRoot(), "workspace");
  332. mkdirSync(join(workspacePath, ".zcode"), { recursive: true });
  333. // 修复原因:CR-01 后非法 JSON(如 "{broken")统一走 schema 解析分支(文案"结构不符合
  334. // schema",已由 workspaceHookTrustCorrupt.test.ts 覆盖);本用例验证的是 IO 不可读分支,
  335. // 因此用目录占位 trust store 路径——readFile 对目录稳定返回 EISDIR/EPERM(非 ENOENT),
  336. // 在 macOS/Linux/Windows 上都能触发"不可读"日志分支。
  337. mkdirSync(join(home, ".zcode", "security", "workspace-hook-trust-v1.json"), {
  338. recursive: true,
  339. });
  340. writeFileSync(
  341. join(workspacePath, ".zcode", "config.json"),
  342. JSON.stringify({
  343. hooks: {
  344. enabled: true,
  345. events: {
  346. SessionStart: [{ hooks: [{ type: "command", command: "echo untrusted" }] }],
  347. },
  348. },
  349. }),
  350. "utf-8",
  351. );
  352. const logger = {
  353. debug: vi.fn(),
  354. info: vi.fn(),
  355. warn: vi.fn(),
  356. error: vi.fn(),
  357. };
  358. const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  359. try {
  360. const service = await createHooksServiceInEnv(home, { logger });
  361. const result = await service.loadHooks({ workspacePath });
  362. expect(result.trustStoreCorrupt).toBe(true);
  363. expect(result.hooks[0]?.workspaceHook?.trustState).not.toBe("trusted_persistent");
  364. expect(logger.warn).toHaveBeenCalledWith(
  365. undefined,
  366. "Workspace Hook Trust store 不可读,已 fail-closed 忽略全部持久信任记录",
  367. expect.objectContaining({ path: expect.stringContaining("workspace-hook-trust-v1.json") }),
  368. );
  369. expect(consoleWarn).not.toHaveBeenCalled();
  370. } finally {
  371. consoleWarn.mockRestore();
  372. }
  373. });
  374. });