workspace-hook-mutation.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import { open, mkdir, readFile, rename, rm } from "node:fs/promises";
  2. import { basename, dirname, resolve } from "node:path";
  3. import type { WorkspaceHookBundleSnapshotData } from "./workspace-hook-digest.js";
  4. import { createWorkspaceHookDeclarationDigest } from "./workspace-hook-digest.js";
  5. import {
  6. workspaceHooksConfigSchema,
  7. type WorkspaceHookDefinition,
  8. } from "./workspace-hook-config.js";
  9. export interface AtomicWorkspaceHookConfigWriteOptions {
  10. beforeRename?: () => void | Promise<void>;
  11. }
  12. export class WorkspaceHookMutationError extends Error {
  13. constructor(
  14. readonly code:
  15. | "workspace_hooks_snapshot_mismatch"
  16. | "workspace_hooks_bundle_changed"
  17. | "workspace_hooks_config_unreadable"
  18. | "workspace_hooks_config_write_failed",
  19. message: string,
  20. options?: ErrorOptions,
  21. ) {
  22. super(message, options);
  23. this.name = "WorkspaceHookMutationError";
  24. }
  25. }
  26. /**
  27. * Workspace Hook settings writes must never expose a partially-written config to Runtime watchers.
  28. * The temp file is written in the destination directory, flushed, closed, then atomically renamed.
  29. */
  30. export async function atomicWriteWorkspaceHookConfig(
  31. filePath: string,
  32. value: Record<string, unknown>,
  33. options: AtomicWorkspaceHookConfigWriteOptions = {},
  34. ): Promise<void> {
  35. const directory = dirname(filePath);
  36. await mkdir(directory, { recursive: true });
  37. const tempPath = resolve(
  38. directory,
  39. `.${basename(filePath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,
  40. );
  41. let handle: Awaited<ReturnType<typeof open>> | undefined;
  42. try {
  43. handle = await open(tempPath, "wx", 0o600);
  44. await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`, "utf8");
  45. await handle.sync();
  46. await handle.close();
  47. handle = undefined;
  48. await options.beforeRename?.();
  49. await rename(tempPath, filePath);
  50. } catch (error) {
  51. await handle?.close().catch(() => undefined);
  52. await rm(tempPath, { force: true }).catch(() => undefined);
  53. throw error;
  54. }
  55. }
  56. export async function writeWorkspaceHookConfiguredToggle(input: {
  57. configPath: string;
  58. snapshot: WorkspaceHookBundleSnapshotData;
  59. reviewItemId: string;
  60. enabled: boolean;
  61. writeOptions?: AtomicWorkspaceHookConfigWriteOptions;
  62. }): Promise<void> {
  63. const configPath = resolve(input.configPath);
  64. const entry = input.snapshot.hooks.find((item) => item.reviewItemId === input.reviewItemId);
  65. const source = entry ? input.snapshot.sourceFiles[entry.sourceFileIndex] : undefined;
  66. if (
  67. !entry ||
  68. !entry.editable ||
  69. !source?.editable ||
  70. source.configFileKind !== ".zcode/config.json" ||
  71. resolve(source.canonicalPath) !== configPath
  72. ) {
  73. throw mismatch("Workspace Hook toggle target is not the current editable project config");
  74. }
  75. let raw: unknown;
  76. try {
  77. raw = JSON.parse(await readFile(configPath, "utf8"));
  78. } catch (error) {
  79. // 此处是 readFile/JSON.parse 失败,不能报成 config_write_failed:
  80. // 用户据此反复重试「写入」而真实原因是配置读不出来或不是合法 JSON。
  81. throw new WorkspaceHookMutationError(
  82. "workspace_hooks_config_unreadable",
  83. "Workspace Hook config could not be read",
  84. { cause: error },
  85. );
  86. }
  87. if (!isRecord(raw)) throw mismatch("Workspace Hook config root is not an object");
  88. const parsedHooks = workspaceHooksConfigSchema.safeParse(raw.hooks);
  89. if (!parsedHooks.success) throw mismatch("Workspace Hook config no longer matches its schema");
  90. const rawHooks = raw.hooks;
  91. if (!isRecord(rawHooks)) throw mismatch("Workspace Hook config has no hooks object");
  92. const events = rawHooks.events;
  93. if (!isRecord(events)) throw mismatch("Workspace Hook config has no events object");
  94. const matchers = events[entry.event];
  95. if (!Array.isArray(matchers)) throw mismatch("Workspace Hook event no longer exists");
  96. const matcher = matchers[entry.matcherIndex];
  97. if (!isRecord(matcher) || !Array.isArray(matcher.hooks)) {
  98. throw mismatch("Workspace Hook matcher no longer exists");
  99. }
  100. const rawDeclaration = matcher.hooks[entry.hookIndex];
  101. if (!isRecord(rawDeclaration)) throw mismatch("Workspace Hook declaration no longer exists");
  102. const parsedDeclaration = getParsedDeclaration(
  103. parsedHooks.data.events?.[entry.event]?.[entry.matcherIndex]?.hooks[entry.hookIndex],
  104. );
  105. if (!parsedDeclaration) throw mismatch("Workspace Hook declaration no longer matches its schema");
  106. // 此处刻意把 entry 自身的 resolvedTimeoutMs / resolvedMaxOutputBytes 回填为 digest 的
  107. // "default",目的是校验「磁盘上的声明与 review 时所见一致」——即 source/command/event/
  108. // matcher/hookIndex 等声明本体字段在 review 之后没有被第三方改动。
  109. // 已知边界:当仅 root 级默认值(hooks.timeoutMs / hooks.maxOutputBytes)在磁盘上变化时,
  110. // entry.resolvedTimeoutMs 仍是 review 时解析到的旧值,回填后重算出的 digest 必然等于
  111. // entry.hookDeclarationDigest,因此本守卫不会捕获 root default 的变化(尽管
  112. // resolvedTimeoutMs 参与 digest 恰恰是为了让 root 变化能触发「声明变更→重新 review」)。
  113. // Admission 侧不受影响:hook 执行评估使用的是当前 snapshot,不依赖这里的 digest 比较,
  114. // 不存在提权风险。
  115. const currentDigest = createWorkspaceHookDeclarationDigest({
  116. sourceRelativePath: entry.sourceRelativePath,
  117. sourceDiscoveryOrder: source.discoveryOrder,
  118. event: entry.event,
  119. matcher: parsedHooks.data.events?.[entry.event]?.[entry.matcherIndex]?.matcher ?? null,
  120. matcherIndex: entry.matcherIndex,
  121. hookIndex: entry.hookIndex,
  122. hook: parsedDeclaration,
  123. defaultTimeoutMs: entry.resolvedTimeoutMs,
  124. resolvedMaxOutputBytes: entry.resolvedMaxOutputBytes,
  125. });
  126. if (currentDigest !== entry.hookDeclarationDigest) {
  127. throw mismatch("Workspace Hook declaration changed after review");
  128. }
  129. rawDeclaration.enabled = input.enabled;
  130. await atomicWriteWorkspaceHookConfig(configPath, raw, input.writeOptions);
  131. }
  132. function getParsedDeclaration(value: unknown): WorkspaceHookDefinition | undefined {
  133. if (!value || typeof value !== "object") return undefined;
  134. return value as WorkspaceHookDefinition;
  135. }
  136. function mismatch(message: string): WorkspaceHookMutationError {
  137. return new WorkspaceHookMutationError("workspace_hooks_snapshot_mismatch", message);
  138. }
  139. function isRecord(value: unknown): value is Record<string, unknown> {
  140. return typeof value === "object" && value !== null && !Array.isArray(value);
  141. }