code-command-recorder.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. export interface CodeCommandCall {
  4. argumentCount: number;
  5. argumentHashes: string[];
  6. }
  7. /** 只保存参数摘要,避免将错误 URI 中意外夹带的 authority/凭据写入证据。 */
  8. export async function readCodeCommandCalls(logPath: string): Promise<CodeCommandCall[]> {
  9. let text: string;
  10. try {
  11. text = await readFile(logPath, "utf8");
  12. } catch (error) {
  13. if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
  14. throw error;
  15. }
  16. return text
  17. .split("\n")
  18. .filter(Boolean)
  19. .map((line) => {
  20. const call = JSON.parse(line) as CodeCommandCall;
  21. if (
  22. !Number.isInteger(call.argumentCount) ||
  23. !Array.isArray(call.argumentHashes) ||
  24. call.argumentHashes.length !== call.argumentCount ||
  25. !call.argumentHashes.every(
  26. (hash) => typeof hash === "string" && /^[a-f0-9]{64}$/u.test(hash),
  27. )
  28. ) {
  29. throw new Error("code CLI 录制结果格式错误");
  30. }
  31. return call;
  32. });
  33. }
  34. /** macOS/Linux 的真实可执行夹具;只替代外部编辑器进程,不替代 Main 的 URI 构造。 */
  35. export async function createCodeCommandRecorder(artifactDir: string) {
  36. if (process.platform === "win32") throw new Error("Windows 需提供可执行 code.exe 录制夹具");
  37. await mkdir(artifactDir, { recursive: true });
  38. const binDir = await mkdtemp(join(artifactDir, "editor-cli-"));
  39. const commandPath = join(binDir, "code");
  40. const scriptPath = join(binDir, "record.cjs");
  41. const logPath = join(binDir, "code-calls.jsonl");
  42. await writeFile(
  43. scriptPath,
  44. [
  45. 'const { appendFile } = require("node:fs/promises");',
  46. 'const { createHash } = require("node:crypto");',
  47. "const args = process.argv.slice(2);",
  48. 'const call = { argumentCount: args.length, argumentHashes: args.map(value => createHash("sha256").update(value).digest("hex")) };',
  49. `appendFile(${JSON.stringify(logPath)}, JSON.stringify(call) + "\\n", { mode: 0o600 }).catch(error => { console.error(error.message); process.exitCode = 1; });`,
  50. ].join("\n"),
  51. { mode: 0o600 },
  52. );
  53. const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
  54. await writeFile(
  55. commandPath,
  56. `#!/bin/sh\nunset NODE_OPTIONS\nexec ${quote(process.execPath)} ${quote(scriptPath)} "$@"\n`,
  57. { mode: 0o755 },
  58. );
  59. return { binDir, commandPath, logPath, readCalls: () => readCodeCommandCalls(logPath) };
  60. }